secret
Last active

read git master commit using pure Python

  • Download Gist
.gitignore
1
/tmp/
read-commit.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#!/usr/bin/env python
import hashlib
import os
import shutil
import subprocess
import zlib
 
# create sample git repo
try: shutil.rmtree('tmp')
except OSError: pass
subprocess.check_call("""
mkdir tmp
cd tmp
echo hello > file.txt
git init
git add file.txt
git commit -m'initial commit'
""", shell=True, stdout=open(os.devnull, 'wb'))
 
# read the commit without git
sha = open('tmp/.git/refs/heads/master').read().rstrip()
fn = 'tmp/.git/objects/%s/%s' % (sha[:2], sha[2:])
raw_bytes = zlib.decompress(open(fn, 'rb').read())
header, _, content = raw_bytes.partition(b'\0')
type_, size = header.split()
assert type_ == b'commit'
assert len(content) == int(size)
print(content.decode())
 
# compute sha
readsha = hashlib.sha1(raw_bytes).hexdigest()
assert readsha == sha

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.