Git tip: squash intermediate commits
Often we write a lot of intermediate commit messages on a task where only one or two commits would be sufficient. Take the following example:
5596df4 FE: Fix layout for mobile --- newer commit ---
5596df4 FE: More style adjustments
13c4c41 FE: Adjust margins
3f4b0ce Bug: Fix typo
**a63d5af** Task: Create feature X --- initial commit ---
b32af23 FE: Create banner
17daeff Bug: Fix this
...
Note that all commits since a63d5af
(the initial commit) are small changes that relate directly with Create feature X task*.* These are the intermediate commits, and in the example above we want to combine them into single commit. So, today we are going to cover the basics of squashing intermediate commits into single one using the git rebase --interactive
command.
Merge commits
To merge the commits you can either pass the number of commits you want to merge or use hash of the commit you want to rewrite from.
Use git rebase --interactive HEAD~N
to merge a number of commits, where N
is the number of commits starting from the most recent, so for example to merge the 5 newest commits you do:
$ git rebase --interactive HEAD~5
Or, use git rebase --interactive [commit-hash]
to merge all commits above the given commit hash. Note the commit-hash
is the hash of the commit just before the first one you want to rewrite from, in our example is b32af23
.
5596df4 FE: Fix layout for mobile --- newer commit ---
5596df4 FE: More style adjustments
13c4c41 FE: Adjust margins
3f4b0ce Bug: Fix typo
**a63d5af** Task: Create feature X --- initial commit ---
b32af23 FE: Create banner --- ⬆️ merge all commits above this ⬆️ ---
...
Like this:
$ git rebase --interactive b32af23
The squash
Next, your editor should pop up, showing a few options to squash the commits. Note the commits are in reverse order the top being one the initial commit.
You mark a commit as squashable by changing the word pick
into squash
, as follows:
pick a63d5af Task: Create feature X --- initial commit ---
squash 3f4b0ce Bug: Fix typo
squash 13c4c41 FE: Adjust margins
squash 5596df4 FE: More style adjustments
squash 5596df4 FE: Fix layout for mobile --- newer commit ---
Save the file and close the editor.
Git will squash those commits after one last commit. The editor should pop up one last time for the squash commit. This will be filled with all the commits messages you have squashed, this might be useful for future reference, but they can be removed.
Task: The new Feature X --- the new squash commit ---
FE: Fix layout for mobile --- the old intermediate commits ---
FE: More style adjustments
FE: Adjust margins
Bug: Fix typo
Task: Create feature X
Let me know if you found this article useful, if it could be improved or if you have any other suggestions.
-
João Augusto
A big football, photography and Apple fan - our front-end developer João has not only got the eye for making our websites sparkle, he’s got to have the latest, greatest gear to do it on. @joaoeaugusto