在大型存储库上使用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:-.}
第二个别名的一部分意味着您只能获得当前目录中冲突文件的列表,而不是整个存储库。)