Skip to content

Instantly share code, notes, and snippets.

Created May 1, 2013
What would you like to do?
Sample Git update hook that deploys the changed files to the web root.
import logging
import git
import sys
import os
def main():
Update all files according to a diff.
# Configure logging.
logger = logging.getLogger()
formatter = logging.Formatter('%(levelname)s: %(message)s')
ch = logging.StreamHandler(sys.stdout)
# Start.'Starting update hook.')
repo = git.Repo()
# Check arguments.
logging.debug('Arguments: %s', sys.argv)
assert len(sys.argv) == 4
if sys.argv[2] == '0000000000000000000000000000000000000000':
sys.argv[2] = repo.git.hash_object('-w', '-t', 'tree', os.devnull)
if sys.argv[3] == '0000000000000000000000000000000000000000':
sys.argv[3] = repo.git.hash_object('-w', '-t', 'tree', os.devnull)
# Iterate over the diff.
assert repo.bare == True
diff = repo.git.diff('--name-status', sys.argv[2], sys.argv[3])
tree = repo.commit(sys.argv[3]).tree
for line in diff.split("\n"):
if not line: continue
status, file = line.split("\t", 1)
assert status in ['A', 'D', 'M']
target = get_target(file)
logging.debug('%s %s -> %s', status, file, target)
if target:
if status == 'D':
# Unlink file.
os.unlink(target)'Deleted %s', target)
# Remove parent dirs.
os.removedirs(os.path.dirname(target))'Cleaned away parent of %s', target)
except OSError:
logging.debug('Did not clean away parent of %s', target)
# Create directories.
node = tree[file]
assert isinstance(node, git.Blob)
if status == 'A':
os.makedirs(os.path.dirname(target))'Created directory for %s', target)
except OSError:
logging.debug('Did not create directory for %s', target)
# Write blob.
node.stream_data(open(target, 'w'))'Wrote %s', target)
else:'Ignored %s', target)
# Done.'update hook finished.')
def get_target(file):
Returns the target by a given filename.
splitpath = file.split(os.sep)
if splitpath[0] in ['www', 'local', 'tools', 'data']:
return os.path.join('/var', file)
return False
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment