#!/usr/bin/perl -w

# Produce nice statistics from SubVersion repository

use strict;
use Regex::PreSuf;
use XML::Simple;

# directories to track statistic for
my @track = qw(
trunk
branches/hidra
branches/fsb
branches/tehnika
branches/humanistika
branches/ffzg
branches/unesco
branches/lezbib
branches/cpi
branches/drustvene
branches/biomed
trunk2
);

my @ignore = qw(
branches/biomed/openisis
branches/cpi/openisis
branches/drustvene/openisis
branches/ffzg/openisis
branches/fsb/openisis
branches/hidra/openisis
branches/humanistika/openisis
branches/lezbib/openisis
branches/tehnika/openisis
branches/unesco/openisis
openisis/
trunk2/openisis
trunk/openisis
);

my $from_rev = 1;
my $to_rev = 'HEAD';

my $track_re = presuf(@track);
my $ignore_re = presuf(@ignore);

my %add;
my %del;
my %lin;

# print headline

print STDERR "reading log\n";

open(LOG, "svn log -v --xml -r $from_rev:$to_rev |") || die "svn log: $!";
my $log;
while(<LOG>) {
	$log .= $_;
}
close(LOG);

my $fmt = "\n" . "-" x 79 . "\nr%5s| %8s | %s\n\n%s\n";

			


my $xml = XMLin($log, ForceArray => [ 'logentry', 'path' ]);
foreach my $e (@{$xml->{'logentry'}}) {
	my $rev = $e->{'revision'};
	my $date = $e->{'date'};
	$date =~ s/T/ /;
	$date =~ s/\..*$//;
	$date =~ s/(\d\d\d\d)-(\d\d)-(\d\d)/$2\/$3\/$1/ || die "can't parse date: $date";

	print "$rev,$date,";

	printf STDERR ($fmt, $e->{'revision'}, $e->{'author'}, $e->{'date'}, $e->{'msg'});
	foreach my $p (@{$e->{'paths'}->{'path'}}) {
		my ($action,$path) = ($p->{'action'},$p->{'content'});

		print STDERR "$action: $path\n";
	}

	# cound added/deleted lines for this revision
	
	open(DIFF, "svn diff -r".($rev-1).":$rev |") || die "svn diff: $!";

	my ($add,$del) = (0,0);

	my $skip = 1;
	my $path;

	while(<DIFF>) {
		chomp;
		if (/^Index:\s+(($track_re).*)$/) {
			next if (/^Index:\s+$ignore_re/);
			$path = $2;
		}
		next if (! $path);
		next if ($path && $skip && !/^@@/);
		$skip = 0;
		if (/^(\+|-|\s)/) {
			if ("$1" eq "+") {
				$add++;
			} elsif ("$1" eq "-") {
				$del--;
			}
		} elsif (/^$/) {
			$add{$path} += $add;
			$del{$path} += $del;
			$lin{$path} += $add + $del;

			undef $path;
			($add,$del,$skip) = (0,0,1);
		}
	}
	close(DIFF);

	foreach my $path (@track) {
		print
			'"',$path,'"',
			",",
			$lin{$path} || 0,
			",",
			$add{$path} || 0,
			",",
			$del{$path} || 0,
			",";
		$add{$path} = 0;
		$del{$path} = 0;
	}
	my $msg = $e->{'msg'};
	$msg =~ s/\s+/ /gs;
	$msg =~ s/"/\\"/g;
	print "\"$msg\"\n";
}
