#!/usr/bin/perl
#
# authors - List files in get repo by author, using wildcards
#
# Copyright 2013 by Werner Almesberger
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#


$WIDTH = 79;

open(LOG, "git ls-files |") || die "popen ls-files";
while (<LOG>) {
	chop;
	$e{$_} = 1;
}
close LOG;

open(LOG, "git log --format='%an <%ae>' --name-only --no-merges |") ||
   die "popen log";
while (<LOG>) {
	chop;
	if (/^$/) {
		$a = $last;
		undef $last;
		next;
	}
	if (defined $e{$last}) {
		push @{ $f{$last} }, $a;
		$a{$a} = 1;
	}
	$last = $_;
}
if (defined $e{$last}) {
	push @{ $f{$last} }, $a;
	$a{$a} = 1;
}
close LOG;


sub add
{
	local ($a, $f) = @_;
	local $d, $n, $t;
	local $best, $best_k, $k;

	if ($f =~ m|/([^/]+)$|) {
		$d = "$`/";
		$n = $1;
	} else {
		$d = "";
		$n = $f;
	}
	undef $best;
	undef $best_k;
	LONGER: for ($i = 0; $i <= length $n; $i++) {
		$t = $d.substr($n, 0, $i);
		$k = 0;
		FIT: for (keys %f) {
			next unless substr($_, 0, length $t) eq $t;
			$k++;
			for (@{ $f{$_} }) {
				next FIT if $_ eq $a;
			}
			next LONGER;
		}
		last if $best_k > $k;
		$best = $t;
		$best_k = $k;
	}
	if ($best eq $f) {
		$m{$f} = 1;
	} else {
		$m{"$best*"} = 1;
	}
}


for $a (sort keys %a) {
	undef %m;
	for $f (keys %f) {
		for (@{ $f{$f} }) {
			next if $_ ne $a;
			&add($a, $f);
			last;
		}
	}
	next unless %m;
	print $a, "\n";
	undef $p;
	for (sort keys %m) {
		if (!defined $p) {
			$p = $_;
			next;
		}
		if (length("$p $_") > $WIDTH) {
			print "$p\n";
			$p = $_;
		} else {
			$p .= " $_";
		}
	}
	print $p, "\n\n";
}
