Git rebase vs merge
1. Merge
Given two branches master
and feature
, merging feature
into master
will create a commit that will be the descendent of both branches, thus capturing all the changes made in both branches. This commit will set at the tip of master
. If the tip of feature
is a linear descendent of the tip of master
, then this is called a fast forward merge, since the histories of the branches do not diverge, feature
can be seen as a continuation of master
history.
1.1. Example
----Before--- master | A--B--C--D \ \ E--F--G | feature ----After---- master | A--B--C--D----H \ / \ / E--F--G | feature
1.2. Example of a fast forward merge
----Before--- master | A--B--C--D \ \ E--F--G | feature ----After---- A--B--C--D----H \ \ E--F--G | feature, master
2. Rebase
In contrast, given feature
and master
, rebase
will re-write the commits of feature
as if they had started from the tip of master. Think of feature
as containing some diffs. Then, rebase
applies those diffs starting at the tip of master
2.1. Important notes
You can mess about all you want in your local version of feature
. rebase
let's you re-write history, squash commits together, etc. But you should only do this on your local version. Once it's pushed, you should use revert
to undo anything you might want to undo.
2.2. Example
----Before--- master | A--B--C--D \ \ E--F--G | feature ----After---- master | A--B--C--D \ \ E'--F'--G' | feature
3. Re-writing history
You can use rebase -i
to edit previous commits. You can use git commit --amend
to change the last commit, e.g. to add a file you forgot or change the commit message.