8

作为人类,有很多方法可以查看存储库是否存在需要解决的冲突。

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

我可以想到一种方法,例如:

__git_ps1 "%s" | grep MERGING > /dev/null 2>&1 && echo "In merge state"

但是,我怀疑这不是推荐的方法。首先,因为__git_ps1__C 程序员开始,我倾向于认为它不适合我使用,其次我猜测有一种更合适的方法,例如:

git repo-status --is-merging

这将具有返回值或类似的东西。

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

4

3 回答 3

14

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

于 2012-12-17T18:16:59.233 回答
4

在 GNU/我会做的任何事情上

$ if { git status --porcelain | sed -nr '/^U.|.U|AA|DD/q1'; }
> then # no merge conflicts
> else # merge conflicts
> fi
于 2012-12-15T16:26:00.073 回答
1

这对你有用吗?

$ 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 filewhereXYare 两个字母,你可能有一个需要解决的冲突。

于 2012-12-15T16:27:13.707 回答