Merge strategies: merge vs. squash vs. rebase¶
I use git merge
, git merge squash
and git rebase
depending on the situation. They all have their merits, but their use depends
very much on the context.
git merge
adds a new commit when the branches are merged.
This has the advantage that it best represents the true history. You can see the merge and all the WIP commits that were run during development. If necessary, you can simply undo the merge with
git revert -m|--mainline 1|2 MERGE-COMMIT_SHA
.-m 1
takes you back to the behaviour of the parent element from the branch to which you have applied the changes.
-m 2
takes you back to the behaviour of the parent element from the branch from which you have applied the changes.
Tip
More commits also make git bisect better, as long as a build can be created for each commit. With a hundred or at most a thousand lines that have changed, I still have a chance of finding the bug in a reasonable amount of time.
See also
git merge --squash
allows you to merge all changes from a branch into a single commit above the current branch.
This is useful if you have many small WIP commits that are really all aimed at one feature. When squashing, I make sure to rewrite the commit message so that it is as meaningful as possible. The usual squash commit message created by Git, GitLab etc. is usually not sufficient and simply adds all squash commit messages together, possibly a series of WIP commit messages.
git rebase
moves a sequence of commits to a new base commit. With
git rebase
, the advantage to find a bug quickly using git bisect remains. In addition, however, it is now easier to recognise the context in which the bug occurred.Tip
With a large diff and many WIP commits,
git rebase
can be used interactively to selectively choose commits for the squash option and rearrange the commits. However, it only does one thing at a time:merge commits with the
squash
option orchange the order of the commits or
edit the commits.
Do not try to make all changes at once.
Tip
If you don’t feel safe with
git rebase
, then don’t do it! You can usegit merge
orgit commit --amend
instead.