Handling merge conflicts with git

Like a similar post for Mercurial, this tip tries to document a list of systematic steps to handle merge conflicts with git.

  1. List the conflict status (first column = ours, second column = theirs):
    git status -s
    Or more detailed (stage 1 = ancestor, stage 2 = ours, stage 3 = theirs):
    git ls-files -u
  2. In case of a git-merge, you can check the history of both heads:
    git log --graph --left-right --boundary HEAD...MERGE_HEAD
    Or, to list only the commits that contribute to conflicts:
    git log --left-right --merge
    In case of git-rebase, you can investigate the history and the commit that is being applied:
    git log
    git show $(cat .git/rebase-apply/original-commit)
  3. Resolve the conflict:
    1. Manual resolution and mark as resolved:
      vim <file>
      git diff -c <file>
      git add <file>
    2. Resolution using a tool:
      git mergetool <file>
    3. Resolve by selecting local/other version:
      git checkout --ours <file>
      git checkout --theirs <file>
      git diff -c <file>
      git add <file>
    4. Note that git-diff can be used to inspect changes against both parents at the same time. The default is --cc (combined/condensed) which omits those hunks from -c (combined) that are identical to the hunk from either parent (see git-diff-tree(1)).

  4. (If the resolution went wrong) You can still redo the merge if it is not yet staged:

    git merge-index git-merge-one-file <file>
  5. (If you decide the merge was a bad idea, or want to start over) Abort the merge:

    git merge --abort
    Or the rebase:
    git rebase --abort

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>