10 September 2013

error: failed to push some refs to '[email protected]:joallard/foo'

So, you’ve merged the master branch with itself, and you ended up with a merge commit nobody wanted.

The problem

Let me tell you a little story…

John and Pete are working together on a repo.

$ git log --graph --pretty=oneline --abbrev-commit  # an alias I have under 'git lol', but 'gitk' does just fine
* 812492b (master, origin/master, origin/HEAD) Add stuff
* 474c16e I am many things
* 12b7661 I am a Unicorn!

Pete wants to make some changes, and clones the repo/pulls those changes. He gets the same history.

Meanwhile, Jon continues working, building on top of that, and pushes his changes. Pete also makes some changes, without pulling first.

* 1c12c15 (HEAD, master) 123
* 8ee7d24 Do stuff
* d4f7393 Woo
* 812492b (origin/master, origin/HEAD) Add stuff
* 474c16e I am many things
* 12b7661 I am a Unicorn!

When comes the time to push…

$ git push
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to '/home/jon/dev3/foo'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

And so, he does what instructed. He pulls (and thus gets the status of origin)

$ git pull origin master
 * branch            master     -> FETCH_HEAD
Already up-to-date!
Merge made by the 'recursive' strategy.

*   1654d53 (HEAD, master) Merge branch 'master' of /home/jon/dev3/foo
|\\  
| * 57b81dc (origin/master, origin/HEAD) Blah
| * 1794a9f Do other stuff
| * a235abc Correct more
* | 1c12c15 123
* | 8ee7d24 Do stuff
* | d4f7393 Woo
|/  
* 812492b Add stuff
* 474c16e I am many things
* 12b7661 I am a Unicorn!

Git suggests merging, and an ugly merge commit is born.

Explanation

Because Pete didn’t pull the changes before committing, he committed on top of an old commit (812492b), one which Jon had already built upon. Indeed, Jon built a235abc, 1794a9f, etc. on top of it.

If Pete had pulled before committing, his master branch would’ve been updated to 57b81dc, and instead of on 812492b, d4f7393 would’ve been built on top of that (bearing another commit SHA).