Instead of merging other branches into yours, git’s rebase command can reapply your changes onto another branch.
Let’s say you’re working on a feature branch called
feature/login, which is
based on the main
develop branch. While working in your branch, somebody else
pushes some commits to
develop. How would you get these commits into your
develop branch back into yours would result in a merge commit in
your branch. Merge commits are typically reserved for merging branches back
upstream. Another option is to cherry-pick the commits. This works, but you’d
duplicate commits already in the
develop branch into yours, which can cause
issues when merging your feature branch upstream later.
Git’s rebase command allows you to temporarily rewind the commits you did in this branch, pull in everything from another branch and apply your commits on top of that again.
$ git rebase develop First, rewinding head to replay your work on top of it... Fast-forwarded feature/login to develop.
It’s as if you didn’t start working in the
feature/login branch before the
commits you pulled in were made. You can also
rebase so you don’t have to switch out of your current branch.
Conflicts served in smaller chunks
Besides keeping your history clean, rebase also has your back when you run into a merge conflict during the rebase:
$ git rebase develop First, rewinding head to replay your work on top of it... Applying: feature/login Using index info to reconstruct a base tree... Falling back to patching base and 3-way merge... Auto-merging config/environment.rb CONFLICT (content): Merge conflict in config/environment.rb Failed to merge in the changes. Patch failed at 0001 feature/login When you have resolved this problem run "git rebase --continue". If you would prefer to skip this patch, instead run "git rebase --skip". To restore the original branch and stop rebasing run "git rebase --abort".
Because rebase merges every commit individually, conflicts will be served in
smaller chunks making them easier to fix and understand. When you’re done
fixing a conflict, simply
git add the file and continue rebasing:
$ git rebase --continue
Rebase vs Merge
When you’re working on a feature branch and you need changes from the main development branch, I would suggest using rebase. Merge can be used when you want to merge a feature branch back into your development branch. That way, you’ll be able to see when you merged in what in the future because you have that merge commit I called “nasty” before. It isn’t, really.
What I would like to ask you is to rebase your feature branch to the main development branch before merging it in. This way you make sure your branch applies cleanly to the branch you’re merging into.