#!/usr/bin/env perl

use warnings;
use strict;
use Encode;

## Checks the commit diff for suspicious lines not covered by util/checkwhite
## and util/unbrace, namely unresolved merges.

open DIFF, "git diff-index -p -M --cached HEAD --|"
    or die "pre-commit: Can't obtain the diff. Run git commit -n to ignore.\n";

my $found_bad = 0;
my $filename;
my $reported_filename = "";
my $lineno;
my $lastadd = 0; # a terrible hack
my $skip = 0;

sub bad_line
{
    return if $skip;
    my ($why, $noquote) = @_;
    if (!$found_bad)
    {
        print STDERR "*\n";
        print STDERR "* You have some suspicious patch lines:\n";
        print STDERR "*\n";
        $found_bad = 1;
    }
    if ($reported_filename ne $filename)
    {
        print STDERR "* $filename\n";
        $reported_filename = $filename;
    }
    print STDERR "  + $why (line $lineno)\n";
    #print STDERR "$_\n" unless $noquote;
}

while (<DIFF>)
{
    if (m|^diff --git a/(.*) b/\1$|)
    {
        $filename = $1;

        $skip = $filename =~ /\.(png|gif|ttf|ico|icns|fig|tex|eps|pdf)$/i
             || $filename =~ /\.(sln|vim|pbxproj|vsprops|plist|csproj|config|cs)$/i
             || $filename =~ /\.(vcproj|vcproj\.user|vcxproj|vcxproj\.filters)$/i
             || $filename =~ /^\.gitmodules$/
             || $filename =~ /\.(lex|tab)\./
             || $filename !~ /\./;
        next;
    }
    if (/^@@ -\S+ \+(\d+)/)
    {
        $lineno = $1 - 1;
        next;
    }
    if (/^ /)
    {
        $lineno++;
        next;
    }
    if (s/^\+//)
    {
        $lineno++;
        chomp;
        bad_line("unresolved merge conflict") if /^([<>])\1{6} |^={7}$/;
    }
    $lastadd = $lineno if $_ eq "";
}

if ($found_bad)
{
    print STDERR "\nPlease correct or, if it's a false positive,\n".
                 "commit -n to ignore. In that case, please report it as a bug.\n";
    exit 1;
}
