e07cd5931dcdbd476fceddaff9825163a20ed54d
   1package DiffHighlight;
   2
   3use 5.008;
   4use warnings FATAL => 'all';
   5use strict;
   6
   7# Highlight by reversing foreground and background. You could do
   8# other things like bold or underline if you prefer.
   9my @OLD_HIGHLIGHT = (
  10        color_config('color.diff-highlight.oldnormal'),
  11        color_config('color.diff-highlight.oldhighlight', "\x1b[7m"),
  12        color_config('color.diff-highlight.oldreset', "\x1b[27m")
  13);
  14my @NEW_HIGHLIGHT = (
  15        color_config('color.diff-highlight.newnormal', $OLD_HIGHLIGHT[0]),
  16        color_config('color.diff-highlight.newhighlight', $OLD_HIGHLIGHT[1]),
  17        color_config('color.diff-highlight.newreset', $OLD_HIGHLIGHT[2])
  18);
  19
  20my $RESET = "\x1b[m";
  21my $COLOR = qr/\x1b\[[0-9;]*m/;
  22my $BORING = qr/$COLOR|\s/;
  23
  24# The patch portion of git log -p --graph should only ever have preceding | and
  25# not / or \ as merge history only shows up on the commit line.
  26my $GRAPH = qr/$COLOR?\|$COLOR?\s+/;
  27
  28my @removed;
  29my @added;
  30my $in_hunk;
  31
  32our $line_cb = sub { print @_ };
  33our $flush_cb = sub { local $| = 1 };
  34
  35sub handle_line {
  36        local $_ = shift;
  37
  38        if (!$in_hunk) {
  39                $line_cb->($_);
  40                $in_hunk = /^$GRAPH*$COLOR*\@\@ /;
  41        }
  42        elsif (/^$GRAPH*$COLOR*-/) {
  43                push @removed, $_;
  44        }
  45        elsif (/^$GRAPH*$COLOR*\+/) {
  46                push @added, $_;
  47        }
  48        else {
  49                flush();
  50                $line_cb->($_);
  51                $in_hunk = /^$GRAPH*$COLOR*[\@ ]/;
  52        }
  53
  54        # Most of the time there is enough output to keep things streaming,
  55        # but for something like "git log -Sfoo", you can get one early
  56        # commit and then many seconds of nothing. We want to show
  57        # that one commit as soon as possible.
  58        #
  59        # Since we can receive arbitrary input, there's no optimal
  60        # place to flush. Flushing on a blank line is a heuristic that
  61        # happens to match git-log output.
  62        if (!length) {
  63                $flush_cb->();
  64        }
  65}
  66
  67sub flush {
  68        # Flush any queued hunk (this can happen when there is no trailing
  69        # context in the final diff of the input).
  70        show_hunk(\@removed, \@added);
  71        @removed = ();
  72        @added = ();
  73}
  74
  75sub highlight_stdin {
  76        while (<STDIN>) {
  77                handle_line($_);
  78        }
  79        flush();
  80}
  81
  82# Ideally we would feed the default as a human-readable color to
  83# git-config as the fallback value. But diff-highlight does
  84# not otherwise depend on git at all, and there are reports
  85# of it being used in other settings. Let's handle our own
  86# fallback, which means we will work even if git can't be run.
  87sub color_config {
  88        my ($key, $default) = @_;
  89        my $s = `git config --get-color $key 2>/dev/null`;
  90        return length($s) ? $s : $default;
  91}
  92
  93sub show_hunk {
  94        my ($a, $b) = @_;
  95
  96        # If one side is empty, then there is nothing to compare or highlight.
  97        if (!@$a || !@$b) {
  98                $line_cb->(@$a, @$b);
  99                return;
 100        }
 101
 102        # If we have mismatched numbers of lines on each side, we could try to
 103        # be clever and match up similar lines. But for now we are simple and
 104        # stupid, and only handle multi-line hunks that remove and add the same
 105        # number of lines.
 106        if (@$a != @$b) {
 107                $line_cb->(@$a, @$b);
 108                return;
 109        }
 110
 111        my @queue;
 112        for (my $i = 0; $i < @$a; $i++) {
 113                my ($rm, $add) = highlight_pair($a->[$i], $b->[$i]);
 114                $line_cb->($rm);
 115                push @queue, $add;
 116        }
 117        $line_cb->(@queue);
 118}
 119
 120sub highlight_pair {
 121        my @a = split_line(shift);
 122        my @b = split_line(shift);
 123
 124        # Find common prefix, taking care to skip any ansi
 125        # color codes.
 126        my $seen_plusminus;
 127        my ($pa, $pb) = (0, 0);
 128        while ($pa < @a && $pb < @b) {
 129                if ($a[$pa] =~ /$COLOR/) {
 130                        $pa++;
 131                }
 132                elsif ($b[$pb] =~ /$COLOR/) {
 133                        $pb++;
 134                }
 135                elsif ($a[$pa] eq $b[$pb]) {
 136                        $pa++;
 137                        $pb++;
 138                }
 139                elsif (!$seen_plusminus && $a[$pa] eq '-' && $b[$pb] eq '+') {
 140                        $seen_plusminus = 1;
 141                        $pa++;
 142                        $pb++;
 143                }
 144                else {
 145                        last;
 146                }
 147        }
 148
 149        # Find common suffix, ignoring colors.
 150        my ($sa, $sb) = ($#a, $#b);
 151        while ($sa >= $pa && $sb >= $pb) {
 152                if ($a[$sa] =~ /$COLOR/) {
 153                        $sa--;
 154                }
 155                elsif ($b[$sb] =~ /$COLOR/) {
 156                        $sb--;
 157                }
 158                elsif ($a[$sa] eq $b[$sb]) {
 159                        $sa--;
 160                        $sb--;
 161                }
 162                else {
 163                        last;
 164                }
 165        }
 166
 167        if (is_pair_interesting(\@a, $pa, $sa, \@b, $pb, $sb)) {
 168                return highlight_line(\@a, $pa, $sa, \@OLD_HIGHLIGHT),
 169                       highlight_line(\@b, $pb, $sb, \@NEW_HIGHLIGHT);
 170        }
 171        else {
 172                return join('', @a),
 173                       join('', @b);
 174        }
 175}
 176
 177# we split either by $COLOR or by character. This has the side effect of
 178# leaving in graph cruft. It works because the graph cruft does not contain "-"
 179# or "+"
 180sub split_line {
 181        local $_ = shift;
 182        return utf8::decode($_) ?
 183                map { utf8::encode($_); $_ }
 184                        map { /$COLOR/ ? $_ : (split //) }
 185                        split /($COLOR+)/ :
 186                map { /$COLOR/ ? $_ : (split //) }
 187                split /($COLOR+)/;
 188}
 189
 190sub highlight_line {
 191        my ($line, $prefix, $suffix, $theme) = @_;
 192
 193        my $start = join('', @{$line}[0..($prefix-1)]);
 194        my $mid = join('', @{$line}[$prefix..$suffix]);
 195        my $end = join('', @{$line}[($suffix+1)..$#$line]);
 196
 197        # If we have a "normal" color specified, then take over the whole line.
 198        # Otherwise, we try to just manipulate the highlighted bits.
 199        if (defined $theme->[0]) {
 200                s/$COLOR//g for ($start, $mid, $end);
 201                chomp $end;
 202                return join('',
 203                        $theme->[0], $start, $RESET,
 204                        $theme->[1], $mid, $RESET,
 205                        $theme->[0], $end, $RESET,
 206                        "\n"
 207                );
 208        } else {
 209                return join('',
 210                        $start,
 211                        $theme->[1], $mid, $theme->[2],
 212                        $end
 213                );
 214        }
 215}
 216
 217# Pairs are interesting to highlight only if we are going to end up
 218# highlighting a subset (i.e., not the whole line). Otherwise, the highlighting
 219# is just useless noise. We can detect this by finding either a matching prefix
 220# or suffix (disregarding boring bits like whitespace and colorization).
 221sub is_pair_interesting {
 222        my ($a, $pa, $sa, $b, $pb, $sb) = @_;
 223        my $prefix_a = join('', @$a[0..($pa-1)]);
 224        my $prefix_b = join('', @$b[0..($pb-1)]);
 225        my $suffix_a = join('', @$a[($sa+1)..$#$a]);
 226        my $suffix_b = join('', @$b[($sb+1)..$#$b]);
 227
 228        return $prefix_a !~ /^$GRAPH*$COLOR*-$BORING*$/ ||
 229               $prefix_b !~ /^$GRAPH*$COLOR*\+$BORING*$/ ||
 230               $suffix_a !~ /^$BORING*$/ ||
 231               $suffix_b !~ /^$BORING*$/;
 232}