]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewDiff.pm
viewdiff: linkify diffstats for non-format-patch emails
[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);
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                 push @{$ctx->{-qry}->{dfpost}}, $2;
146         } elsif ($$x =~ s/$BLOB_TO_NULL/'index '.oid($dctx, $spfx, $1).$2/e) {
147                 push @{$ctx->{-qry}->{dfpre}}, $1;
148         } elsif ($$x =~ $BLOB_TO_BLOB) {
149                 # modification-only, not add/delete:
150                 # linkify hunk headers later using oid_a and oid_b
151                 @$dctx{qw(oid_a oid_b)} = ($1, $2);
152                 push @{$ctx->{-qry}->{dfpre}}, $1;
153                 push @{$ctx->{-qry}->{dfpost}}, $2;
154         } else {
155                 warn "BUG? <$$x> had no ^index line";
156         }
157         $$x =~ s!^diff --git!anchor1($ctx, $pb) // 'diff --git'!ems;
158         my $dst = $ctx->{obuf};
159         $$dst .= qq(<span\nclass="head">);
160         $$dst .= $$x;
161         $$dst .= '</span>';
162         $dctx;
163 }
164
165 sub diff_before_or_after ($$) {
166         my ($ctx, $x) = @_;
167         my $linkify = $ctx->{-linkify};
168         my $dst = $ctx->{obuf};
169         if (exists $ctx->{-anchors} && $$x =~ /\A(.*?) # likely "---\n"
170                         # diffstat lines:
171                         ((?:^\x20(?:[^\n]+?)(?:\x20+\|\x20[^\n]*\n))+)
172                         (\x20[0-9]+\x20files?\x20)changed,([^\n]+\n)
173                         (.*?)\z/msx) { # notes, commit message, etc
174                 undef $$x;
175                 my @x = ($5, $4, $3, $2, $1);
176                 $$dst .= $linkify->to_html(pop @x); # uninteresting prefix
177                 for my $l (split(/^/m, pop(@x))) { # per-file diffstat lines
178                         $l =~ /^ (.+)( +\| .*\z)/s and
179                                 anchor0($dst, $ctx, $1, $2) and next;
180                         $$dst .= $linkify->to_html($l);
181                 }
182                 $$dst .= $x[2]; # $3 /^ \d+ files? /
183                 my $end = $ctx->{end_id} // 'related';
184                 $$dst .= "<a href=#$end>changed</a>,";
185                 $$dst .= ascii_html($x[1]); # $4: insertions/deletions
186                 $$dst .= $linkify->to_html($x[0]); # notes, commit message, etc
187         } else {
188                 $$dst .= $linkify->to_html($$x);
189         }
190 }
191
192 # callers must do CRLF => LF conversion before calling this
193 sub flush_diff ($$) {
194         my ($ctx, $cur) = @_;
195
196         my @top = split($EXTRACT_DIFFS, $$cur);
197         undef $$cur; # free memory
198
199         my $linkify = $ctx->{-linkify};
200         my $dst = $ctx->{obuf};
201         my $dctx; # {}, keys: Q, oid_a, oid_b
202
203         while (defined(my $x = shift @top)) {
204                 if (scalar(@top) >= 4 &&
205                                 $top[1] =~ $IS_OID &&
206                                 $top[0] =~ $IS_OID) {
207                         $dctx = diff_header(\$x, $ctx, \@top);
208                 } elsif ($dctx) {
209                         my $after = '';
210
211                         # Quiet "Complex regular subexpression recursion limit"
212                         # warning.  Perl will truncate matches upon hitting
213                         # that limit, giving us more (and shorter) scalars than
214                         # would be ideal, but otherwise it's harmless.
215                         #
216                         # We could replace the `+' metacharacter with `{1,100}'
217                         # to limit the matches ourselves to 100, but we can
218                         # let Perl do it for us, quietly.
219                         no warnings 'regexp';
220
221                         for my $s (split(/((?:(?:^\+[^\n]*\n)+)|
222                                         (?:(?:^-[^\n]*\n)+)|
223                                         (?:^@@ [^\n]+\n))/xsm, $x)) {
224                                 if (!defined($dctx)) {
225                                         $after .= $s;
226                                 } elsif ($s =~ s/\A@@ (\S+) (\S+) @@//) {
227                                         $$dst .= qq(<span\nclass="hunk">);
228                                         diff_hunk($dst, $dctx, $1, $2);
229                                         $$dst .= $linkify->to_html($s);
230                                         $$dst .= '</span>';
231                                 } elsif ($s =~ /\A\+/) {
232                                         $$dst .= qq(<span\nclass="add">);
233                                         $$dst .= $linkify->to_html($s);
234                                         $$dst .= '</span>';
235                                 } elsif ($s =~ /\A-- $/sm) { # email sig starts
236                                         $dctx = undef;
237                                         $after .= $s;
238                                 } elsif ($s =~ /\A-/) {
239                                         $$dst .= qq(<span\nclass="del">);
240                                         $$dst .= $linkify->to_html($s);
241                                         $$dst .= '</span>';
242                                 } else {
243                                         $$dst .= $linkify->to_html($s);
244                                 }
245                         }
246                         diff_before_or_after($ctx, \$after) unless $dctx;
247                 } else {
248                         diff_before_or_after($ctx, \$x);
249                 }
250         }
251 }
252
253 1;