Git Pull Causes a Merge

If you type git pull and expect a fast-forward update, but get a merge instead, don’t panic! This usually happens when we’re collaborating on a branch with other people, and we’ve made changes on our local version of a branch, and someone else (or the other you, if you use git to sync between multiple dev platforms) has made changes to the remote version of a branch in the meantime. It also happens really frequently in teams where all commits are to the master branch … yet another reason to have a decent branching strategy.

All that’s happened is something like this:

$ git log --oneline --all --graph --decorate
* 054f163 (HEAD, branch1) Installation instructions for the application
| * 0ce808c (origin/branch1) Fixing template layout
|/  
* 927aad9 A random change of 731 to ideas2.txt

Since the last common commit, there are commits on your local branch, and the remote one. You could just let the merge go ahead but there are other options. You could also check out a new branch at this point, reset your tracking branch to the right place and then reapply your changes using cherry-pick or by rebasing and then fast-forward merging your branch.

In fact, git has an inbuilt command that does the last of those options: rebases your local branch against the remote branch. So in this case, working on branch1:

git pull

becomes

git pull --rebase

And voila! Your changes look as if they just happened, crucially after the ones from the remote branch, and at this point you can safely push your changes up to the remote.

Note that if you have a branch that should always defer to upstream changes (the master branch on your fork of a project is a prime example) then you can configure it to always use --rebase when you run git pull. To do so, set the config option for branch.master.rebase:

git config --local branch.master.rebase true

If you’re seeing this scenario often then this may indicate a confusing branching strategy but hopefully this example shows you how you can quickly recover and get on with your work.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.