如果存储库处于冲突阶段,如何询问git?

Sha*_*baz 8 git state status

作为一个人,有很多方法可以看到存储库是否存在需要解决的冲突.

但是,我正在寻找一种方法来在脚本中检查这一点.也就是说,检查存储库是否处于良好状态以开始对其执行某些操作,或者它处于用户必须修复冲突的阶段.

我可以想到以下方式:

__git_ps1 "%s" | grep MERGING > /dev/null 2>&1 && echo "In merge state"
Run Code Online (Sandbox Code Playgroud)

但是,我怀疑这不是推荐的方法.首先是因为作为C程序员__git_ps1开始__并且作为C程序员我倾向于认为它不适合我的使用,其次我猜测有更合适的方式:

git repo-status --is-merging
Run Code Online (Sandbox Code Playgroud)

哪个会有返回值,或类似的东西.

那么,如果存储库处于合并状态,我如何询问git(作为脚本)?

me_*_*and 14

git status在大型存储库上使用或类似将会很慢,因为它需要检查整个工作副本的状态以及索引.我们只对索引感兴趣,所以我们可以使用更快的命令来检查索引状态.

具体来说,我们可以使用git ls-files --unmerged.如果没有处于冲突状态的文件,那么该命令将不会产生输出,如果存在以下情况,则该命令将如下所示:

$ git ls-files --unmerged
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 1       filename
100644 4a58007052a65fbc2fc3f910f2855f45a4058e74 2       filename
100644 65b2df87f7df3aeedef04be96703e55ac19c2cfb 3       filename
Run Code Online (Sandbox Code Playgroud)

所以我们可以检查该文件是否产生任何输出:[[ -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"
Run Code Online (Sandbox Code Playgroud)

这将产生如下行为:

$ 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
Run Code Online (Sandbox Code Playgroud)

(cd ${GIT_PREFIX:-.}第二个别名的一部分意味着您只获取当前目录中的冲突文件列表,而不是整个存储库.)