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


当前回答

有多种方法可以实现这一结果。第一个简单的选择是使用git日志并使用grep搜索特定的提交,但这并不总是准确的

git log | grep <commit_id>

你最好直接使用git分支来查找包含给定COMMIT_ID的所有分支

git branch --contains $COMMIT_ID

下一步是找到当前的分支,这可以从git 1.8.1开始使用

git symbolic-ref --short HEAD

结合在一起的

git branch $(git symbolic-ref --short HEAD) --contains $COMMIT_ID

但是上面的命令不会返回true或false,如果提交在当前分支中,则有一个更短的版本返回退出代码0,如果不是则返回退出代码1

git merge-base --is-ancestor $COMMIT_ID HEAD

退出代码很好,但当你想要字符串为真或假的答案,你需要添加更多,然后结合if从bash你得到

if [ 0 -eq $(git merge-base --is-ancestor $COMMIT_ID HEAD) ]; then echo "true"; else echo "false"; fi

其他回答

提取@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”。)

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

> git log | findstr "commit-id"

如:

> git log | findstr "c601cd6366d"

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

# 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$'

列出包含commit的本地分支:

Git分支——包含<commit-id>

列出所有包含commit的分支,只包括remote:

Git分支-a——包含<commit-id>

类似地,检查commit是否在特定的分支中:

Git log <branch> | grep <commit_id>

如果分支不存在,则在分支名称前加上origin/

有多种方法可以实现这一结果。第一个简单的选择是使用git日志并使用grep搜索特定的提交,但这并不总是准确的

git log | grep <commit_id>

你最好直接使用git分支来查找包含给定COMMIT_ID的所有分支

git branch --contains $COMMIT_ID

下一步是找到当前的分支,这可以从git 1.8.1开始使用

git symbolic-ref --short HEAD

结合在一起的

git branch $(git symbolic-ref --short HEAD) --contains $COMMIT_ID

但是上面的命令不会返回true或false,如果提交在当前分支中,则有一个更短的版本返回退出代码0,如果不是则返回退出代码1

git merge-base --is-ancestor $COMMIT_ID HEAD

退出代码很好,但当你想要字符串为真或假的答案,你需要添加更多,然后结合if从bash你得到

if [ 0 -eq $(git merge-base --is-ancestor $COMMIT_ID HEAD) ]; then echo "true"; else echo "false"; fi