Git: Should I merge or rebase my feature branch?
Preserving history
Merging and rebasing are two strategies for incorporating changes from one branch into another. Supposing two branches, master and feature, Git preserves the commit history of feature on master differently depending on the strategy you choose.
Merging gives feature work substance. Git memorializes the origin of commits from feature and commemorates the final merge with a dedicated “merge commit”. By contrast, rebasing keeps your commit history on master linear and therefore more searchable.
Merge demo
The following sequence of commands adds some commits to master, creates a branch feature, then merges feature into master. The resulting graph shows how Git preserves the work done on feature.
echo 1 > main.txtgit add main.txtgit commit -m "1"echo 2 > main.txtgit commit -am "2"git checkout -b featureecho 3 > feature.txtgit add feature.txtgit commit -m "3"git checkout -echo 4 > main.txtgit commit -am "4"git merge feature --no-editecho 5 > main.txtgit commit -am "5"git log --graph --pretty=oneline --abbrev-commit* aedc5d2 5* ca52804 Merge branch 'feature'|\| * 05b86ef 3* | 593c8c0 4|/* fb9a721 2* cbfa685 1
Rebase demo
The only difference in the following sequence of commands is rebasing feature on top of master. The resulting graph is a straight line with no mention of feature.
echo 1 > main.txtgit add main.txtgit commit -m "1"echo 2 > main.txtgit commit -am "2"git checkout -b featureecho 3 > feature.txtgit add feature.txtgit commit -m "3"git checkout -echo 4 > main.txtgit commit -am "4"git rebase featureecho 5 > main.txtgit commit -am "5"git log --graph --pretty=oneline --abbrev-commit* 824e964 5* 5164ca2 4* 4905a5f 3* f0b3d04 2* 2d84cee 1
Conclusion
Both merging and rebasing involve different workflows for resolving code conflicts and working with collaborators. Before diving into the particulars of each strategy, decide if your team prefers the searchability of rebasing or the heft of merging.