git tree at default when we have not merged nor rebased:
we get by rebasing:
So, when to 'git rebase' instead of 'git merge'?
It's simple, with rebase you say to use another branch as the new base for your work so...
If you have for example a branch master and you create a branch to implement a new feature, say you name it cool-feature, of course the master branch is the base for your new feature.
Now at a certain point you want to add the new feature you implemented in the master branch. You could just switch to master and merge the cool-feature branch:
$git checkout master
$git merge cool-feature
but this way a new dummy commit is added, if you want to avoid spaghetti-history and of course be sexier you can rebase:
$git checkout master
$git rebase cool-feature
Alternatively if you want to resolve conflicts in your topic branch as VonC suggested you can rebase you branch this way:
$git checkout cool-feature
$git rebase master
and then merge it in master:
$git checkout master
$git merge cool-feature
This time, since the topic branch has the same commits of master plus the commits with the new feature, the merge will be just a fast-forward!
What happens with the conflicts in 'git rebase' vs 'git merge'?
"Conflicts" mean "parallel evolutions of a same content". So if it goes "all to hell" during a merge, it means you have massive evolutions on the same set of files.
The reason why a rebase is then better than a merge is that:
-
You rewrite your local commit history with the one of the master (and then reapply your work, resolving any conflict then) the final merge will certainly be a "fast forward" one, because it will have all the commit history of the master, plus only your changes to reapply. Therefore the correct workflow in that case (evolutions on common set of files) is rebase first, then merge.
-
However, that means that, if you push your local branch (for backup reason), that branch should not be pulled (or at least used) by anyone else (since the commit history will be rewritten by the successive rebase).