diff --git a/progit/lib.py b/progit/lib.py index 9159f9d..a8e0aec 100644 --- a/progit/lib.py +++ b/progit/lib.py @@ -9,6 +9,7 @@ """ +import datetime import json import os import shutil @@ -46,6 +47,41 @@ def create_session(db_url, debug=False, pool_recycle=3600): return scopedsession +def commit_to_patch(repo_obj, commit): + ''' For a given commit (PyGit2 commit object) of a specified git repo, + returns a string representation of the changes the commit did in a + format that allows it to be used as patch. + ''' + if commit.parents: + diff = commit.tree.diff_to_tree() + + parent = repo_obj.revparse_single('%s^' % commit.oid.hex) + diff = repo_obj.diff(parent, commit) + else: + # First commit in the repo + diff = commit.tree.diff_to_tree(swap=True) + + patch = """From %(commit)s +From: %(author_name)s <%(author_email)s> +Date: %(date)s + +%(msg)s + +%(patch)s +""" % ( + { + 'commit': commit.oid.hex, + 'author_name': commit.author.name, + 'author_email': commit.author.email, + 'date': datetime.datetime.utcfromtimestamp( + commit.commit_time).strftime('%b %d %Y %H:%M:%S +0000'), + 'msg': commit.message, + 'patch': diff.patch, + } + ) + return patch + + def get_user(session, username): ''' Return the user corresponding to this username, or None. ''' user = session.query(