如何通过SHA-1检查Git存储库中是否存在提交

sko*_*yov 36 git

在类似的主题中验证是否存在提交,他们建议:

git rev-list HEAD..$sha
Run Code Online (Sandbox Code Playgroud)

如果它退出而没有错误代码,则存在提交.

但它仅仅用于验证是否足够有效?

我在考虑这个选项:

git cat-file commit $sha
Run Code Online (Sandbox Code Playgroud)

这对我的任务是否正确,还有其他想法吗?

rem*_*ram 38

你可以运行git cat-file -t $sha并检查它返回"提交".你是对的,你不需要实际打印实际的对象......

不过,我并不是100%确定幕后发生的事情会更有效率.

test $(git cat-file -t $sha) == commit

  • 最终我决定使用`git cat-file commit $ sha`,因为如果`$ sha`不代表提交,它只是退出错误,所以我不需要测试stdout(在我的情况下我也需要修剪为它在"commit"结束时添加换行符. (7认同)
  • 分支不是对象 :) 检查您输入的是 ref 还是 SHA-1 可以使用 rev-parse 完成:`[[ $(git rev-parse --symbolic-full-name $sha) = refs/* ]] ` (3认同)
  • 请注意,这也将返回分支名称的“提交” (2认同)

Pau*_*per 29

git cat-file -e $sha^{commit}
Run Code Online (Sandbox Code Playgroud)

来自git cat-filedocs:

   -e
      Suppress all output; instead exit with zero status if <object> exists
      and is a valid object.
Run Code Online (Sandbox Code Playgroud)

这(1)表明这是一个预期的用例,cat-file并且(2)避免了实际输出任何提交内容的资源.

追加^{commit}确保对象是提交(即不是树或blob)或 - 如remram指出 - 解析为提交.

例如,

if git cat-file -e $sha^{commit}; then
  echo $sha exists
else
  echo $sha does not exist
fi
Run Code Online (Sandbox Code Playgroud)


and*_*vin 7

如果您确定sha是提交,那么cat-file -e可以使用例如:

if git cat-file -e $sha 2> /dev/null 
then 
  echo exists 
else 
  echo missing 
fi
Run Code Online (Sandbox Code Playgroud)

这是非常有效的,因为这是一个内置的,除了检查sha存在之外什么都不做:

return !has_sha1_file(sha1);
Run Code Online (Sandbox Code Playgroud)

否则,如果不确定sha是提交对象,则需要使用其他答案来确定类型git cat-file -t.这只是性能稍差,因为git必须查看文件信息.这不像拆包整个文件那样昂贵.

  • `git rev-parse --verify`只会检查标识符是否是有效的哈希值.`git rev-parse --verify 1234567890123456789012345678901234567890`将永远返回true (2认同)

Bla*_*tha 7

git rev-parse -q --verify "$sha^{commit}" > /dev/null
Run Code Online (Sandbox Code Playgroud)

git rev-parse文档:

   --verify
       Verify that exactly one parameter is provided, and that it can be turned into a raw 20-byte SHA-1 that can be used to access the object database. If so, emit it to the standard output; otherwise, error out.

       If you want to make sure that the output actually names an object in your object database and/or can be used as a specific type of object you require, you can add the ^{type} peeling operator to the parameter. For
       example, git rev-parse "$VAR^{commit}" will make sure $VAR names an existing object that is a commit-ish (i.e. a commit, or an annotated tag that points at a commit). To make sure that $VAR names an existing object of
       any type, git rev-parse "$VAR^{object}" can be used.

   -q, --quiet
       Only meaningful in --verify mode. Do not output an error message if the first argument is not a valid object name; instead exit with non-zero status silently. SHA-1s for valid object names are printed to stdout on
       success.
Run Code Online (Sandbox Code Playgroud)

作为奖励,如果你不抑制输出,你可以获得完整的 sha。