我要做的是版本检查。我想确保代码保持在最小版本之上。因此,我需要一种方法来知道当前分支是否包含指定的提交。


当前回答

获取包含特定提交的分支列表。

# get all the branches where the commit exists
$ git branch --contains <commit-id>

检查分支是否有特定的提交。

# output the branch-name if the commit exists in that branch
$ git branch --contains <commit-id> | grep <branch-name>

使用精确匹配搜索分支(例如,特征)。

$ git branch --contains <commit-id> | grep -E '(^|\s)feature$'

例:如果你有3个本地分支,分别叫feature, feature1, feature2

$ git branch --contains <commit-id> | grep 'feature'

# output
feature
feature1
feature2

$ git branch --contains <commit-id> | grep -E '(^|\s)feature$'

# output
feature     

您也可以在本地和远程分支中搜索(使用-a),或者只在远程分支中搜索(使用-r)。

# search in both 'local' & 'remote' branches  
$ git branch -a --contains <commit-id> | grep -E '(^|\s)feature$'

# search in 'remote' branches  
$ git branch -r --contains <commit-id> | grep -E '(^|\s)feature$'

其他回答

是的,另一个选择:

git rev-list <branch name> | grep `git rev-parse <commit>`

这对我来说是最好的,因为它也适用于本地缓存的远程分支,如remotes/origin/master,在git分支上——contains不会工作。

这不仅仅是OP关于“当前分支”的问题,但我发现问这个问题的“任何分支”版本都很愚蠢,所以我决定在这里发帖。

只在本地分行查,那已经签出去了。

git branch --contains $COMMIT_ID

检入所有分支(获取的本地和远程分支)

git branch -a --contains $COMMIT_ID

确保获取遥控器

git fetch origin

提取@torek的评论作为答案:

有关如何查找包含指定提交的所有分支,请参阅建议的副本。

要找出当前分支是否包含提交C,请使用“管道”命令git merge-base——is-祖宗。如果C是HEAD的祖先,则当前分支包含C,因此:

if git merge-base --is-ancestor $hash HEAD; then
    echo I contain commit $hash
else
    echo I do not contain commit $hash
fi

(旁注:在shell脚本中,退出0的命令为“true”,而退出非0的命令为“false”。)

git branch --contains <commit-id> --points-at <target branch name>

如果提交id存在于目标分支中,它将返回目标分支名称。否则命令执行失败。

在Windows机器的Windows/CMD终端上。你可以:

> git log | findstr "commit-id"

如:

> git log | findstr "c601cd6366d"