#!/usr/bin/env perl
#
# @brief  Git filter to implement rcs keyword expansion as seen in cvs and svn.
# @author Martin Turon
#
# Usage:
#    .git_filter/rcs-keywords.smudge file_path < file_contents
# 
# To add keyword expansion:
#    <project>/.gitattributes                    - *.c filter=rcs-keywords
#    <project>/.git_filters/rcs-keywords.smudge  - copy this file to project
#    <project>/.git_filters/rcs-keywords.clean   - copy companion to project
#    ~/.gitconfig                                - add [filter] lines below
#
# [filter "rcs-keywords"]
#	clean  = .git_filters/rcs-keywords.clean
#	smudge = .git_filters/rcs-keywords.smudge %f
#
# Copyright (c) 2009-2011 Turon Technologies, Inc.  All rights reserved.

$path = shift;
$path =~ /.*\/(.*)/;
$filename = $1;

if (0 == length($filename)) {
	$filename = $path;
}

# Need to grab filename and to use git log for this to be accurate.
$rev = `git log --date=iso -- | head -n 3`;
$rev =~ /^Author:\s*(.*)\s*$/m;
$author = $1;
$author =~ /\s*(.*)\s*<.*/;
$name = $1;
$rev =~ /^Date:\s*(.*)\s*$/m;
$date = $1;
$rev =~ /^commit (.*)$/m;
$ident = $1;
$shortident = substr($ident,0, 6);

while (<STDIN>) {
    s/\$Date(((::)*)[^\$]*)\$/TR("\$Date",$1,$date,$2,"\$")/eo;
    s/\$Author(((::)*)[^\$]*)\$/TR("\$Author",$1,$author,$2,"\$")/eo;
    s/\$Id(((::)*)[^\$]*)\$/TR("\$Id",$1,"$filename | $date | $name",$2,"\$")/eo;
    s/\$File(((::)*)[^\$]*)\$/TR("\$File",$1,$filename,$2,"\$")/eo;
    s/\$Source(((::)*)[^\$]*)\$/TR("\$Source",$1,$path,$2,"\$")/eo;
    s/\$Rev(((::)*)[^\$]*)\$/TR("\$Rev",$1,$shortident,$2,"\$")/eo;
    s/\$Revision(((::)*)[^\$]*)\$/TR("\$Revision",$1,$ident,$2,"\$")/eo;
} continue {
    print or die "-p destination: $!\n";
}

sub TR{
    my ($pre,$from,$to,$fix,$post)=@_;
    return $pre.$to.$post if($fix eq '');

    $pre.=$fix;
    if(length($from)<length($to)+length($fix)){
         $to=substr($to,0,length($from)-length($fix));
    }else{
         $to.=' ' x (length($from)-length($to)-length($fix));
    }
    return $pre.$to.$post;
}
