验证提交是否存在
如何验证当前分支中是否存在给定 sha 的提交?
有很多方法可以解析输出,但我需要返回布尔值的最佳方法(用于 bash 脚本中)。
例如
sha=$1
if [ -z `git magic --validate $sha` ]; then
echo "Invalid commit sha: $sha"
exit 1
fi
How to validate whether the commit with given sha exists in current branch?
There are many ways to parse outputs, but I need optimal way which returns boolean (for usage in bash script).
e.g.
sha=$1
if [ -z `git magic --validate $sha` ]; then
echo "Invalid commit sha: $sha"
exit 1
fi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这会测试
$sha
是否是当前分支 (HEAD
) 的祖先提交,如果是,则成功退出。在你的例子中,
This tests if
$sha
is an ancestor commit for the current branch (HEAD
), and exits successfully if it is.In your example,
您可以在条件中使用 grep 的退出代码。
对于当前分支,
You can use the exit code from grep in conditionals.
For the current branch,
实际上并没有验证提交(我猜 SHA1 就是这个意思)是否存在。它验证数据库中是否存在与提供的 SHA1 对应的对象。也就是说,如果存在与 SHA1 匹配的 blob 或树对象,它将报告它存在,即使它不是提交。
这将验证该对象是否存在并且它是一个可以用作提交(提交或带注释的标签)的对象。
Does not actually verify that commit (I guess SHA1 is what is meant) exists. It verifies that there is an object in the database corresponding to the SHA1 provided. That is, if there is a blob or tree object that matches the SHA1, it will report that it exists, even if it is not a commit.
This will verify that the object exists and that it is an object that can be used as a commit (commit or annotated tag).
修订列表 | grep 方法工作正常;开销很小,因为 git 必须打印出所有 SHA1 供 grep 查看,但这并不是什么大问题。
如果您愿意,您也可以使用 git merge-base 来完成此操作 - 如果目标提交和分支的合并基础是目标提交,则分支包含目标提交:
无论采用哪种方式,请注意,
rev-list
和merge-base
将打印出 SHA1,因此,如果您正在测试包含的提交是由分支或标记命名的,那么您首先要使用 git rev-parse 将其转换为 SHA1。The
rev-list | grep
method works fine; there's the tiniest bit of overhead because git has to print out all the SHA1s forgrep
to see, but it's not really a big deal.You can also do it with
git merge-base
if you like - if the merge base of the target commit and the branch is the target commit, the branch contains the target commit:Either way you do it, note that
rev-list
andmerge-base
are going to be printing out SHA1s, so if the commit you're testing for inclusion is named by a branch or tag, you'll want to usegit rev-parse
to turn it into an SHA1 first.的输出
您可以查看“如果此命令因存储库中根本不存在 sha1 而失败,则退出代码将不为零” 。如果输出为空,则提交位于当前分支中,如果输出非空,则不是。所以你的脚本看起来像
如果你已经知道
$sha
真正命名了一个提交(作为 SHA1 哈希或任何其他方式),这可以简化为You can look at the output of
If this command fails because the sha1 does not exist at all in the repository, the exit code will be non-zero. If the output is empty, the commit is in the current branch, and if it is non-empty, it is not. So your script would look like
In case you already know that
$sha
really names a commit (as a SHA1 hash or in any other way), this simplifies togit cat-file 打印有关存储库中对象的信息。 “-e”检查对象是否有效并以 0 状态退出,如果无效则以 1 状态退出。
git cat-file prints information about the objects in the repository. "-e" checks if the object is valid and exits with a 0 status and when invalid exists with a 1.