read git master commit using pure Python
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
/tmp/ |
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/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment