Scenario: You are working with a branch that isn't yours, and you attempt to push it. It's rejected. Naturally you pull. However, Git prompts you for a commit message, and you are mildly confused.

What happened is your local copy of the branch isn't up-to-date with the remote copy. To get it up to speed, Git automatically merges the remote into the local, resulting in an extraneous commit.

You need to take the remote branch in its entirety, then reapply your changes to it. Here's how:

  1. Abort the merge commit. If you're in an editor, clear all contents and quit. Git will cancel the commit.
  2. Move your out-of-date branch to a temporary local branch.

    git checkout -b temp
    
  3. Switch back to the base branch and overwrite it with the remote version.

    git checkout -
    git reset --hard <name of the origin>/<name of the base branch>
    
  4. Switch back to your temporary branch and rebase it on the newly updated remote branch. It's good to always rebase interactively (-i) so it's clear which commits you're replaying on top of the base. You may need to resolve conflicts at this point, as well.

    git checkout -
    git rebase -i <name of the base branch>
    
  5. Switch back to the base branch and merge your temporary branch into the base.

    git checkout -
    git merge temp
    
  6. Nuke the temporary branch.

    git branch -D temp
    

You now have reapplied your commit(s) to the branch cleanly.

More blog posts