]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewVCS.pm
viewvcs: add tree view
[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::GitAsyncCat;
21 use PublicInbox::WwwStream qw(html_oneshot);
22 use PublicInbox::Linkify;
23 use PublicInbox::Tmpfile;
24 use PublicInbox::ViewDiff qw(flush_diff uri_escape_path);
25 use PublicInbox::View;
26 use PublicInbox::Eml;
27 use Text::Wrap qw(wrap);
28 use PublicInbox::Hval qw(ascii_html to_filename);
29 my $hl = eval {
30         require PublicInbox::HlMod;
31         PublicInbox::HlMod->new;
32 };
33
34 my %QP_MAP = ( A => 'oid_a', a => 'path_a', b => 'path_b' );
35 our $MAX_SIZE = 1024 * 1024; # TODO: configurable
36 my $BIN_DETECT = 8000; # same as git
37 my $SHOW_FMT = '--pretty=format:'.join('%n', '%P', '%p', '%H', '%T', '%s', '%f',
38         '%an <%ae>  %ai', '%cn <%ce>  %ci', '%b%x00');
39
40 my %GIT_MODE = (
41         '100644' => ' ', # blob
42         '100755' => 'x', # executable blob
43         '040000' => 'd', # tree
44         '120000' => 'l', # symlink
45         '160000' => 'g', # commit (gitlink)
46 );
47
48 sub html_page ($$;@) {
49         my ($ctx, $code) = @_[0, 1];
50         my $wcb = delete $ctx->{-wcb};
51         $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
52         my $res = html_oneshot($ctx, $code, @_[2..$#_]);
53         $wcb ? $wcb->($res) : $res;
54 }
55
56 sub dbg_log ($) {
57         my ($ctx) = @_;
58         my $log = delete $ctx->{lh} // die 'BUG: already captured debug log';
59         if (!seek($log, 0, 0)) {
60                 warn "seek(log): $!";
61                 return '<pre>debug log seek error</pre>';
62         }
63         $log = do { local $/; <$log> } // do {
64                 warn "readline(log): $!";
65                 return '<pre>debug log read error</pre>';
66         };
67         $ctx->{-linkify} //= PublicInbox::Linkify->new;
68         "<hr><pre>debug log:\n\n".
69                 $ctx->{-linkify}->to_html($log).'</pre>';
70 }
71
72 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
73         my ($r, $bref, $ctx) = @_;
74         my ($git, $oid, $type, $size, $di) = @{$ctx->{-res}};
75         my @cl = ('Content-Length', $size);
76         if (!defined $r) { # sysread error
77                 html_page($ctx, 500, dbg_log($ctx));
78         } elsif (index($$bref, "\0") >= 0) {
79                 [200, [qw(Content-Type application/octet-stream), @cl] ];
80         } else {
81                 my $n = length($$bref);
82                 if ($n >= $BIN_DETECT || $n == $size) {
83                         return [200, [ 'Content-Type',
84                                 'text/plain; charset=UTF-8', @cl ] ];
85                 }
86                 if ($r == 0) {
87                         my $log = dbg_log($ctx);
88                         warn "premature EOF on $oid $log";
89                         return html_page($ctx, 500, $log);
90                 }
91                 undef; # bref keeps growing
92         }
93 }
94
95 sub stream_large_blob ($$) {
96         my ($ctx, $res) = @_;
97         $ctx->{-res} = $res;
98         my ($git, $oid, $type, $size, $di) = @$res;
99         my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
100         my $qsp = PublicInbox::Qspawn->new($cmd);
101         my $env = $ctx->{env};
102         $env->{'qspawn.wcb'} = delete $ctx->{-wcb};
103         $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
104 }
105
106 sub show_other_result ($$) { # tag
107         my ($bref, $ctx) = @_;
108         if (my $qsp_err = delete $ctx->{-qsp_err}) {
109                 return html_page($ctx, 500, dbg_log($ctx) .
110                                 "git show error:$qsp_err");
111         }
112         my $l = PublicInbox::Linkify->new;
113         utf8::decode($$bref);
114         html_page($ctx, 200, '<pre>', $l->to_html($$bref), '</pre><hr>',
115                 dbg_log($ctx));
116 }
117
118 sub cmt_title { # git->cat_async callback
119         my ($bref, $oid, $type, $size, $ctx) = @_;
120         utf8::decode($$bref);
121         my $title = $$bref =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/ ? $1 : '';
122         push(@{$ctx->{-cmt_pt}} , ascii_html($title)) == @{$ctx->{-cmt_P}} and
123                 cmt_finalize($ctx);
124 }
125
126 sub show_commit_start { # ->psgi_qx callback
127         my ($bref, $ctx) = @_;
128         if (my $qsp_err = delete $ctx->{-qsp_err}) {
129                 return html_page($ctx, 500, dbg_log($ctx) .
130                                 "git show/patch-id error:$qsp_err");
131         }
132         my $patchid = (split(/ /, $$bref))[0]; # ignore commit
133         $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
134         open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
135                 die "open $ctx->{-tmp}/h: $!";
136         chop(my $buf = do { local $/ = "\0"; <$fh> });
137         chomp $buf;
138         my ($P, $p);
139         ($P, $p, @$ctx{qw(cmt_H cmt_T cmt_s cmt_f cmt_au cmt_co cmt_b)})
140                 = split(/\n/, $buf, 9);
141         return cmt_finalize($ctx) if !$P;
142         @{$ctx->{-cmt_P}} = split(/ /, $P);
143         @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
144         if ($ctx->{env}->{'pi-httpd.async'}) {
145                 for (@{$ctx->{-cmt_P}}) {
146                         ibx_async_cat($ctx, $_, \&cmt_title, $ctx);
147                 }
148         } else { # synchronous
149                 for (@{$ctx->{-cmt_P}}) {
150                         $ctx->{git}->cat_async($_, \&cmt_title, $ctx);
151                 }
152                 $ctx->{git}->cat_async_wait;
153         }
154 }
155
156 sub cmt_finalize {
157         my ($ctx) = @_;
158         $ctx->{-linkify} //= PublicInbox::Linkify->new;
159         my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
160         # try to keep author and committer dates lined up
161         my ($au, $co) = delete @$ctx{qw(cmt_au cmt_co)};
162         my $x = length($au) - length($co);
163         if ($x > 0) {
164                 $x = ' ' x $x;
165                 $co =~ s/>/>$x/;
166         } elsif ($x < 0) {
167                 $x = ' ' x (-$x);
168                 $au =~ s/>/>$x/;
169         }
170         $_ = ascii_html($_) for ($au, $co);
171         $au =~ s!(&gt; +)([0-9]{4,}-\S+ \S+)!
172                 my ($gt, $t) = ($1, $2);
173                 $t =~ tr/ :-//d;
174                 qq($gt<a
175 href="$upfx?t=$t"
176 title="list contemporary emails">$2</a>)
177                 !e;
178         my $s = $ctx->{-linkify}->to_html(delete $ctx->{cmt_s});
179         $ctx->{-title_html} = $s;
180         my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
181         $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
182         if (@$P == 1) {
183                 $x = qq{ (<a
184 href="$ctx->{cmt_f}.patch">patch</a>)\n   parent $P->[0]};
185         } elsif (@$P > 1) {
186                 $x = qq(\n  parents $P->[0]\n);
187                 shift @$P;
188                 $x .= qq(          $_\n) for @$P;
189                 chop $x;
190         } else {
191                 $x = ' (root commit)';
192         }
193         PublicInbox::WwwStream::html_init($ctx);
194         $ctx->zmore(<<EOM);
195 <pre>   commit $ctx->{cmt_H}$x
196      tree <a href="$upfx$ctx->{cmt_T}/s/">$ctx->{cmt_T}</a>
197    author $au
198 committer $co
199
200 <b>$s</b>
201 EOM
202         $x = delete $ctx->{cmt_b};
203         $ctx->zmore("\n", $ctx->{-linkify}->to_html($x)) if length($x);
204         undef $x;
205         open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
206                 die "open $ctx->{-tmp}/p: $!";
207         if (-s $fh > $MAX_SIZE) {
208                 $ctx->zmore("---\n patch is too large to show\n");
209         } else { # prepare flush_diff:
210                 $ctx->{obuf} = \$x;
211                 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
212                 read($fh, my $bdy, -s _);
213                 $bdy =~ s/\r?\n/\n/gs;
214                 $ctx->{-anchors} = {} if $bdy =~ /^diff --git /sm;
215                 flush_diff($ctx, \$bdy); # undefs $bdy
216                 $ctx->zmore($x);
217                 undef $x;
218                 # TODO: should there be another textarea which attempts to
219                 # search for the exact email which was applied to make this
220                 # commit?
221                 if (my $qry = delete $ctx->{-qry}) {
222                         my $q = '';
223                         for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
224                                 # keep blobs as short as reasonable, emails
225                                 # are going to be older than what's in git
226                                 substr($_, 7, 64, '');
227                                 $q .= "dfblob:$_ ";
228                         }
229                         chop $q; # no trailing SP
230                         local $Text::Wrap::columns = PublicInbox::View::COLS;
231                         local $Text::Wrap::huge = 'overflow';
232                         $q = wrap('', '', $q);
233                         my $rows = ($q =~ tr/\n/\n/) + 1;
234                         $q = ascii_html($q);
235                         $ctx->zmore(<<EOM);
236 <hr><form action=$upfx
237 id=related><pre>find related emails, including ancestors/descendants/conflicts
238 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
239 <input type=submit value=search
240 />\t(<a href=${upfx}_/text/help/>help</a>)</pre></form>
241 EOM
242                 }
243         }
244         $x = $ctx->zflush($ctx->_html_end);
245         my $res_hdr = delete $ctx->{-res_hdr};
246         push @$res_hdr, 'Content-Length', length($x);
247         delete($ctx->{env}->{'qspawn.wcb'})->([200, $res_hdr, [$x]]);
248 }
249
250 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
251         my ($r, $bref, $ctx) = @_;
252         if (!defined $r) { # sysread error
253                 html_page($ctx, 500, dbg_log($ctx));
254         } elsif (index($$bref, "\n\n") >= 0) {
255                 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
256                 my $fn = to_filename($eml->header('Subject') // '');
257                 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
258                 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
259                                 'Content-Disposition',
260                                 qq(inline; filename=$fn.patch) ] ];
261         } elsif ($r == 0) {
262                 my $log = dbg_log($ctx);
263                 warn "premature EOF on $ctx->{patch_oid} $log";
264                 return html_page($ctx, 500, $log);
265         } else {
266                 undef; # bref keeps growing until "\n\n"
267         }
268 }
269
270 sub show_patch ($$) {
271         my ($ctx, $res) = @_;
272         my ($git, $oid) = @$res;
273         my @cmd = ('git', "--git-dir=$git->{git_dir}",
274                 qw(format-patch -1 --stdout -C),
275                 "--signature=git format-patch -1 --stdout -C $oid", $oid);
276         my $qsp = PublicInbox::Qspawn->new(\@cmd);
277         $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
278         $ctx->{patch_oid} = $oid;
279         $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
280 }
281
282 sub show_commit ($$) {
283         my ($ctx, $res) = @_;
284         return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
285         my ($git, $oid) = @$res;
286         # patch-id needs two passes, and we use the initial show to ensure
287         # a patch embedded inside the commit message body doesn't get fed
288         # to patch-id:
289         my $cmd = [ '/bin/sh', '-c',
290                 "git show --encoding=UTF-8 '$SHOW_FMT'".
291                 " -z --no-notes --no-patch $oid >h && ".
292                 'git show --encoding=UTF-8 --pretty=format:%n -M'.
293                 " --stat -p $oid >p && ".
294                 "git patch-id --stable <p" ];
295         my $e = { GIT_DIR => $git->{git_dir} };
296         my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
297         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
298         $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
299         $ctx->{git} = $git;
300         $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
301 }
302
303 sub show_other ($$) {
304         my ($ctx, $res) = @_;
305         my ($git, $oid, $type, $size) = @$res;
306         $size > $MAX_SIZE and return html_page($ctx, 200,
307                 ascii_html($type)." $oid is too big to show\n". dbg_log($ctx));
308         my $cmd = ['git', "--git-dir=$git->{git_dir}",
309                 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
310         my $qsp = PublicInbox::Qspawn->new($cmd);
311         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
312         $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
313 }
314
315 sub show_tree_result ($$) {
316         my ($bref, $ctx) = @_;
317         if (my $qsp_err = delete $ctx->{-qsp_err}) {
318                 return html_page($ctx, 500, dbg_log($ctx) .
319                                 "git ls-tree -z error:$qsp_err");
320         }
321         my @ent = split(/\0/, $$bref);
322         my $qp = delete $ctx->{qp};
323         my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
324         my $pfx = $qp->{b};
325         $$bref = "<pre><a href=#tree>tree</a> $ctx->{tree_oid}";
326         if (defined $pfx) {
327                 my $x = ascii_html($pfx);
328                 $pfx .= '/';
329                 $$bref .= qq(  <a href=#path>path</a>: $x</a>\n);
330         } else {
331                 $pfx = '';
332                 $$bref .= qq[  (<a href=#path>path</a> unknown)\n];
333         }
334         my ($x, $m, $t, $oid, $sz, $f, $n);
335         $$bref .= "\n   size    name";
336         for (@ent) {
337                 ($x, $f) = split(/\t/, $_, 2);
338                 undef $_;
339                 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
340                 $m = $GIT_MODE{$m} // '?';
341                 utf8::decode($f);
342                 $n = ascii_html($f);
343                 if ($m eq 'g') { # gitlink submodule commit
344                         $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
345                         next;
346                 }
347                 my $q = 'b='.ascii_html(uri_escape_path($pfx.$f));
348                 if ($m eq 'd') { $n .= '/' }
349                 elsif ($m eq 'x') { $n = "<b>$n</b>" }
350                 elsif ($m eq 'l') { $n = "<i>$n</i>" }
351                 $$bref .= qq(\n$m\t$sz\t<a\nhref="../../$oid/s/?$q">$n</a>);
352         }
353         $$bref .= dbg_log($ctx);
354         $$bref .= <<EOM;
355 <pre>glossary
356 --------
357 <dfn
358 id=tree>Tree</dfn> objects belong to commits or other tree objects.  Trees may
359 reference blobs, sub-trees, or commits of submodules.
360
361 <dfn
362 id=path>Path</dfn> names are stored in tree objects, but trees do not know
363 their own path name.  A tree's path name comes from their parent tree,
364 or it is the root tree referenced by a commit object.  Thus, this web UI
365 relies on the `b=' URI parameter as a hint to display the path name.
366
367 <dfn title="submodule commit"
368 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
369 EOM
370         chop $$bref;
371         html_page($ctx, 200, $$bref);
372 }
373
374 sub show_tree ($$) {
375         my ($ctx, $res) = @_;
376         my ($git, $oid, undef, $size) = @$res;
377         $size > $MAX_SIZE and return html_page($ctx, 200,
378                         "tree $oid is too big to show\n". dbg_log($ctx));
379         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
380                 qw(ls-tree -z -l --no-abbrev), $oid ];
381         my $qsp = PublicInbox::Qspawn->new($cmd);
382         $ctx->{tree_oid} = $oid;
383         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
384         $qsp->psgi_qx($ctx->{env}, undef, \&show_tree_result, $ctx);
385 }
386
387 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
388 sub solve_result {
389         my ($res, $ctx) = @_;
390         my $hints = delete $ctx->{hints};
391         $res or return html_page($ctx, 404, dbg_log($ctx));
392         ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
393
394         my ($git, $oid, $type, $size, $di) = @$res;
395         return show_commit($ctx, $res) if $type eq 'commit';
396         return show_tree($ctx, $res) if $type eq 'tree';
397         return show_other($ctx, $res) if $type ne 'blob';
398         my $path = to_filename($di->{path_b} // $hints->{path_b} // 'blob');
399         my $raw_link = "(<a\nhref=$path>raw</a>)";
400         if ($size > $MAX_SIZE) {
401                 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
402                 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
403 <pre><b>Too big to show, download available</b>
404 "$oid $type $size bytes $raw_link</pre>
405 EOM
406         }
407
408         my $blob = $git->cat_file($oid);
409         if (!$blob) { # WTF?
410                 my $e = "Failed to retrieve generated blob ($oid)";
411                 warn "$e ($git->{git_dir})";
412                 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
413         }
414
415         my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
416         if (defined $ctx->{fn}) {
417                 my $h = [ 'Content-Length', $size, 'Content-Type' ];
418                 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
419                 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
420         }
421
422         $bin and return html_page($ctx, 200,
423                                 "<pre>$oid $type $size bytes (binary)" .
424                                 " $raw_link</pre>".dbg_log($ctx));
425
426         # TODO: detect + convert to ensure validity
427         utf8::decode($$blob);
428         my $nl = ($$blob =~ s/\r?\n/\n/sg);
429         my $pad = length($nl);
430
431         ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
432         my $ok = $hl->do_hl($blob, $path) if $hl;
433         if ($ok) {
434                 $blob = $ok;
435         } else {
436                 $$blob = ascii_html($$blob);
437         }
438
439         my $x = "<pre>$oid $type $size bytes $raw_link</pre>" .
440                 "<hr /><table\nclass=blob>".
441                 "<tr><td\nclass=linenumbers><pre>";
442         $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
443         $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
444                 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
445
446         # using some of the same CSS class names and ids as cgit
447         html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
448                 '</code></pre></td></tr></table>'.dbg_log($ctx));
449 }
450
451 # GET /$INBOX/$GIT_OBJECT_ID/s/
452 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
453 sub show ($$;$) {
454         my ($ctx, $oid_b, $fn) = @_;
455         my $qp = $ctx->{qp};
456         my $hints = $ctx->{hints} = {};
457         while (my ($from, $to) = each %QP_MAP) {
458                 defined(my $v = $qp->{$from}) or next;
459                 $hints->{$to} = $v if $v ne '';
460         }
461         $ctx->{fn} = $fn;
462         $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
463         open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
464         my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
465                                                 \&solve_result, $ctx);
466         $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
467         # PSGI server will call this immediately and give us a callback (-wcb)
468         sub {
469                 $ctx->{-wcb} = $_[0]; # HTTP write callback
470                 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);
471         };
472 }
473
474 1;