]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewDiff.pm
No ext_urls
[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 v5.12;
11 use parent qw(Exporter);
12 our @EXPORT_OK = qw(flush_diff uri_escape_path);
13 use URI::Escape qw(uri_escape_utf8);
14 use PublicInbox::Hval qw(ascii_html to_attr);
15 use PublicInbox::Git qw(git_unquote);
16
17 my $OID_NULL = '0{7,}';
18 my $OID_BLOB = '[a-f0-9]{7,}';
19 my $LF = qr!\n!;
20 my $ANY = qr![^\n]!;
21 my $FN = qr!(?:"?[^/\n]+/[^\n]+|/dev/null)!;
22
23 # cf. git diff.c :: get_compact_summary
24 my $DIFFSTAT_COMMENT =
25         qr/(?: *\((?:new|gone|(?:(?:new|mode) [\+\-][lx]))\))? *\z/s;
26 my $NULL_TO_BLOB = qr/^(index $OID_NULL\.\.)($OID_BLOB)\b/ms;
27 my $BLOB_TO_NULL = qr/^index ($OID_BLOB)(\.\.$OID_NULL)\b/ms;
28 my $BLOB_TO_BLOB = qr/^index ($OID_BLOB)\.\.($OID_BLOB)/ms;
29 our $EXTRACT_DIFFS = qr/(
30                 (?:     # begin header stuff, don't capture filenames, here,
31                         # but instead wait for the --- and +++ lines.
32                         (?:^diff\x20--git\x20$FN\x20$FN$LF)
33
34                         # old mode || new mode || copy|rename|deleted|...
35                         (?:^[a-z]$ANY+$LF)*
36                 )? # end of optional stuff, everything below is required
37                 ^index\x20($OID_BLOB)\.\.($OID_BLOB)$ANY*$LF
38                 ^---\x20($FN)$LF
39                 ^\+{3}\x20($FN)$LF)/msx;
40 our $IS_OID = qr/\A$OID_BLOB\z/s;
41
42 sub uri_escape_path {
43         # '/' + $URI::Escape::Unsafe{RFC3986}
44         uri_escape_utf8($_[0], "^A-Za-z0-9\-\._~/");
45 }
46
47 # link to line numbers in blobs
48 sub diff_hunk ($$$) {
49         my ($dctx, $ca, $cb) = @_;
50         my ($oid_a, $oid_b, $spfx) = @$dctx{qw(oid_a oid_b spfx)};
51
52         if (defined($spfx) && defined($oid_a) && defined($oid_b)) {
53                 my $n = ($ca =~ /^-([0-9]+)/) ? "#n$1" : '';
54                 my $x = qq(@@ <a\nhref="$spfx$oid_a/s/$dctx->{Q}$n">$ca</a>);
55
56                 $n = ($cb =~ /^\+([0-9]+)/) ? "#n$1" : '';
57                 $x .= qq( <a\nhref="$spfx$oid_b/s/$dctx->{Q}$n">$cb</a> @@);
58         } else {
59                 "@@ $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 ($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         my $attr = to_attr($ctx->{-apfx}.$fn) // return;
87         $ctx->{-anchors}->{$attr} = 1;
88         my $spaces = ($orig =~ s/( +)\z//) ? $1 : '';
89         print { $ctx->{zfh} } " <a\nid=i$attr\nhref=#$attr>",
90                         ascii_html($orig), '</a>', $spaces,
91                         $ctx->{-linkify}->to_html($rest);
92 }
93
94 # returns "diff --git" anchor destination, undef otherwise
95 sub anchor1 ($$) {
96         my ($ctx, $pb) = @_;
97         my $attr = to_attr($ctx->{-apfx}.$pb) // return;
98
99         my $ok = delete $ctx->{-anchors}->{$attr};
100
101         # unlikely, check the end of long path names we captured,
102         # assume diffstat and diff output follow the same order,
103         # and ignore different ordering (could be malicious input)
104         unless ($ok) {
105                 my $fn = shift(@{$ctx->{-long_path}}) // return;
106                 $pb =~ /\Q$fn\E\z/s or return;
107                 $attr = to_attr($ctx->{-apfx}.$fn) // return;
108                 $ok = delete $ctx->{-anchors}->{$attr} // return;
109         }
110         $ok ? "<a\nhref=#i$attr\nid=$attr>diff</a> --git" : undef
111 }
112
113 sub diff_header ($$$) {
114         my ($x, $ctx, $top) = @_;
115         my (undef, undef, $pa, $pb) = splice(@$top, 0, 4); # ignore oid_{a,b}
116         my $spfx = $ctx->{-spfx};
117         my $dctx = { spfx => $spfx };
118
119         # get rid of leading "a/" or "b/" (or whatever --{src,dst}-prefix are)
120         $pa = (split(m'/', git_unquote($pa), 2))[1] if $pa ne '/dev/null';
121         $pb = (split(m'/', git_unquote($pb), 2))[1] if $pb ne '/dev/null';
122         if ($pa eq $pb && $pb ne '/dev/null') {
123                 $dctx->{Q} = '?b='.uri_escape_path($pb);
124         } else {
125                 my @q;
126                 push @q, 'b='.uri_escape_path($pb) if $pb ne '/dev/null';
127                 push @q, 'a='.uri_escape_path($pa) if $pa ne '/dev/null';
128                 $dctx->{Q} = '?'.join('&amp;', @q);
129         }
130
131         # linkify early and all at once, since we know the following
132         # subst ops on $$x won't need further escaping:
133         $$x = $ctx->{-linkify}->to_html($$x);
134
135         # no need to capture oid_a and oid_b on add/delete,
136         # we just linkify OIDs directly via s///e in conditional
137         if ($$x =~ s/$NULL_TO_BLOB/$1 . oid($dctx, $spfx, $2)/e) {
138                 push @{$ctx->{-qry}->{dfpost}}, $2;
139         } elsif ($$x =~ s/$BLOB_TO_NULL/'index '.oid($dctx, $spfx, $1).$2/e) {
140                 push @{$ctx->{-qry}->{dfpre}}, $1;
141         } elsif ($$x =~ $BLOB_TO_BLOB) {
142                 # modification-only, not add/delete:
143                 # linkify hunk headers later using oid_a and oid_b
144                 @$dctx{qw(oid_a oid_b)} = ($1, $2);
145                 push @{$ctx->{-qry}->{dfpre}}, $1;
146                 push @{$ctx->{-qry}->{dfpost}}, $2;
147         } else {
148                 warn "BUG? <$$x> had no ^index line";
149         }
150         $$x =~ s!^diff --git!anchor1($ctx, $pb) // 'diff --git'!ems;
151         print { $ctx->{zfh} } qq(<span\nclass="head">), $$x, '</span>';
152         $dctx;
153 }
154
155 sub diff_before_or_after ($$) {
156         my ($ctx, $x) = @_;
157         if (exists $ctx->{-anchors} && $$x =~ # diffstat lines:
158                         /((?:^\x20(?:[^\n]+?)(?:\x20+\|\x20[^\n]*\n))+)
159                         (\x20[0-9]+\x20files?\x20)changed,/msx) {
160                 my $pre = substr($$x, 0, $-[0]); # (likely) short prefix
161                 substr($$x, 0, $+[0], ''); # sv_chop on $$x ($$x may be long)
162                 my @x = ($2, $1);
163                 my $lnk = $ctx->{-linkify};
164                 my $zfh = $ctx->{zfh};
165                 # uninteresting prefix
166                 print $zfh $lnk->to_html($pre);
167                 for my $l (split(/^/m, pop(@x))) { # $2 per-file stat lines
168                         $l =~ /^ (.+)( +\| .*\z)/s and
169                                 anchor0($ctx, $1, $2) and next;
170                          print $zfh $lnk->to_html($l);
171                 }
172                 my $ch = $ctx->{changed_href} // '#related';
173                 print $zfh pop(@x), # $3 /^ \d+ files? /
174                         qq(<a href="$ch">changed</a>,),
175                         # insertions/deletions, notes, commit message, etc:
176                         $lnk->to_html($$x);
177         } else {
178                 print { $ctx->{zfh} } $ctx->{-linkify}->to_html($$x);
179         }
180 }
181
182 # callers must do CRLF => LF conversion before calling this
183 sub flush_diff ($$) {
184         my ($ctx, $cur) = @_;
185
186         my @top = split($EXTRACT_DIFFS, $$cur);
187         undef $$cur; # free memory
188
189         my $lnk = $ctx->{-linkify};
190         my $dctx; # {}, keys: Q, oid_a, oid_b
191         my $zfh = $ctx->zfh;
192
193         while (defined(my $x = shift @top)) {
194                 if (scalar(@top) >= 4 &&
195                                 $top[1] =~ $IS_OID &&
196                                 $top[0] =~ $IS_OID) {
197                         $dctx = diff_header(\$x, $ctx, \@top);
198                 } elsif ($dctx) {
199                         open(my $afh, '>>:utf8', \(my $after='')) or
200                                 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                                 undef $x;
216                                 if (!defined($dctx)) {
217                                         print $afh $s;
218                                 } elsif ($s =~ s/\A@@ (\S+) (\S+) @@//) {
219                                         print $zfh qq(<span\nclass="hunk">),
220                                                 diff_hunk($dctx, $1, $2),
221                                                 $lnk->to_html($s),
222                                                 '</span>';
223                                 } elsif ($s =~ /\A\+/) { # $s may be huge
224                                         print $zfh qq(<span\nclass="add">),
225                                                         $lnk->to_html($s),
226                                                         '</span>';
227                                 } elsif ($s =~ /\A-- $/sm) { # email sig starts
228                                         $dctx = undef;
229                                         print $afh $s;
230                                 } elsif ($s =~ /\A-/) { # $s may be huge
231                                         print $zfh qq(<span\nclass="del">),
232                                                         $lnk->to_html($s),
233                                                         '</span>';
234                                 } else { # $s may be huge
235                                         print $zfh $lnk->to_html($s);
236                                 }
237                         }
238                         if (!$dctx) {
239                                 utf8::decode($after);
240                                 diff_before_or_after($ctx, \$after);
241                         }
242                 } else {
243                         diff_before_or_after($ctx, \$x);
244                 }
245         }
246 }
247
248 1;