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