#!/usr/bin/perl
#
# TODO: Still fails when files may contain spaces
#
# Should accept multiple commit names or commit ranges
#
# I think it fails when the WD is not the root of the repo

use strict;
use Getopt::Std;
my %opt = ( q => 0,
            u => 0,
            d => 0,
            0 => $ENV{GIT_DIRTYFILES_NULSEP} ? 1 : 0,
    );


getopts('qud0', \%opt) or usage();
my $commit = shift;
my (@changed, @deleted);

sub cdup {
    my $names = shift;
    chomp(my ($cdup) = qx{git rev-parse --show-cdup 2> /dev/null});
    exit 1 unless $? == 0;
    s/^/$cdup/ for @$names;
}

if ($commit) {
    chomp(@changed = grep /\S/, qx{git show --pretty="format:" --name-only $commit});
    cdup(\@changed);
} else {
    chomp(@changed = qx{git status --porcelain});
    exit 1 unless $? == 0;
    @changed = grep !/^\?\? /, @changed unless $opt{q};
    @changed = grep  /^[UD]U /, @changed if $opt{u};
    @deleted = grep /^(D | D) /, @changed;
    @changed = grep ! /^(D | D) /, @changed;
    s/^.. // or die "<$_>???\n" for @changed;
    s/.* -> // for @changed;
    die "Fucking shell, how does it work?\n"
        if grep / /, @changed;

    cdup(\@changed);

    chomp(@changed = qx{find @changed -type f }) if @changed;
    exit 1 unless $? == 0;
}

my $sep = $opt{0} ? "\0" : "\n";
if ($opt{d}) {
    s/^.. // for @deleted;
    push @changed, @deleted;
}
print join $sep, @changed, "";
exit 0;

sub usage {
    print STDERR "git dirtyfiles [-q] [-u] [-d] [-0] [commit]
    list the names of files that have been changed since the last commit,
    one per line (or separated by NUL if -0 is given)

    With -q, include files that are unknown to Git

    With -u, include only files with merge conflicts

    With -d, include even the names of files that have been deleted
    and are no longer in the working tree.  Normally these are omitted.

    With a commit, list the names of the files that were changed in that commit
";
    exit 2;
}
