|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import time |
| 6 | +from hashlib import sha1 |
| 7 | +from subprocess import check_call |
| 8 | +from tempfile import TemporaryDirectory |
| 9 | + |
| 10 | +os.environ['GIT_PAGER'] = '' |
| 11 | + |
| 12 | +commit_message = 'Add foo' |
| 13 | +commit_metadata = { |
| 14 | + 'name': 'Andrew', |
| 15 | + |
| 16 | + 'date': time.strftime('%s %z') |
| 17 | +} |
| 18 | +git_env = {('GIT_%s_%s' % (who.upper(), what.upper()), value) |
| 19 | + for who in ['author', 'committer'] |
| 20 | + for what, value in commit_metadata.items()} |
| 21 | + |
| 22 | +def hash(object_type, contents): |
| 23 | + return sha1(b'%s %d\0%s' % (object_type, len(contents), contents)) |
| 24 | + |
| 25 | +file_hash = hash(b'blob', b'hi\n') |
| 26 | +print(f'file_hash = {file_hash.hexdigest()}') |
| 27 | + |
| 28 | +tree_hash = hash(b'tree', b'100644 foo\0%b' % file_hash.digest()) |
| 29 | +print(f'tree_hash = {tree_hash.hexdigest()}') |
| 30 | + |
| 31 | +commit = """tree %s |
| 32 | +author %s <%s> %s |
| 33 | +committer %s <%s> %s |
| 34 | +
|
| 35 | +%s |
| 36 | +""" % (tree_hash.hexdigest(), |
| 37 | + commit_metadata['name'], commit_metadata['email'], commit_metadata['date'], |
| 38 | + commit_metadata['name'], commit_metadata['email'], commit_metadata['date'], |
| 39 | + commit_message) |
| 40 | +commit = commit.encode('UTF-8') |
| 41 | + |
| 42 | +commit_hash = hash(b'commit', commit) |
| 43 | +print(f'commit_hash = {commit_hash.hexdigest()}') |
| 44 | +print() |
| 45 | +sys.stdout.flush() |
| 46 | + |
| 47 | +with TemporaryDirectory() as t: |
| 48 | + os.chdir(t) |
| 49 | + with open('foo', 'w') as f: |
| 50 | + f.write('hi\n') |
| 51 | + check_call(['git', 'init']) |
| 52 | + check_call(['git', 'add', 'foo']) |
| 53 | + |
| 54 | + env = os.environ.copy() |
| 55 | + env.update(git_env) |
| 56 | + check_call(['git', 'commit', '-m', commit_message], env=env) |
| 57 | + check_call(['git', 'log', '-m', 'foo']) |
0 commit comments