Search code examples
gitgit-merge

How to check if git merge problems have been fixed?


When merging branches it is common to get merge conflicts which are listed on the command prompt. I know how to get the issues fixed by looking at the files that have conflicts and making the appropriate changes. We also have "mergetool" which can be very useful (not very good at using it though). From what I've read from different sources the steps to get this resolved are:

  • fix conflicts
  • add
  • push

This seems pretty simple. But what if I miss something and don't fix it? Does Git provide a way to check if there is something else to be fixed other than using mergetool?


Solution

  • Do:

    git diff -S "<<<<<<< HEAD" -S "=======" -S ">>>>>>> $(git name-rev --name-only MERGE_HEAD)" HEAD
    

    This compares the contents of the worktree with HEAD, but only shows any output if one or more of the three types of merge marks is included in the change.

    For example, if you are merging from a branch called develop, an unmerged file might look like this:

    public void fooTheBar(Bar input) {
    <<<<<<< HEAD
      if (input == null) {
        throw new Exception("input cannot be null!");
      }
    =======
      Console.WriteLine("preparing to foo the bar");
    >>>>>>> develop
      input.foo();
    }
    

    So to ensure all files have been merged, you need to search for any of the following three lines:

    <<<<<<< HEAD
    =======
    >>>>>>> develop
    

    And that is what the -S arguments in the command do. Since it won't always be develop, we use the command:

    git name-rev --name-only MERGE_HEAD
    

    to get the name of the branch that you are merging into your current branch.

    (You could probably search for just one of those lines, but searching for all three is more robust, and will show you cases where e.g. you forgot to remove just one of the lines.)

    Since the command compares the worktree to HEAD, and not just to the staged changes, this will work even if you have git added a file that still contains conflicts.