Skip to content

Instantly share code, notes, and snippets.

@MrKevinWeiss
Created December 13, 2022 13:19
Show Gist options
  • Save MrKevinWeiss/e333abe6141238754d4b3b803e32135d to your computer and use it in GitHub Desktop.
Save MrKevinWeiss/e333abe6141238754d4b3b803e32135d to your computer and use it in GitHub Desktop.
Calculate the git blob hash of
#!/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())
@MrKevinWeiss
Copy link
Author

I guess at some point git will change to sha256...

@MrKevinWeiss
Copy link
Author

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