#!/usr/bin/perl

use Data::Dumper;

#for b in `git branch --no-color|sed 's/.* //'`; do echo [$b]; for t in `git tag`; do if git branch --contains $t|sed 's/.* //'|grep -q ^$b\$; then echo "  $t"; fi; done; done

sub gitbranches {
	( my $dir = shift ) =~ s/\/$//;
	my $branches = {};
	my $cmd = "git --git-dir=\"$dir/.git\" --work-tree=\"$dir\""
		. " branch --no-color";

	open( my $git, "$cmd|" ) || die( $! );

	while ( <$git> ) {
		chomp();

		if ( $_ =~ /\s*\*?\s*(.*)$/ ) {
			$branches->{$1} = [];
			}
		}

	close( $git );

	return( $branches );
	}

sub gitcontains {
	( my $dir = shift ) =~ s/\/$//;
	my $branches = gitbranches( $dir );
	my $tags = gittags( $dir );

	foreach my $tag ( @$tags ) {
		my $cmd = "git --git-dir=\"$dir/.git\" --work-tree=\"$dir\""
			. " branch --contains \"$tag\"";

		open( my $git, "$cmd|" ) || die( $! );

		while ( <$git> ) {
			chomp();

			if ( $_ =~ /\s*\*?\s*(.*)$/ ) {
				push( @{$branches->{$1}}, $tag );

				last;
				}
			}
		}

	return( $branches );
	}

sub gittags {
	( my $dir = shift ) =~ s/\/$//;
	my $tags = [];
	my $cmd = "git --git-dir=\"$dir/.git\" --work-tree=\"$dir\" tag";

	open( my $git, "$cmd|" ) || die( $! );

	while ( <$git> ) {
		chomp();

		push( @$tags, $_ );
		}

	close( $git );

	return( $tags );
	}

my $branches = gitcontains( $ARGV[0] );

foreach my $branch ( sort( keys( %$branches ) ) ) {
	print "[$branch]\n";

	foreach my $tag ( @{$branches->{$branch}} ) {
		print "  $tag\n";
		}
	}
