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