#!/bin/bash
#
#	git-blame based authoring statistics
#	written by Jan Engelhardt, 2008-2009
#
#	This program is free software; you can redistribute it and/or
#	modify it under the terms of the WTF Public License version 2 or
#	(at your option) any later version.
#

if [[ "$1" == "--tsvn" ]]; then
	#
	# Workaround for TortoiseSVN, which is too strict with diffs
	#
	shift;
	tsvn=1;

	# So arcane...
	rev=$(git log $(git rev-list --reverse "$@" | head -n1) |
	      grep "git-svn-id:" | head -n1 | grep -Po '(?<=\@)\d+');
	echo "On SVN r$rev";
fi;

j=0;
for i in $(git rev-list --reverse "$@"); do
	let ++j;
	f="$(printf %04u.diff $j)";
	echo -en "[$f] ";

	# The rationale behind this seemingly stupid invocation of cat is
	# that we want to make git-log behave as if it was not outputting
	# to a terminal.
	git log -1 --abbrev-commit --pretty=oneline "$i" | cat;
	p=$(git rev-parse "$i^");
	echo "parent $p ("$(git describe "$i^" 2>/dev/null)")" >"$f";
	git log -1 -C -M -p --stat=72 --summary --patience "$i" | \
	perl -lpe '$s=1 if/^---/;s/^ {4}// if!$s' >>"$f";
	if [[ -z "$tsvn" ]]; then
		echo -en "-- \n# Created with git-export-patch\n" >>"$f";
	else
		echo -en "-- \n# Created with git-export-tsvn-patch\n" >>"$f";

		pesubst -s '^(--- \S+)' -d '$1\t(revision '"$rev"')' -mm "$f";
		# Convert to p0
		pesubst -s '^--- a/(.*)' -d '--- $1' -mm "$f";
		pesubst -s '^\+\+\+ b/(.*)' -d '+++ $1' -mm "$f";
	fi;
done;
