Git: An alias to speed up fixing merge conflicts

Fixing merge conflicts can feel like untangling knots…

There you are, minding your own business, rebasing your branch and… surprise! A merge conflict!

Fixing merge conflicts can be a little time consuming. The alias in this post can smooth that process out a bit.

Update (2022-11-11): Eric Engestrom told me on Twitter about git mergetool, which is a built-in command for stepping through merge conflicts. This might be easier to use than the below workflow—I’m still playing with it and may write a post in the future.

Update (2022-11-13): Removed an add-unmerged alias from the below to instead recommend git add -u, thanks to a suggestion from Christos Kontas on Twitter.

List files with conflicts

Git calls files with conflicts unmerged, because it couldn’t merge parallel edits. You can see the filenames in the “Unmerged paths” section of git status:

$ git status
...
Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
  both added:      drink.txt

no changes added to commit (use "git add" and/or "git commit -a")

You can output just the unmerged files with the --diff-filter option for git diff:

$ git diff --name-only --diff-filter U
drink.txt

Neat.

Edit and add files with conflicts

Run this command to add an alias for editing unmerged files:

$ git config --global alias.edit-unmerged '!git diff --name-only --diff-filter U | xargs -r $(git var GIT_EDITOR)'

Git will add this to your ~/.gitconfig:

[alias]
    edit-unmerged = !git diff --name-only --diff-filter U | xargs -r $(git var GIT_EDITOR)

Now, when you have a merge conflict, you can open all the unmerged files with:

$ git edit-unmerged

You can step through each in your text editor, fixing them as necessary. Then, you can add them all with the -u option (--update) for git add:

$ git add -u

…and you’re ready to commit:

$ git status --short
M  drink.txt

$ git rebase --continue
[detached HEAD d80c05f] Frappucino
 1 file changed, 5 insertions(+)
Successfully rebased and updated refs/heads/barstucks.

Sweet.

History

Unfortunately, I can’t remember where I picked up this alias. When I searched, I found a version in the GitAlias project, which gave me the hint to adjust to use GIT_EDITOR rather than hardcoding the editor commmand.

The GitAlias project has other aliases for editing files in other states like “staged”, which you might like. But personally, I don’t think I’ve needed them, though I use the above “unmerged” alias all the time.

Fin

May you resolve merge conflicts in record time,

—Adam


Make your development more pleasant with Boost Your Django DX.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: