1
-#!/usr/bin/perl
1
+package DiffHighlight;
2
3
use 5.008;
4
use warnings FATAL => 'all';
29
my @added;
30
my $in_hunk;
31
32
-# Some scripts may not realize that SIGPIPE is being ignored when launching the
33
-# pager--for instance scripts written in Python.
34
-$SIG{PIPE} = 'DEFAULT';
32
+our $line_cb = sub { print @_ };
33
+our $flush_cb = sub { local $| = 1 };
34
+
35
+sub handle_line {
36
+ local $_ = shift;
37
36
-while (<>) {
38
if (!$in_hunk) {
38
- print;
39
+ $line_cb->($_);
40
$in_hunk = /^$GRAPH*$COLOR*\@\@ /;
41
}
42
elsif (/^$GRAPH*$COLOR*-/) {
50
@removed = ();
51
@added = ();
52
52
- print;
53
+ $line_cb->($_);
54
$in_hunk = /^$GRAPH*$COLOR*[\@ ]/;
55
}
56
63
# place to flush. Flushing on a blank line is a heuristic that
64
# happens to match git-log output.
65
if (!length) {
65
- local $| = 1;
66
+ $flush_cb->();
67
}
68
}
69
69
-# Flush any queued hunk (this can happen when there is no trailing context in
70
-# the final diff of the input).
71
-show_hunk(\@removed, \@added);
70
+sub flush {
71
+ # Flush any queued hunk (this can happen when there is no trailing
72
+ # context in the final diff of the input).
73
+ show_hunk(\@removed, \@added);
74
+}
75
73
-exit 0;
76
+sub highlight_stdin {
77
+ while (<STDIN>) {
78
+ handle_line($_);
79
+ }
80
+ flush();
81
+}
82
83
# Ideally we would feed the default as a human-readable color to
84
# git-config as the fallback value. But diff-highlight does
96
97
# If one side is empty, then there is nothing to compare or highlight.
98
if (!@$a || !@$b) {
91
- print @$a, @$b;
99
+ $line_cb->(@$a, @$b);
100
return;
101
}
102
105
# stupid, and only handle multi-line hunks that remove and add the same
106
# number of lines.
107
if (@$a != @$b) {
100
- print @$a, @$b;
108
+ $line_cb->(@$a, @$b);
109
return;
110
}
111
112
my @queue;
113
for (my $i = 0; $i < @$a; $i++) {
114
my ($rm, $add) = highlight_pair($a->[$i], $b->[$i]);
107
- print $rm;
115
+ $line_cb->($rm);
116
push @queue, $add;
117
}
110
- print @queue;
118
+ $line_cb->(@queue);
119
}
120
121
sub highlight_pair {