Created
December 13, 2022 13:19
-
-
Save MrKevinWeiss/e333abe6141238754d4b3b803e32135d to your computer and use it in GitHub Desktop.
Calculate the git blob hash of
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
"""Hashes the contents of files matching git. | |
Example of how to get the get hash allowing `git cat-file -p <hash>` to work. | |
The output of the files should match `git ls-tree HEAD -r -t`. | |
""" | |
from sys import argv | |
from hashlib import sha1 | |
if __name__ == '__main__': | |
for filename in argv[1:]: | |
with open(filename, 'rb') as f: | |
h = sha1() | |
data = f.read() | |
h.update(f"blob {len(data)}\0".encode('utf-8')) | |
h.update(data) | |
print(h.hexdigest()) |
Note that the \r\n
issues can occur here. Either sync with settings in git or adapt with
with open(filename, 'r') as f:
h = sha1()
data = f.read().replace("\r", "").encode("utf-8")
h.update(f"blob {len(data)}\0".encode('utf-8'))
h.update(data)
print(h.hexdigest())
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I guess at some point git will change to sha256...