作为一个人,有很多方法可以查看存储库是否存在需要解决的冲突。
但是,我正在寻找一种在脚本中检查这一点的方法。也就是说,检查存储库是否处于良好状态以开始对其进行操作,或者是否处于用户必须修复冲突的阶段。
我可以想到如下的方法:
__git_ps1 "%s" | grep MERGING > /dev/null 2>&1 && echo "In merge state"
但是,我怀疑这不是推荐的方法。首先,因为
__git_ps1
以 __
开头,作为一名 C 程序员,我倾向于认为它不适合我使用,其次,我猜测有一个更合适的方法,例如:
git repo-status --is-merging
它会有返回值,或者类似的东西。
那么,如果存储库处于合并状态,我如何询问 git(作为脚本)?
使用
git status
或类似的方法在大型存储库上会很慢,因为它需要检查整个工作副本的状态以及索引。我们只对索引感兴趣,因此我们可以使用更快的命令来检查索引状态。
具体来说,我们可以使用
git ls-files --unmerged
。如果没有处于冲突状态的文件,该命令将不会产生任何输出,如果有,则如下所示:
$ git ls-files --unmerged
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 1 filename
100644 4a58007052a65fbc2fc3f910f2855f45a4058e74 2 filename
100644 65b2df87f7df3aeedef04be96703e55ac19c2cfb 3 filename
因此我们可以检查该文件是否产生任何输出:
[[ -z $(git ls-files --unmerged) ]]
。如果存储库是干净的,该命令将返回零,如果存储库有冲突,则返回非零。将 -z
替换为 -n
以获得相反的行为。
您可以将以下内容添加到您的
~/.gitconfig
:
[alias]
conflicts = ![[ -n $(git ls-files --unmerged) ]]
list-conflicts = "!cd ${GIT_PREFIX:-.}; git ls-files --unmerged | cut -f2 | sort -u"
这将产生如下行为:
$ git st
# On branch master
nothing to commit (working directory clean)
$ git conflicts && echo 'Conflicts exist' || echo 'No conflicts'
No conflicts
$ git merge other-branch
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.
$ git conflicts && echo 'Conflicts exist' || echo 'No conflicts'
Conflicts exist
$ git list-conflicts
file
(第二个别名的
cd ${GIT_PREFIX:-.}
部分意味着您只能获得当前目录中冲突文件的列表,而不是整个存储库。)
另一种方法:
$ if git status --porcelain | grep -Eq '^(U.|.U|AA|DD)'
> then # no merge conflicts
> else # merge conflicts
> fi
这对你有用吗?
$ git merge origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.
$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 1 and 1 different commit each, respectively.
#
# Unmerged paths:
# (use "git add/rm <file>..." as appropriate to mark resolution)
#
# both modified: file
#
no changes added to commit (use "git add" and/or "git commit -a")
$ git status -s
UU file
您可以告诉您处于合并状态,因为它告诉您一个文件有 2 处修改并且两者均未合并。实际上,如果您有
XY file
,其中 X
和 Y
都是字母,那么您可能存在需要解决的冲突。