]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewVCS.pm
viewdiff: linkify diffstats for non-format-patch emails
[public-inbox.git] / lib / PublicInbox / ViewVCS.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 # show any VCS object, similar to "git show"
5 #
6 # This can use a "solver" to reconstruct blobs based on git
7 # patches (with abbreviated OIDs in the header).  However, the
8 # abbreviated OIDs must match exactly what's in the original
9 # email (unless a normal code repo already has the blob).
10 #
11 # In other words, we can only reliably reconstruct blobs based
12 # on links generated by ViewDiff (and only if the emailed
13 # patches apply 100% cleanly to published blobs).
14
15 package PublicInbox::ViewVCS;
16 use strict;
17 use v5.10.1;
18 use File::Temp 0.19 (); # newdir
19 use PublicInbox::SolverGit;
20 use PublicInbox::WwwStream qw(html_oneshot);
21 use PublicInbox::Linkify;
22 use PublicInbox::Tmpfile;
23 use PublicInbox::ViewDiff qw(flush_diff);
24 use PublicInbox::View;
25 use Text::Wrap qw(wrap);
26 use PublicInbox::Hval qw(ascii_html to_filename);
27 my $hl = eval {
28         require PublicInbox::HlMod;
29         PublicInbox::HlMod->new;
30 };
31
32 my %QP_MAP = ( A => 'oid_a', a => 'path_a', b => 'path_b' );
33 our $MAX_SIZE = 1024 * 1024; # TODO: configurable
34 my $BIN_DETECT = 8000; # same as git
35 my $SHOW_FMT = '--pretty=format:'.join('%n', '%H', '%T', '%P', '%s',
36         '%an <%ae>%x09%ai', '%cn <%ce>%x09%ci', '%b%x00');
37
38 sub html_page ($$$) {
39         my ($ctx, $code, $strref) = @_;
40         my $wcb = delete $ctx->{-wcb};
41         $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
42         my $res = html_oneshot($ctx, $code, $strref);
43         $wcb ? $wcb->($res) : $res;
44 }
45
46 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
47         my ($r, $bref, $ctx) = @_;
48         my ($res, $logref) = delete @$ctx{qw(-res -logref)};
49         my ($git, $oid, $type, $size, $di) = @$res;
50         my @cl = ('Content-Length', $size);
51         if (!defined $r) { # error
52                 html_page($ctx, 500, $logref);
53         } elsif (index($$bref, "\0") >= 0) {
54                 [200, [qw(Content-Type application/octet-stream), @cl] ];
55         } else {
56                 my $n = length($$bref);
57                 if ($n >= $BIN_DETECT || $n == $size) {
58                         return [200, [ 'Content-Type',
59                                 'text/plain; charset=UTF-8', @cl ] ];
60                 }
61                 if ($r == 0) {
62                         warn "premature EOF on $oid $$logref";
63                         return html_page($ctx, 500, $logref);
64                 }
65                 @$ctx{qw(-res -logref)} = ($res, $logref);
66                 undef; # bref keeps growing
67         }
68 }
69
70 sub stream_large_blob ($$$$) {
71         my ($ctx, $res, $logref, $fn) = @_;
72         $ctx->{-logref} = $logref;
73         $ctx->{-res} = $res;
74         my ($git, $oid, $type, $size, $di) = @$res;
75         my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
76         my $qsp = PublicInbox::Qspawn->new($cmd);
77         my $env = $ctx->{env};
78         $env->{'qspawn.wcb'} = delete $ctx->{-wcb};
79         $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
80 }
81
82 sub show_other_result ($$) {
83         my ($bref, $ctx) = @_;
84         my ($qsp_err, $logref) = delete @$ctx{qw(-qsp_err -logref)};
85         if ($qsp_err) {
86                 $$logref .= "git show error:$qsp_err";
87                 return html_page($ctx, 500, $logref);
88         }
89         my $l = PublicInbox::Linkify->new;
90         utf8::decode($$bref);
91         $$bref = '<pre>'. $l->to_html($$bref);
92         $$bref .= '</pre><hr>' . $$logref;
93         html_page($ctx, 200, $bref);
94 }
95
96 sub show_commit_result ($$) {
97         my ($bref, $ctx) = @_;
98         my ($qsp_err, $logref, $tmp) = @$ctx{qw(-qsp_err -logref -tmp)};
99         if ($qsp_err) {
100                 $$logref .= "git show/patch-id error:$qsp_err";
101                 return html_page($ctx, 500, $logref);
102         }
103         my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
104         my $patchid = (split(/ /, $$bref))[0]; # ignore commit
105         if (defined $patchid) {
106                 $ctx->{-q_value_html} = "patchid:$patchid";
107                 $patchid = "\n  patchid $patchid";
108         } else {
109                 $patchid = '';
110         }
111         my $l = $ctx->{-linkify} = PublicInbox::Linkify->new;
112         open my $fh, '<:utf8', "$tmp/h" or die "open $tmp/h: $!";
113         chop(my $buf = do { local $/ = "\0"; <$fh> });
114         my ($H, $T, $P, $s, $au, $co, $bdy) = split(/\n/, $buf, 7);
115         chomp $bdy;
116         # try to keep author and committer dates lined up
117         my $x = length($au) - length($co);
118         if ($x > 0) {
119                 $x = ' ' x $x;
120                 $co =~ s/\t/$x\t/;
121         } elsif ($x < 0) {
122                 $x = ' ' x (-$x);
123                 $au =~ s/\t/$x\t/;
124         }
125         $_ = ascii_html($_) for ($au, $co);
126         $_ = $l->to_html($_) for ($s, $bdy);
127         $ctx->{-title_html} = $s;
128         my @p = split(/ /, $P);
129         if (@p == 1) {
130                 $P = qq(\n   parent <a href="$upfx$P/s/">$P</a>);
131         } elsif (@p > 1) {
132                 $P = qq(\n  parents <a href="$upfx$p[0]/s/">$p[0]</a>\n);
133                 shift @p;
134                 $P .= qq(          <a href="$upfx$_/s/">$_</a>\n) for @p;
135                 chop $P;
136         } else { # root commit
137                 $P = ' (root commit)';
138         }
139         PublicInbox::WwwStream::html_init($ctx);
140         $ctx->zmore(<<EOM);
141 <pre>   commit $H$P
142      tree <a href="$upfx$T/s/">$T</a>
143    author $au
144 committer $co$patchid
145
146 <b>$s</b>\n
147 EOM
148         $ctx->zmore($bdy);
149         open $fh, '<:utf8', "$tmp/p" or die "open $tmp/p: $!";
150         if (-s $fh > $MAX_SIZE) {
151                 $ctx->zmore("---\n patch is too large to show\n");
152         } else { # prepare flush_diff:
153                 $buf = '';
154                 $ctx->{obuf} = \$buf;
155                 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
156                 $bdy = '';
157                 read($fh, $bdy, -s _);
158                 $bdy =~ s/\r?\n/\n/gs;
159                 $ctx->{-anchors} = {} if $bdy =~ /^diff --git /sm;
160                 flush_diff($ctx, \$bdy);
161                 $ctx->zmore($buf);
162                 undef $buf;
163                 # TODO: should there be another textarea which attempts to
164                 # search for the exact email which was applied to make this
165                 # commit?
166                 if (my $qry = delete $ctx->{-qry}) {
167                         my $q = '';
168                         for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
169                                 # keep blobs as short as reasonable, emails
170                                 # are going to be older than what's in git
171                                 substr($_, 7, 64, '');
172                                 $q .= "dfblob:$_ ";
173                         }
174                         chop $q; # no trailing SP
175                         local $Text::Wrap::columns = PublicInbox::View::COLS;
176                         local $Text::Wrap::huge = 'overflow';
177                         $q = wrap('', '', $q);
178                         my $rows = ($q =~ tr/\n/\n/) + 1;
179                         $q = ascii_html($q);
180                         $ctx->zmore(<<EOM);
181 <hr><form action=$upfx
182 id=related><pre>find related emails, including ancestors/descendants/conflicts
183 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
184 <input type=submit value=search
185 />\t(<a href=${upfx}_/text/help/>help</a>)</pre></form>
186 EOM
187                 }
188         }
189         $x = $ctx->zflush($ctx->_html_end);
190         my $res_hdr = delete $ctx->{-res_hdr};
191         push @$res_hdr, 'Content-Length', length($x);
192         delete($ctx->{env}->{'qspawn.wcb'})->([200, $res_hdr, [$x]]);
193 }
194
195 sub show_commit ($$$$) {
196         my ($ctx, $res, $logref, $fn) = @_;
197         my ($git, $oid) = @$res;
198         # patch-id needs two passes, and we use the initial show to ensure
199         # a patch embedded inside the commit message body doesn't get fed
200         # to patch-id:
201         my $cmd = [ '/bin/sh', '-c',
202                 "git show --encoding=UTF-8 '$SHOW_FMT'".
203                 " -z --no-notes --no-patch $oid >h && ".
204                 'git show --encoding=UTF-8 --pretty=format:%n -M'.
205                 " --stat -p $oid >p && ".
206                 "git patch-id --stable <p" ];
207         my $xenv = { GIT_DIR => $git->{git_dir} };
208         my $tmp = File::Temp->newdir("show-$oid-XXXX", TMPDIR => 1);
209         my $qsp = PublicInbox::Qspawn->new($cmd, $xenv, { -C => "$tmp" });
210         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
211         $ctx->{-logref} = $logref;
212         $ctx->{-tmp} = $tmp;
213         $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
214         $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_result, $ctx);
215 }
216
217 sub show_other ($$$$) {
218         my ($ctx, $res, $logref, $fn) = @_;
219         my ($git, $oid, $type, $size) = @$res;
220         if ($size > $MAX_SIZE) {
221                 $$logref = "$oid is too big to show\n" . $$logref;
222                 return html_page($ctx, 200, $logref);
223         }
224         my $cmd = ['git', "--git-dir=$git->{git_dir}",
225                 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
226         my $qsp = PublicInbox::Qspawn->new($cmd);
227         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
228         $ctx->{-logref} = $logref;
229         $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
230 }
231
232 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
233 sub solve_result {
234         my ($res, $ctx) = @_;
235         my ($log, $hints, $fn) = delete @$ctx{qw(log hints fn)};
236
237         unless (seek($log, 0, 0)) {
238                 warn "seek(log): $!";
239                 return html_page($ctx, 500, \'seek error');
240         }
241         $log = do { local $/; <$log> };
242
243         my $l = PublicInbox::Linkify->new;
244         $log = '<pre>debug log:</pre><hr /><pre>' .
245                 $l->to_html($log) . '</pre>';
246
247         $res or return html_page($ctx, 404, \$log);
248         ref($res) eq 'ARRAY' or return html_page($ctx, 500, \$log);
249
250         my ($git, $oid, $type, $size, $di) = @$res;
251         return show_commit($ctx, $res, \$log, $fn) if $type eq 'commit';
252         return show_other($ctx, $res, \$log, $fn) if $type ne 'blob';
253         my $path = to_filename($di->{path_b} // $hints->{path_b} // 'blob');
254         my $raw_link = "(<a\nhref=$path>raw</a>)";
255         if ($size > $MAX_SIZE) {
256                 return stream_large_blob($ctx, $res, \$log, $fn) if defined $fn;
257                 $log = "<pre><b>Too big to show, download available</b>\n" .
258                         "$oid $type $size bytes $raw_link</pre>" . $log;
259                 return html_page($ctx, 200, \$log);
260         }
261
262         my $blob = $git->cat_file($oid);
263         if (!$blob) { # WTF?
264                 my $e = "Failed to retrieve generated blob ($oid)";
265                 warn "$e ($git->{git_dir})";
266                 $log = "<pre><b>$e</b></pre>" . $log;
267                 return html_page($ctx, 500, \$log);
268         }
269
270         my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
271         if (defined $fn) {
272                 my $h = [ 'Content-Length', $size, 'Content-Type' ];
273                 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
274                 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
275         }
276
277         if ($bin) {
278                 $log = "<pre>$oid $type $size bytes (binary)" .
279                         " $raw_link</pre>" . $log;
280                 return html_page($ctx, 200, \$log);
281         }
282
283         # TODO: detect + convert to ensure validity
284         utf8::decode($$blob);
285         my $nl = ($$blob =~ s/\r?\n/\n/sg);
286         my $pad = length($nl);
287
288         $l->linkify_1($$blob);
289         my $ok = $hl->do_hl($blob, $path) if $hl;
290         if ($ok) {
291                 $blob = $ok;
292         } else {
293                 $$blob = ascii_html($$blob);
294         }
295
296         # using some of the same CSS class names and ids as cgit
297         $log = "<pre>$oid $type $size bytes $raw_link</pre>" .
298                 "<hr /><table\nclass=blob>".
299                 "<tr><td\nclass=linenumbers><pre>" . join('', map {
300                         sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_)
301                 } (1..$nl)) . '</pre></td>' .
302                 '<td><pre> </pre></td>'. # pad for non-CSS users
303                 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>" .
304                 $l->linkify_2($$blob) .
305                 '</code></pre></td></tr></table>' . $log;
306
307         html_page($ctx, 200, \$log);
308 }
309
310 # GET /$INBOX/$GIT_OBJECT_ID/s/
311 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
312 sub show ($$;$) {
313         my ($ctx, $oid_b, $fn) = @_;
314         my $qp = $ctx->{qp};
315         my $hints = $ctx->{hints} = {};
316         while (my ($from, $to) = each %QP_MAP) {
317                 defined(my $v = $qp->{$from}) or next;
318                 $hints->{$to} = $v if $v ne '';
319         }
320
321         $ctx->{'log'} = tmpfile("solve.$oid_b") // die "tmpfile: $!";
322         $ctx->{fn} = $fn;
323         my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
324                                                 \&solve_result, $ctx);
325         # PSGI server will call this immediately and give us a callback (-wcb)
326         sub {
327                 $ctx->{-wcb} = $_[0]; # HTTP write callback
328                 $solver->solve($ctx->{env}, $ctx->{log}, $oid_b, $hints);
329         };
330 }
331
332 1;