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