]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewDiff.pm
www: viewdiff: use return value for diff_hunk
[public-inbox.git] / lib / PublicInbox / ViewDiff.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # used by PublicInbox::View
5 # This adds CSS spans for diff highlighting.
6 # It also generates links for ViewVCS + SolverGit to show
7 # (or reconstruct) blobs.
8
9 package PublicInbox::ViewDiff;
10 use strict;
11 use v5.10.1;
12 use parent qw(Exporter);
13 our @EXPORT_OK = qw(flush_diff uri_escape_path);
14 use URI::Escape qw(uri_escape_utf8);
15 use PublicInbox::Hval qw(ascii_html to_attr);
16 use PublicInbox::Git qw(git_unquote);
17
18 my $OID_NULL = '0{7,}';
19 my $OID_BLOB = '[a-f0-9]{7,}';
20 my $LF = qr!\n!;
21 my $ANY = qr![^\n]!;
22 my $FN = qr!(?:"?[^/\n]+/[^\n]+|/dev/null)!;
23
24 # cf. git diff.c :: get_compact_summary
25 my $DIFFSTAT_COMMENT =
26         qr/(?: *\((?:new|gone|(?:(?:new|mode) [\+\-][lx]))\))? *\z/s;
27 my $NULL_TO_BLOB = qr/^(index $OID_NULL\.\.)($OID_BLOB)\b/ms;
28 my $BLOB_TO_NULL = qr/^index ($OID_BLOB)(\.\.$OID_NULL)\b/ms;
29 my $BLOB_TO_BLOB = qr/^index ($OID_BLOB)\.\.($OID_BLOB)/ms;
30 our $EXTRACT_DIFFS = qr/(
31                 (?:     # begin header stuff, don't capture filenames, here,
32                         # but instead wait for the --- and +++ lines.
33                         (?:^diff\x20--git\x20$FN\x20$FN$LF)
34
35                         # old mode || new mode || copy|rename|deleted|...
36                         (?:^[a-z]$ANY+$LF)*
37                 )? # end of optional stuff, everything below is required
38                 ^index\x20($OID_BLOB)\.\.($OID_BLOB)$ANY*$LF
39                 ^---\x20($FN)$LF
40                 ^\+{3}\x20($FN)$LF)/msx;
41 our $IS_OID = qr/\A$OID_BLOB\z/s;
42
43 sub uri_escape_path {
44         # '/' + $URI::Escape::Unsafe{RFC3986}
45         uri_escape_utf8($_[0], "^A-Za-z0-9\-\._~/");
46 }
47
48 # link to line numbers in blobs
49 sub diff_hunk ($$$) {
50         my ($dctx, $ca, $cb) = @_;
51         my ($oid_a, $oid_b, $spfx) = @$dctx{qw(oid_a oid_b spfx)};
52
53         if (defined($spfx) && defined($oid_a) && defined($oid_b)) {
54                 my ($n) = ($ca =~ /^-([0-9]+)/);
55                 $n = defined($n) ? "#n$n" : '';
56
57                 my $x = qq(@@ <a\nhref="$spfx$oid_a/s/$dctx->{Q}$n">$ca</a>);
58
59                 ($n) = ($cb =~ /^\+([0-9]+)/);
60                 $n = defined($n) ? "#n$n" : '';
61                 $x .= qq( <a\nhref="$spfx$oid_b/s/$dctx->{Q}$n">$cb</a> @@);
62         } else {
63                 "@@ $ca $cb @@";
64         }
65 }
66
67 sub oid ($$$) {
68         my ($dctx, $spfx, $oid) = @_;
69         defined($spfx) ? qq(<a\nhref="$spfx$oid/s/$dctx->{Q}">$oid</a>) : $oid;
70 }
71
72 # returns true if diffstat anchor written, false otherwise
73 sub anchor0 ($$$$) {
74         my ($dst, $ctx, $fn, $rest) = @_;
75
76         my $orig = $fn;
77
78         # normal git diffstat output is impossible to parse reliably
79         # without --numstat, and that isn't the default for format-patch.
80         # So only do best-effort handling of renames for common cases;
81         # which works well in practice. If projects put "=>", or trailing
82         # spaces in filenames, oh well :P
83         $fn =~ s/$DIFFSTAT_COMMENT//;
84         $fn =~ s/\{(?:.+) => (.+)\}/$1/ or $fn =~ s/.* => (.+)/$1/;
85         $fn = git_unquote($fn);
86
87         # long filenames will require us to check in anchor1()
88         push(@{$ctx->{-long_path}}, $fn) if $fn =~ s!\A\.\.\./?!!;
89
90         if (defined(my $attr = to_attr($ctx->{-apfx}.$fn))) {
91                 $ctx->{-anchors}->{$attr} = 1;
92                 my $spaces = ($orig =~ s/( +)\z//) ? $1 : '';
93                 $$dst .= " <a\nid=i$attr\nhref=#$attr>" .
94                         ascii_html($orig) . '</a>' . $spaces .
95                         $ctx->{-linkify}->to_html($rest);
96                 return 1;
97         }
98         undef;
99 }
100
101 # returns "diff --git" anchor destination, undef otherwise
102 sub anchor1 ($$) {
103         my ($ctx, $pb) = @_;
104         my $attr = to_attr($ctx->{-apfx}.$pb) // return;
105
106         my $ok = delete $ctx->{-anchors}->{$attr};
107
108         # unlikely, check the end of long path names we captured,
109         # assume diffstat and diff output follow the same order,
110         # and ignore different ordering (could be malicious input)
111         unless ($ok) {
112                 my $fn = shift(@{$ctx->{-long_path}}) // return;
113                 $pb =~ /\Q$fn\E\z/s or return;
114                 $attr = to_attr($ctx->{-apfx}.$fn) // return;
115                 $ok = delete $ctx->{-anchors}->{$attr} // return;
116         }
117         $ok ? "<a\nhref=#i$attr\nid=$attr>diff</a> --git" : undef
118 }
119
120 sub diff_header ($$$) {
121         my ($x, $ctx, $top) = @_;
122         my (undef, undef, $pa, $pb) = splice(@$top, 0, 4); # ignore oid_{a,b}
123         my $spfx = $ctx->{-spfx};
124         my $dctx = { spfx => $spfx };
125
126         # get rid of leading "a/" or "b/" (or whatever --{src,dst}-prefix are)
127         $pa = (split(m'/', git_unquote($pa), 2))[1] if $pa ne '/dev/null';
128         $pb = (split(m'/', git_unquote($pb), 2))[1] if $pb ne '/dev/null';
129         if ($pa eq $pb && $pb ne '/dev/null') {
130                 $dctx->{Q} = '?b='.uri_escape_path($pb);
131         } else {
132                 my @q;
133                 if ($pb ne '/dev/null') {
134                         push @q, 'b='.uri_escape_path($pb);
135                 }
136                 if ($pa ne '/dev/null') {
137                         push @q, 'a='.uri_escape_path($pa);
138                 }
139                 $dctx->{Q} = '?'.join('&amp;', @q);
140         }
141
142         # linkify early and all at once, since we know the following
143         # subst ops on $$x won't need further escaping:
144         $$x = $ctx->{-linkify}->to_html($$x);
145
146         # no need to capture oid_a and oid_b on add/delete,
147         # we just linkify OIDs directly via s///e in conditional
148         if ($$x =~ s/$NULL_TO_BLOB/$1 . oid($dctx, $spfx, $2)/e) {
149                 push @{$ctx->{-qry}->{dfpost}}, $2;
150         } elsif ($$x =~ s/$BLOB_TO_NULL/'index '.oid($dctx, $spfx, $1).$2/e) {
151                 push @{$ctx->{-qry}->{dfpre}}, $1;
152         } elsif ($$x =~ $BLOB_TO_BLOB) {
153                 # modification-only, not add/delete:
154                 # linkify hunk headers later using oid_a and oid_b
155                 @$dctx{qw(oid_a oid_b)} = ($1, $2);
156                 push @{$ctx->{-qry}->{dfpre}}, $1;
157                 push @{$ctx->{-qry}->{dfpost}}, $2;
158         } else {
159                 warn "BUG? <$$x> had no ^index line";
160         }
161         $$x =~ s!^diff --git!anchor1($ctx, $pb) // 'diff --git'!ems;
162         my $dst = $ctx->{obuf};
163         $$dst .= qq(<span\nclass="head">);
164         $$dst .= $$x;
165         $$dst .= '</span>';
166         $dctx;
167 }
168
169 sub diff_before_or_after ($$) {
170         my ($ctx, $x) = @_;
171         my $linkify = $ctx->{-linkify};
172         my $dst = $ctx->{obuf};
173         if (exists $ctx->{-anchors} && $$x =~ /\A(.*?) # likely "---\n"
174                         # diffstat lines:
175                         ((?:^\x20(?:[^\n]+?)(?:\x20+\|\x20[^\n]*\n))+)
176                         (\x20[0-9]+\x20files?\x20)changed,([^\n]+\n)
177                         (.*?)\z/msx) { # notes, commit message, etc
178                 undef $$x;
179                 my @x = ($5, $4, $3, $2, $1);
180                 $$dst .= $linkify->to_html(pop @x); # uninteresting prefix
181                 for my $l (split(/^/m, pop(@x))) { # per-file diffstat lines
182                         $l =~ /^ (.+)( +\| .*\z)/s and
183                                 anchor0($dst, $ctx, $1, $2) and next;
184                         $$dst .= $linkify->to_html($l);
185                 }
186                 $$dst .= $x[2]; # $3 /^ \d+ files? /
187                 my $ch = $ctx->{changed_href} // '#related';
188                 $$dst .= qq(<a href="$ch">changed</a>,);
189                 $$dst .= ascii_html($x[1]); # $4: insertions/deletions
190                 $$dst .= $linkify->to_html($x[0]); # notes, commit message, etc
191         } else {
192                 $$dst .= $linkify->to_html($$x);
193         }
194 }
195
196 # callers must do CRLF => LF conversion before calling this
197 sub flush_diff ($$) {
198         my ($ctx, $cur) = @_;
199
200         my @top = split($EXTRACT_DIFFS, $$cur);
201         undef $$cur; # free memory
202
203         my $linkify = $ctx->{-linkify};
204         my $dst = $ctx->{obuf};
205         my $dctx; # {}, keys: Q, oid_a, oid_b
206
207         while (defined(my $x = shift @top)) {
208                 if (scalar(@top) >= 4 &&
209                                 $top[1] =~ $IS_OID &&
210                                 $top[0] =~ $IS_OID) {
211                         $dctx = diff_header(\$x, $ctx, \@top);
212                 } elsif ($dctx) {
213                         my $after = '';
214
215                         # Quiet "Complex regular subexpression recursion limit"
216                         # warning.  Perl will truncate matches upon hitting
217                         # that limit, giving us more (and shorter) scalars than
218                         # would be ideal, but otherwise it's harmless.
219                         #
220                         # We could replace the `+' metacharacter with `{1,100}'
221                         # to limit the matches ourselves to 100, but we can
222                         # let Perl do it for us, quietly.
223                         no warnings 'regexp';
224
225                         for my $s (split(/((?:(?:^\+[^\n]*\n)+)|
226                                         (?:(?:^-[^\n]*\n)+)|
227                                         (?:^@@ [^\n]+\n))/xsm, $x)) {
228                                 if (!defined($dctx)) {
229                                         $after .= $s;
230                                 } elsif ($s =~ s/\A@@ (\S+) (\S+) @@//) {
231                                         $$dst .= qq(<span\nclass="hunk">);
232                                         $$dst .= diff_hunk($dctx, $1, $2);
233                                         $$dst .= $linkify->to_html($s);
234                                         $$dst .= '</span>';
235                                 } elsif ($s =~ /\A\+/) {
236                                         $$dst .= qq(<span\nclass="add">);
237                                         $$dst .= $linkify->to_html($s);
238                                         $$dst .= '</span>';
239                                 } elsif ($s =~ /\A-- $/sm) { # email sig starts
240                                         $dctx = undef;
241                                         $after .= $s;
242                                 } elsif ($s =~ /\A-/) {
243                                         $$dst .= qq(<span\nclass="del">);
244                                         $$dst .= $linkify->to_html($s);
245                                         $$dst .= '</span>';
246                                 } else {
247                                         $$dst .= $linkify->to_html($s);
248                                 }
249                         }
250                         diff_before_or_after($ctx, \$after) unless $dctx;
251                 } else {
252                         diff_before_or_after($ctx, \$x);
253                 }
254         }
255 }
256
257 1;