#!/usr/bin/env python

import StringIO
import subprocess
import sys

LOGFMT="""From: %an <%ae>

%B
"""

if len(sys.argv) > 2:
    rev_from, rev_to = sys.argv[1], sys.argv[2]
else:
    rev_from, rev_to = 'master', 'HEAD'

grl = subprocess.Popen(['git', 'rev-list', '^%s' % rev_from, rev_to],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
revs = grl.stdout.readlines()
grl.wait()

if not revs:
    sys.stderr.write('Nothing to make a patch from!\n')
    sys.exit(1)

rev = revs[-1].strip()

patch = StringIO.StringIO()

gl1 = subprocess.Popen(['git', 'log', '-1', '--format=format:%s' % (LOGFMT,),
                        rev],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
patch.writelines(gl1.stdout)
gl1.wait()

gd = subprocess.Popen(['git', 'diff', '--binary', rev_from, rev_to],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
patch.writelines((line for line in gd.stdout if not line.startswith('index')))
gd.wait()

sys.stdout.write(patch.getvalue())
patch.close()
