Skip to content

Instantly share code, notes, and snippets.

@zed

zed/.gitignore Secret

Created August 12, 2012 14:40
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save zed/754cdf6540f8ed7c4e56 to your computer and use it in GitHub Desktop.
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
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