For everything you need to know about version control, check out Version control – Everything you need to know, on Programming Duck.
A good workflow when using version control is the following:
- Commit early and often.
- Clean and rewrite your local branch history as often as you want.
- Push to the remote after you’ve finished your work. Then, don’t rewrite your branch history any more (because you shouldn’t rewrite the history of remote branches).
Committing often is very useful. It’s useful to commit every time you write code that you want to keep. You can even use temporary commits with messages such as "wip" (work in progress).
That way, if you make more changes that you don’t want to keep, you can hard reset back to an earlier commit. Since you commit often, you’ll only lose the changes you made in the last few minutes. Most likely, those are exclusively the changes that you wanted to throw away.
On the other hand, if you commit infrequently, then you can’t just hard reset. You would lose a significant amount of work. Instead, you’ll have to manually and carefully fix your code until it works again. This is much more error prone and time-consuming than just resetting back to the working version from 2 minutes ago.
Also, you can clean and structure your branch’s history any time you want.
At the very least, you should ensure that your commits are clean and well-structured before you push.
Here are some commands you can use to clean the commit history of your branch:
git rebase --interactive. This command can rewrite the entire history of your branch. For more information on using this command, see the git rebase tutorial by Atlassian.
git commit --amend. This command modifies your last commit instead of creating a new one.
git commit --fixup hash-number. This command creates a new commit but flags it for "fixup" with the commit with the hash "hash-number". For more information on this command, please see auto-squashing git commits by thoughtbot.
For more details on commands for rewriting history, please see the rewriting history tutorial by Atlassian.
Finally, after your work on the branch is done, push to the remote once.
It’s important to not push again after rewriting your branch’s history, so that you don’t overwrite the history of the remote. This is explained more in Branches (version control) – The ultimate guide.
That’s it for this article.
If you have any feedback, or even counter-arguments, please let me know in the comments.
Next, if you want to know more about version control, please see the article Version control – Everything you need to know.