如何将Git SHA1分配给没有Git的文件? [英] How to assign a Git SHA1's to a file without Git?

查看:177
本文介绍了如何将Git SHA1分配给没有Git的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,当Git给一个文件分配一个SHA1哈希值时,这个SHA1对于该文件根据其内容是唯一的。因此,如果文件从一个存储库移动到另一个存储库,文件的SHA1保持不变,而其内容没有改变。

Git如何计算SHA1摘要?它是否在完整的未压缩文件内容上做到这一点?



我想模拟在Git之外分配SHA1的情况。

解决方案

这是Git如何计算一个文件的SHA1(或者用Git术语来说,是一个blob):

  sha1(blob+ filesize +\0+ data)

所以你可以在没有安装Git的情况下轻松地计算它。请注意,\0是NULL字节,而不是两个字符的字符串。

例如,一个空文件的散列:

  sha1(blob 0\0)=e69de29bb2d1d6434b8b29ae775ad8c2e48c5391

$ touch空
$ git散列对象空
e69de29bb2d1d6434b8b29ae775ad8c2e48c5391

另一个例子: p>

  sha1(blob 7\0foobar\\\
)=323fae03f4606ea9991df8befbb2fca795e648fa

$ echofoobar> foo.txt
$ git hash-object foo.txt
323fae03f4606ea9991df8befbb2fca795e648fa

是一个Python实现:

from hashlib import sha1
def githash(data):
s = sha1()
s.update(blob%u\0%len(data))
s.update(data)
return s.hexdigest()


As I understand it when Git assigns a SHA1 hash to a file this SHA1 is unique to the file based on its contents.

As a result if a file moves from one repository to another the SHA1 for the file remains the same as its contents have not changed.

How does Git calculate the SHA1 digest? Does it do it on the full uncompressed file contents?

I would like to emulate assigning SHA1's outside of Git.

解决方案

This is how Git calculates the SHA1 for a file (or, in Git terms, a "blob"):

sha1("blob " + filesize + "\0" + data)

So you can easily compute it yourself without having Git installed. Note that "\0" is the NULL-byte, not a two-character string.

For example, the hash of an empty file:

sha1("blob 0\0") = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"

$ touch empty
$ git hash-object empty
e69de29bb2d1d6434b8b29ae775ad8c2e48c5391

Another example:

sha1("blob 7\0foobar\n") = "323fae03f4606ea9991df8befbb2fca795e648fa"

$ echo "foobar" > foo.txt
$ git hash-object foo.txt 
323fae03f4606ea9991df8befbb2fca795e648fa

Here is a Python implementation:

from hashlib import sha1
def githash(data):
    s = sha1()
    s.update("blob %u\0" % len(data))
    s.update(data)
    return s.hexdigest()

这篇关于如何将Git SHA1分配给没有Git的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆