#!/usr/bin/perl
#
# AUTHOR: "Hi! My name is Steven Rostedt. And I'm a branch hoarder"
#
# Transcript from one of the meetings of Hoarders Anonymous."

my $localrepo = ".";
my $repo = $localrepo;
my $remote = 0;
my $tags = 0;

while ($#ARGV ge 0 && $ARGV[0] =~ /^-/) {
	if ($ARGV[0] eq "-R") {
		shift;

		if (defined($ARGV[0])) {
			$repo=$ARGV[0];
			$expr = $ARGV[0];
		}
		$remote = 1;
		shift;
	} elsif ($ARGV[0] eq "-r") {
		$remote = 1;
		shift;
	} elsif ($ARGV[0] eq "-t") {
		$tags = 1;
		shift;
	} else {
		last;
	}
}


if ($#ARGV >= 0) {
	$expr = $ARGV[0];
}

open(IN, "git show-ref --head |") or die "open git remote";

my %branches;

while (<IN>) {
	my ($sha, $name) = split /\s+/;
	my $repl = "";

	if (!$remote) {
		if ($name =~ m,^refs/remotes/,) {
			next;
		}
	}
	if (!$tags) {
		if ($name =~ m,^refs/tags/,) {
			next;
		}
	}
	if ($tags || $remote) {
		if ($name =~ m,^refs/heads/,) {
			next;
		}
	}
	$name =~s!refs/(heads|tags|remotes)/!!;

	if (defined($expr)) {
		if ($name !~ m,$expr,) {
			next;
		}
	}
	$branches{$sha} = $name;
}

my %branch_time;
my %branch_date;
my %branch_hash;
my %branch_subject;

foreach my $sha (keys %branches) {
    my @lines = `git show --format="%ct <%ci> %h %s" -s $sha`;
  loop:
    foreach my $line (@lines) {
	chomp $line;
	my $branch = $branches{$sha};
	if ($line =~ /^(\S+) <(\S+).*?> (\S+) (.*)/) {
	    $branch_time{$branch} = $1;
	    $branch_date{$branch} = $2;
	    $branch_hash{$branch} = $3;
	    $branch_subject{$branch} = $4;
	    last loop;
	}
    }
}

foreach my $branch (sort { $branch_time{$a} <=> $branch_time{$b} } keys %branch_time) {
    my $hash = $branch_hash{$branch};
    my $subject = $branch_subject{$branch};
    my $date = $branch_date{$branch};
    if ($tags eq "--tags") {
	printf "%-10s %-13s %s\n", $hash, $date, $subject;
    } else {
	printf "%-10s %-13s %-35s %s\n", $hash, $date, $branch, $subject;
    }
}
