Create a gist now

Instantly share code, notes, and snippets.

@zed /.gitignore Secret
Created Aug 12, 2012

What would you like to do?
read git master commit using pure Python
#!/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
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)
# 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