Git 哈希是如何计算的? [英] How is the Git hash calculated?
问题描述
我想了解 Git 如何计算引用的哈希值.
I'm trying to understand how Git calculates the hash of refs.
$ git ls-remote https://github.com/git/git
....
29932f3915935d773dc8d52c292cadd81c81071d refs/tags/v2.4.2
9eabf5b536662000f79978c4d1b6e4eff5c8d785 refs/tags/v2.4.2^{}
....
在本地克隆 repo.检查 refs/tags/v2.4.2^{}
ref by sha
Clone the repo locally. Check the refs/tags/v2.4.2^{}
ref by sha
$ git cat-file -p 9eabf5b536662000f79978c4d1b6e4eff5c8d785
tree 655a20f99af32926cbf6d8fab092506ddd70e49c
parent df08eb357dd7f432c3dcbe0ef4b3212a38b4aeff
author Junio C Hamano <gitster@pobox.com> 1432673399 -0700
committer Junio C Hamano <gitster@pobox.com> 1432673399 -0700
Git 2.4.2
Signed-off-by: Junio C Hamano <gitster@pobox.com>
复制解压后的内容,以便我们可以对它进行哈希处理.(AFAIK Git 在散列时使用未压缩版本)
Copy the decompressed content so that we can hash it. (AFAIK Git uses the uncompressed version when it's hashing)
git cat-file -p 9eabf5b536662000f79978c4d1b6e4eff5c8d785 > fi
让我们使用 Git 自己的哈希命令对内容进行 SHA-1 处理
Let's SHA-1 the content using Git's own hash command
git hash-object fi
3cf741bbdbcdeed65e5371912742e854a035e665
为什么输出不是[9e]abf5b536662000f79978c4d1b6e4eff5c8d785
?我知道前两个字符 (9e
) 是十六进制的长度.我应该如何散列 fi
的内容,以便获得 Git 引用 abf5b536662000f79978c4d1b6e4eff5c8d785
?
Why is the output not [9e]abf5b536662000f79978c4d1b6e4eff5c8d785
? I understand the first two characters (9e
) are the length in hex. How should I hash the content of fi
so that I can get the Git ref abf5b536662000f79978c4d1b6e4eff5c8d785
?
推荐答案
如git commit 是如何进行的sha1形成",公式为:
(printf "<type> %s " $(git cat-file <type> <ref> | wc -c); git cat-file <type> <ref>)|sha1sum
对于 commit 9eabf5b536662000f79978c4d1b6e4eff5c8d785(它是 v2.4.2^{}
,并且引用了一个树):
In the case of the commit 9eabf5b536662000f79978c4d1b6e4eff5c8d785 (which is v2.4.2^{}
, and which referenced a tree) :
(printf "commit %s " $(git cat-file commit 9eabf5b536662000f79978c4d1b6e4eff5c8d785 | wc -c); git cat-file commit 9eabf5b536662000f79978c4d1b6e4eff5c8d785 )|sha1sum
那将得到 9eabf5b536662000f79978c4d1b6e4eff5c8d785.
That will give 9eabf5b536662000f79978c4d1b6e4eff5c8d785.
也一样:
(printf "commit %s " $(git cat-file commit v2.4.2{} | wc -c); git cat-file commit v2.4.2{})|sha1sum
(还是 9eabf5b536662000f79978c4d1b6e4eff5c8d785)
(still 9eabf5b536662000f79978c4d1b6e4eff5c8d785)
同样,计算标签 v2.4.2 的 SHA1 将是:
Similarly, computing the SHA1 of the tag v2.4.2 would be:
(printf "tag %s " $(git cat-file tag v2.4.2 | wc -c); git cat-file tag v2.4.2)|sha1sum
那就是 29932f3915935d773dc8d52c292cadd81c81071d.
That would give 29932f3915935d773dc8d52c292cadd81c81071d.
这篇关于Git 哈希是如何计算的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!