#!/pro/bin/perl

# git-hist file ...
# (c) 2008 H.Merijn Brand for PROCURA B.V.

use strict;
use warnings;

sub pr_time
{
    my @d = @_;
    sprintf "%4d-%02d-%02d %02d:%02d:%02d", 1900 + $d[5], ++$d[4], @d[3,2,1,0];
    } # pr_time

my @hsh;
my %log;
{   local @ARGV = ("git-log --pretty=format:'%h %ct %s' |");
    while (<>) {
	my ($hsh, $time, $text) = (m/^(\S+)\s+([0-9]+)\s+(.*)/);
	push @hsh, $hsh;
	$log{$hsh} = [ "", $text, pr_time localtime $time ];
	}
    }

{   local @ARGV = ("git-show-ref --tags |");
    while (<>) {
	m{(\S{7}).*/(.*)} or next;
	$log{$1}[0] = $2;
	}
    }

{   my $tag = "";
    my $inc;
    foreach my $hsh (reverse @hsh) {
	if ($log{$hsh}[0]) {
	    $tag = $log{$hsh}[0];
	    $inc = "001";
	    }
	elsif ($tag) {
	    $log{$hsh}[0] = sprintf "%-13s + %s", $tag, $inc++;
	    }
	}
    }

foreach my $file (@ARGV) {
    open my $blame, "-|", "git-blame $file" or next;
    while (<$blame>) {
	my ($hsh, $lnr, $txt) =
	    m/^\^?([0-9a-f]{7}).*?\s+([0-9]+)\)(.*)/ or next;
	printf "%.7s %s %-20s %5d:%s\n",
	    $hsh, $log{$hsh}[2], $log{$hsh}[0], $lnr, $txt;
	}
    }
