###################################################
# file_history_maker.pl
# ver.1.2
# (C) 2015-2017 Hirohisa Aman <aman@ehime-u.ac.jp>
###################################################
# [Usage]
# perl file_history_maker.pl  file_path
#
#
# [Output]
# The change history of the specified file in the following TAB separated form:
#
#    n  N  file_path  hash  date  author  type  message
#
# where
#   n: commitment number (1, 2, ...)
#   N: total count of commitments
#   type: change type of file such as A, M and so on
#   "message": quoted one-line commitment message, which is made from
#              the original commetment message by erasing their new-line
#              characters
use strict;

die("*** Error *** specify a file path!\n") if ( $#ARGV < 0 );
die("*** Error *** Too many files specified!\n") if ( $#ARGV > 0 );

my $file = $ARGV[0];
my @results = `git log --reverse --name-status $file`;

my @commit_hash_values = ();
my @authors = ();
my @dates = ();
my @messages = ();
my @types = ();
my $in_message = 0;
my $message = "";
for ( my $i = 0; $i <= $#results; $i++ ){
    chomp($results[$i]);
    if ( $results[$i] =~ /^commit / ){
	push( @commit_hash_values, substr($results[$i], length("commit ")) );
    }
    elsif ( $results[$i] =~ /^Author: / ){
	push( @authors, &trim( substr($results[$i], length("Author: ")) ) );
    }
    elsif ( $results[$i] =~ /^Date:   / ){
	push( @dates, substr($results[$i], length("Date:   ")) );
	$in_message = 1;
	$message = "";
    }
    elsif ( $results[$i] =~ /^[A-Z]\t/ ){
	(my $type, my $path) = split(/\t/, $results[$i]);
	push( @types, substr($results[$i], 0, 1) );
	$in_message = 0;
	$message = &trim( $message );
	$message = &replace_tab( $message );
	push( @messages, $message );
    }
    elsif ( $in_message == 1 ){
	$results[$i] = &trim_left( $results[$i] );
	$message .= "$results[$i] ";
    }
}

my $N = $#commit_hash_values + 1;
for ( my $i = 0; $i < $N; $i++ ){
    print $i+1, "\t$N\t";
    print "$file\t$commit_hash_values[$i]\t$dates[$i]\t",
          "$authors[$i]\t$types[$i]\t$messages[$i]\n";
}


sub trim_left {
    my $arg = $_[0];
    $arg =~ s/^(\s)*//;
    return $arg;
}

sub trim_right {
    my $arg = $_[0];
    $arg =~ s/(\s)*$//;
    return $arg;
}

sub trim {
    my $arg = $_[0];
    $arg = &trim_left( $arg );
    $arg = &trim_right( $arg );
    return $arg;
}

sub replace_tab {
    my $arg = $_[0];
    $arg =~ s/\t/   /g;
    return $arg;
}
