How do I make git automatically open the mergetool if there is a merge conflict?

心已入冬 提交于 2019-12-31 11:43:04

问题


How do I make git automatically run git mergetool for any merge conflict? This should apply for all merges, using merge, rebase, pull, etc.


回答1:


You cannot (yet) make git do this.


This may or may not be an acceptable workaround.

Create a function in your ~/.bashrc:

git() 
{ 
  if [[ $1 == "merge" ]] || [[ $1 == "rebase" ]] || [[ $1 == "pull" ]]; then 
    command git "$@" 
    rc=$?
    if [[ $rc == 1 ]]; then
      echo "There are conflicts, better run git-mergetool!!!"
      # There might be some other condition that returns a '1',
      # if so you can add another check like this:
      # if grep Conflicts $(git --git-dir)/MERGE_MSG;
      command git mergetool
    fi
  else 
    command git "$@"
  fi
}

Mergetool isn't invoked when it merges:

$ git merge non_conflicting_branch
Merge made by the 'recursive' strategy.
 bar | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 bar

Mergetool is called when there are conflicts:

$ git merge conflicting_branch
Auto-merging foo
CONFLICT (content): Merge conflict in foo
Automatic merge failed; fix conflicts and then commit the result.
There are Conflicts, better run git-mergetool!!!

Mergetool is not called on other errors:

$ git merge adasds
fatal: adasds - not something we can merge



回答2:


You could always use alias

alias 'git-merge'='git merge && git mergetool'
alias 'git-rebase'='git rebase && git mergetool'
alias 'git-pull'='git pull && git mergetool'

And/or write a helper script along these lines

#/bin/bash
git $*
[ "$(git ls-files –abbrev –unmerged | wc -l)" -gt 0 ] && git mergetool

and then

alias git='~/.git/git-script'

There is no direct way of invoking mergetool, because it is only one of several ways to merge (see "HOW TO RESOLVE CONFLICTS" in man 1 git-merge).




回答3:


As far as I know, there is no porcelain way to do it.

You can have a wrapper around git like this (file git_mergetool.sh, on your path, +x):

#!/bin/bash

SEARCH="CONFLICT"
OUTPUT=$(git "$@" 2>&1 | tee /dev/tty)
if `echo ${OUTPUT} | grep -i "${SEARCH}" 1>/dev/null 2>&1`
then
  git mergetool
fi

Then add alias:

echo alias git=\"git_mergetool.sh\" >> ~/.bashrc

Every time you invoke git, the wrapper will check if the word "CONFLICT" pops up. If it does - wrapper launches mergetool.

This can be improved by adding more precise phrase to $SEARCH (like "Automatic merge failed; fix conflicts and then commit the result.") as well as by checking if first argument ($1) is in the list of commands resulting in merge conflict (pull, merge, etc...). Otherwise you will end up parsing a lot of unnecessary data if git command output is too long.



来源:https://stackoverflow.com/questions/10032265/how-do-i-make-git-automatically-open-the-mergetool-if-there-is-a-merge-conflict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!