1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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.
9 package PublicInbox::ViewDiff;
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);
17 my $OID_NULL = '0{7,}';
18 my $OID_BLOB = '[a-f0-9]{7,}';
21 my $FN = qr!(?:"?[^/\n]+/[^\n]+|/dev/null)!;
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)
34 # old mode || new mode || copy|rename|deleted|...
36 )? # end of optional stuff, everything below is required
37 ^index\x20($OID_BLOB)\.\.($OID_BLOB)$ANY*$LF
39 ^\+{3}\x20($FN)$LF)/msx;
40 our $IS_OID = qr/\A$OID_BLOB\z/s;
43 # '/' + $URI::Escape::Unsafe{RFC3986}
44 uri_escape_utf8($_[0], "^A-Za-z0-9\-\._~/");
47 # link to line numbers in blobs
49 my ($dctx, $ca, $cb) = @_;
50 my ($oid_a, $oid_b, $spfx) = @$dctx{qw(oid_a oid_b spfx)};
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>);
56 $n = ($cb =~ /^\+([0-9]+)/) ? "#n$1" : '';
57 $x .= qq( <a\nhref="$spfx$oid_b/s/$dctx->{Q}$n">$cb</a> @@);
64 my ($dctx, $spfx, $oid) = @_;
65 defined($spfx) ? qq(<a\nhref="$spfx$oid/s/$dctx->{Q}">$oid</a>) : $oid;
68 # returns true if diffstat anchor written, false otherwise
70 my ($ctx, $fn, $rest) = @_;
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);
83 # long filenames will require us to check in anchor1()
84 push(@{$ctx->{-long_path}}, $fn) if $fn =~ s!\A\.\.\./?!!;
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);
94 # returns "diff --git" anchor destination, undef otherwise
97 my $attr = to_attr($ctx->{-apfx}.$pb) // return;
99 my $ok = delete $ctx->{-anchors}->{$attr};
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)
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;
110 $ok ? "<a\nhref=#i$attr\nid=$attr>diff</a> --git" : undef
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 };
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);
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('&', @q);
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);
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;
148 warn "BUG? <$$x> had no ^index line";
150 $$x =~ s!^diff --git!anchor1($ctx, $pb) // 'diff --git'!ems;
151 print { $ctx->{zfh} } qq(<span\nclass="head">), $$x, '</span>';
155 sub diff_before_or_after ($$) {
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)
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);
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:
178 print { $ctx->{zfh} } $ctx->{-linkify}->to_html($$x);
182 # callers must do CRLF => LF conversion before calling this
183 sub flush_diff ($$) {
184 my ($ctx, $cur) = @_;
186 my @top = split($EXTRACT_DIFFS, $$cur);
187 undef $$cur; # free memory
189 my $lnk = $ctx->{-linkify};
190 my $dctx; # {}, keys: Q, oid_a, oid_b
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);
199 open(my $afh, '>>:utf8', \(my $after='')) or
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.
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';
212 for my $s (split(/((?:(?:^\+[^\n]*\n)+)|
214 (?:^@@ [^\n]+\n))/xsm, $x)) {
216 if (!defined($dctx)) {
218 } elsif ($s =~ s/\A@@ (\S+) (\S+) @@//) {
219 print $zfh qq(<span\nclass="hunk">),
220 diff_hunk($dctx, $1, $2),
223 } elsif ($s =~ /\A\+/) { # $s may be huge
224 print $zfh qq(<span\nclass="add">),
227 } elsif ($s =~ /\A-- $/sm) { # email sig starts
230 } elsif ($s =~ /\A-/) { # $s may be huge
231 print $zfh qq(<span\nclass="del">),
234 } else { # $s may be huge
235 print $zfh $lnk->to_html($s);
239 utf8::decode($after);
240 diff_before_or_after($ctx, \$after);
243 diff_before_or_after($ctx, \$x);