1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # show any VCS object, similar to "git show"
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).
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).
15 package PublicInbox::ViewVCS;
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;
27 use Text::Wrap qw(wrap);
28 use PublicInbox::Hval qw(ascii_html to_filename prurl);
29 use POSIX qw(strftime);
31 require PublicInbox::HlMod;
32 PublicInbox::HlMod->new;
35 my %QP_MAP = ( A => 'oid_a', a => 'path_a', b => 'path_b' );
36 our $MAX_SIZE = 1024 * 1024; # TODO: configurable
37 my $BIN_DETECT = 8000; # same as git
38 my $SHOW_FMT = '--pretty=format:'.join('%n', '%P', '%p', '%H', '%T', '%s', '%f',
39 '%an <%ae> %ai', '%cn <%ce> %ci', '%b%x00');
42 '100644' => ' ', # blob
43 '100755' => 'x', # executable blob
44 '040000' => 'd', # tree
45 '120000' => 'l', # symlink
46 '160000' => 'g', # commit (gitlink)
49 sub html_page ($$;@) {
50 my ($ctx, $code) = @_[0, 1];
51 my $wcb = delete $ctx->{-wcb};
52 $ctx->{-upfx} //= '../../'; # from "/$INBOX/$OID/s/"
53 my $res = html_oneshot($ctx, $code, @_[2..$#_]);
54 $wcb ? $wcb->($res) : $res;
59 my $log = delete $ctx->{lh} // die 'BUG: already captured debug log';
60 if (!seek($log, 0, 0)) {
62 return '<pre>debug log seek error</pre>';
64 $log = do { local $/; <$log> } // do {
65 warn "readline(log): $!";
66 return '<pre>debug log read error</pre>';
68 return '' if $log eq '';
69 $ctx->{-linkify} //= PublicInbox::Linkify->new;
70 "<hr><pre>debug log:\n\n".
71 $ctx->{-linkify}->to_html($log).'</pre>';
74 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
75 my ($r, $bref, $ctx) = @_;
76 my ($git, $oid, $type, $size, $di) = @{$ctx->{-res}};
77 my @cl = ('Content-Length', $size);
78 if (!defined $r) { # sysread error
79 html_page($ctx, 500, dbg_log($ctx));
80 } elsif (index($$bref, "\0") >= 0) {
81 [200, [qw(Content-Type application/octet-stream), @cl] ];
83 my $n = length($$bref);
84 if ($n >= $BIN_DETECT || $n == $size) {
85 return [200, [ 'Content-Type',
86 'text/plain; charset=UTF-8', @cl ] ];
89 my $log = dbg_log($ctx);
90 warn "premature EOF on $oid $log";
91 return html_page($ctx, 500, $log);
93 undef; # bref keeps growing
97 sub stream_large_blob ($$) {
100 my ($git, $oid, $type, $size, $di) = @$res;
101 my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
102 my $qsp = PublicInbox::Qspawn->new($cmd);
103 my $env = $ctx->{env};
104 $env->{'qspawn.wcb'} = $ctx->{-wcb};
105 $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
108 sub show_other_result ($$) { # future-proofing
109 my ($bref, $ctx) = @_;
110 if (my $qsp_err = delete $ctx->{-qsp_err}) {
111 return html_page($ctx, 500, dbg_log($ctx) .
112 "git show error:$qsp_err");
114 my $l = PublicInbox::Linkify->new;
115 utf8::decode($$bref);
116 html_page($ctx, 200, '<pre>', $l->to_html($$bref), '</pre><hr>',
120 sub cmt_title { # git->cat_async callback
121 my ($bref, $oid, $type, $size, $ctx) = @_;
122 utf8::decode($$bref);
123 my $title = $$bref =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/ ? $1 : '';
124 push(@{$ctx->{-cmt_pt}} , ascii_html($title)) == @{$ctx->{-cmt_P}} and
129 my ($ctx, $cb, @req) = @_;
130 # favor git(1) over Gcf2 (libgit2) for SHA-256 support
131 $ctx->{git}->cat_async($_, $cb, $ctx) for @req;
132 if ($ctx->{env}->{'pi-httpd.async'}) {
133 PublicInbox::GitAsyncCat::watch_cat($ctx->{git});
134 } else { # synchronous, generic PSGI
135 $ctx->{git}->cat_async_wait;
140 my ($ctx, $cb, @req) = @_;
141 if ($ctx->{env}->{'pi-httpd.async'}) {
142 async_check($ctx, $_, $cb, $ctx) for @req;
143 } else { # synchronous, generic PSGI
144 $ctx->{git}->check_async($_, $cb, $ctx) for @req;
145 $ctx->{git}->check_async_wait;
149 sub show_commit_start { # ->psgi_qx callback
150 my ($bref, $ctx) = @_;
151 if (my $qsp_err = delete $ctx->{-qsp_err}) {
152 return html_page($ctx, 500, dbg_log($ctx) .
153 "git show/patch-id error:$qsp_err");
155 my $patchid = (split(/ /, $$bref))[0]; # ignore commit
156 $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
157 open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
158 die "open $ctx->{-tmp}/h: $!";
159 chop(my $buf = do { local $/ = "\0"; <$fh> });
162 ($P, $p, @{$ctx->{cmt_info}}) = split(/\n/, $buf, 9);
163 return cmt_finalize($ctx) if !$P;
164 @{$ctx->{-cmt_P}} = split(/ /, $P);
165 @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
166 do_cat_async($ctx, \&cmt_title, @{$ctx->{-cmt_P}});
171 $ctx->{ibx} and return; # fall back to $upfx
172 $ctx->{git} or die 'BUG: no {git}';
173 if (my $ALL = $ctx->{www}->{pi_cfg}->ALL) {
174 if (defined(my $u = $ALL->base_url($ctx->{env}))) {
175 return wantarray ? ($u) : $u;
179 if (my $ibx_names = $ctx->{git}->{ibx_names}) {
180 my $by_name = $ctx->{www}->{pi_cfg}->{-by_name};
181 for my $name (@$ibx_names) {
182 my $ibx = $by_name->{$name} // do {
183 warn "inbox `$name' no longer exists\n";
187 my $u = defined($ibx->{url}) ?
188 prurl($ctx->{env}, $ibx->{url}) : $name;
189 $u .= '/' if substr($u, -1) ne '/';
193 wantarray ? (@ret) : $ret[0];
198 $ctx->{-linkify} //= PublicInbox::Linkify->new;
199 my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
200 my ($H, $T, $s, $f, $au, $co, $bdy) = @{delete $ctx->{cmt_info}};
201 # try to keep author and committer dates lined up
202 my $x = length($au) - length($co);
210 $_ = ascii_html($_) for ($au, $co);
211 $au =~ s!(> +)([0-9]{4,}-\S+ \S+)!
212 my ($gt, $t) = ($1, $2);
216 title="list contemporary emails">$2</a>)
218 $ctx->{-title_html} = $s = $ctx->{-linkify}->to_html($s);
219 my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
220 $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
223 href="$f.patch">patch</a>)\n <a href=#parent>parent</a> $P->[0]};
225 $x = qq(\n <a href=#parents>parents</a> $P->[0]\n);
227 $x .= qq( $_\n) for @$P;
230 $x = ' (<a href=#root_commit>root commit</a>)';
232 PublicInbox::WwwStream::html_init($ctx);
235 <pre> <a href=#commit>commit</a> $H$x
236 <a href=#tree>tree</a> <a href="$upfx$T/s/?b=">$T</a>
242 print $zfh "\n", $ctx->{-linkify}->to_html($bdy) if length($bdy);
244 open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
245 die "open $ctx->{-tmp}/p: $!";
246 if (-s $fh > $MAX_SIZE) {
247 print $zfh "---\n patch is too large to show\n";
248 } else { # prepare flush_diff:
250 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
252 $ctx->{-anchors} = {} if $x =~ /^diff --git /sm;
253 flush_diff($ctx, \$x); # undefs $x
254 # TODO: should there be another textarea which attempts to
255 # search for the exact email which was applied to make this
257 if (my $qry = delete $ctx->{-qry}) {
259 for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
260 # keep blobs as short as reasonable, emails
261 # are going to be older than what's in git
262 substr($_, 7, 64, '');
265 chop $q; # no trailing SP
266 local $Text::Wrap::columns = PublicInbox::View::COLS;
267 local $Text::Wrap::huge = 'overflow';
268 $q = wrap('', '', $q);
269 my $rows = ($q =~ tr/\n/\n/) + 1;
271 my $ibx_url = ibx_url_for($ctx);
273 if (defined $ibx_url) {
274 $alt = " `$ibx_url'";
275 $ibx_url =~ m!://! or
276 substr($ibx_url, 0, 0, '../../../');
277 $ibx_url = ascii_html($ibx_url);
283 <hr><form action="$ibx_url"
284 id=related><pre>find related emails, including ancestors/descendants/conflicts
285 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
286 <input type=submit value="search$alt"
287 />\t(<a href="${ibx_url}_/text/help/">help</a>)</pre></form>
295 id=commit>Commit</dfn> objects reference one tree, and zero or more parents.
298 id=parent>parent</dfn> commits can typically generate a patch in
299 unified diff format via `git format-patch'.
301 Multiple <dfn id=parents>parents</dfn> means the commit is a merge.
303 <dfn id=root_commit>Root commits</dfn> have no ancestor. Note that it is
304 possible to have multiple root commits when merging independent histories.
306 Every commit references one top-level <dfn id=tree>tree</dfn> object.</pre>
308 delete($ctx->{-wcb})->($ctx->html_done($x));
311 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
312 my ($r, $bref, $ctx) = @_;
313 if (!defined $r) { # sysread error
314 html_page($ctx, 500, dbg_log($ctx));
315 } elsif (index($$bref, "\n\n") >= 0) {
316 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
317 my $fn = to_filename($eml->header('Subject') // '');
318 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
319 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
320 'Content-Disposition',
321 qq(inline; filename=$fn.patch) ] ];
323 my $log = dbg_log($ctx);
324 warn "premature EOF on $ctx->{patch_oid} $log";
325 return html_page($ctx, 500, $log);
327 undef; # bref keeps growing until "\n\n"
331 sub show_patch ($$) {
332 my ($ctx, $res) = @_;
333 my ($git, $oid) = @$res;
334 my @cmd = ('git', "--git-dir=$git->{git_dir}",
335 qw(format-patch -1 --stdout -C),
336 "--signature=git format-patch -1 --stdout -C $oid", $oid);
337 my $qsp = PublicInbox::Qspawn->new(\@cmd);
338 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
339 $ctx->{patch_oid} = $oid;
340 $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
343 sub show_commit ($$) {
344 my ($ctx, $res) = @_;
345 return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
346 my ($git, $oid) = @$res;
347 # patch-id needs two passes, and we use the initial show to ensure
348 # a patch embedded inside the commit message body doesn't get fed
350 my $cmd = [ '/bin/sh', '-c',
351 "git show --encoding=UTF-8 '$SHOW_FMT'".
352 " -z --no-notes --no-patch $oid >h && ".
353 'git show --encoding=UTF-8 --pretty=format:%n -M'.
354 " --stat -p $oid >p && ".
355 "git patch-id --stable <p" ];
356 my $e = { GIT_DIR => $git->{git_dir} };
357 my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
358 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
359 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
361 $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
364 sub show_other ($$) { # just in case...
365 my ($ctx, $res) = @_;
366 my ($git, $oid, $type, $size) = @$res;
367 $size > $MAX_SIZE and return html_page($ctx, 200,
368 ascii_html($type)." $oid is too big to show\n". dbg_log($ctx));
369 my $cmd = ['git', "--git-dir=$git->{git_dir}",
370 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
371 my $qsp = PublicInbox::Qspawn->new($cmd);
372 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
373 $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
376 sub show_tree_result ($$) {
377 my ($bref, $ctx) = @_;
378 if (my $qsp_err = delete $ctx->{-qsp_err}) {
379 return html_page($ctx, 500, dbg_log($ctx) .
380 "git ls-tree -z error:$qsp_err");
382 my @ent = split(/\0/, $$bref);
383 my $qp = delete $ctx->{qp};
384 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
385 my $pfx = $ctx->{-path} // $qp->{b}; # {-path} is from RepoTree
386 $$bref = "<pre><a href=#tree>tree</a> $ctx->{tree_oid}";
387 # $REPO/tree/$path already sets {-upfx}
388 my $upfx = $ctx->{-upfx} //= '../../';
391 if (my $t = $ctx->{-obj}) {
392 my $t = ascii_html($t);
394 \n\$ git ls-tree -l $t # shows similar output on the CLI
396 } elsif ($pfx eq '') {
397 $$bref .= " (root)\n";
399 my $x = ascii_html($pfx);
401 $$bref .= qq( <a href=#path>path</a>: $x</a>\n);
405 $$bref .= qq[ (<a href=#path>path</a> unknown)\n];
407 my ($x, $m, $t, $oid, $sz, $f, $n);
408 $$bref .= "\n size name";
410 ($x, $f) = split(/\t/, $_, 2);
412 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
413 $m = $GIT_MODE{$m} // '?';
416 if ($m eq 'g') { # gitlink submodule commit
417 $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
420 my $q = 'b='.ascii_html(uri_escape_path($pfx.$f));
421 if ($m eq 'd') { $n .= '/' }
422 elsif ($m eq 'x') { $n = "<b>$n</b>" }
423 elsif ($m eq 'l') { $n = "<i>$n</i>" }
424 $$bref .= qq(\n$m\t$sz\t<a\nhref="$upfx$oid/s/?$q">$n</a>);
426 $$bref .= dbg_log($ctx);
431 id=tree>Tree</dfn> objects belong to commits or other tree objects. Trees may
432 reference blobs, sub-trees, or commits of submodules.
435 id=path>Path</dfn> names are stored in tree objects, but trees do not know
436 their own path name. A tree's path name comes from their parent tree,
437 or it is the root tree referenced by a commit object. Thus, this web UI
438 relies on the `b=' URI parameter as a hint to display the path name.
440 <dfn title="submodule commit"
441 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
444 html_page($ctx, 200, $$bref);
447 sub show_tree ($$) { # also used by RepoTree
448 my ($ctx, $res) = @_;
449 my ($git, $oid, undef, $size) = @$res;
450 $size > $MAX_SIZE and return html_page($ctx, 200,
451 "tree $oid is too big to show\n". dbg_log($ctx));
452 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
453 qw(ls-tree -z -l --no-abbrev), $oid ];
454 my $qsp = PublicInbox::Qspawn->new($cmd);
455 $ctx->{tree_oid} = $oid;
456 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
457 $qsp->psgi_qx($ctx->{env}, undef, \&show_tree_result, $ctx);
460 # returns seconds offset from git TZ offset
462 my ($tz) = @_; # e.g "-0700"
464 my $mm = $tz < 0 ? -$tz : $tz;
465 $mm = int($mm / 100) * 60 + ($mm % 100);
466 $mm = $tz < 0 ? -$mm : $mm;
470 sub show_tag_result { # git->cat_async callback
471 my ($bref, $oid, $type, $size, $ctx) = @_;
472 utf8::decode($$bref);
473 my $l = PublicInbox::Linkify->new;
474 $$bref = $l->to_html($$bref);
475 $$bref =~ s!^object ([a-f0-9]+)!object <a
476 href=../../$1/s/>$1</a>!;
478 $$bref =~ s/^(tagger .*> )([0-9]+) ([\-+]?[0-9]+)/$1.strftime(
479 '%Y-%m-%d %H:%M:%S', gmtime($2 + tz_adj($3)))." $3"/sme;
480 # TODO: download link
481 html_page($ctx, 200, '<pre>', $$bref, '</pre>', dbg_log($ctx));
485 my ($ctx, $res) = @_;
486 my ($git, $oid) = @$res;
488 do_cat_async($ctx, \&show_tag_result, $oid);
491 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
493 my ($res, $ctx) = @_;
494 my $hints = delete $ctx->{hints};
495 $res or return html_page($ctx, 404, dbg_log($ctx));
496 ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
498 my ($git, $oid, $type, $size, $di) = @$res;
499 return show_commit($ctx, $res) if $type eq 'commit';
500 return show_tree($ctx, $res) if $type eq 'tree';
501 return show_tag($ctx, $res) if $type eq 'tag';
502 return show_other($ctx, $res) if $type ne 'blob';
503 my $paths = $ctx->{-paths} //= do {
504 my $path = to_filename($di->{path_b}//$hints->{path_b}//'blob');
505 my $raw_more = qq[(<a\nhref="$path">raw</a>)];
506 [ $path, $raw_more ];
509 if ($size > $MAX_SIZE) {
510 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
511 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
512 <pre><b>Too big to show, download available</b>
513 blob $oid $size bytes $paths->[1]</pre>
516 bless $ctx, 'PublicInbox::WwwStream'; # for DESTROY
518 do_cat_async($ctx, \&show_blob, $oid);
521 sub show_blob { # git->cat_async callback
522 my ($blob, $oid, $type, $size, $ctx) = @_;
524 my $e = "Failed to retrieve generated blob ($oid)";
525 warn "$e ($ctx->{git}->{git_dir}) type=$type";
526 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
529 my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
530 if (defined $ctx->{fn}) {
531 my $h = [ 'Content-Length', $size, 'Content-Type' ];
532 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
533 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
536 my ($path, $raw_more) = @{delete $ctx->{-paths}};
537 $bin and return html_page($ctx, 200,
538 "<pre>blob $oid $size bytes (binary)" .
539 " $raw_more</pre>".dbg_log($ctx));
541 # TODO: detect + convert to ensure validity
542 utf8::decode($$blob);
543 my $nl = ($$blob =~ s/\r?\n/\n/sg);
544 my $pad = length($nl);
546 ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
547 my $ok = $hl->do_hl($blob, $path) if $hl;
551 $$blob = ascii_html($$blob);
554 # using some of the same CSS class names and ids as cgit
555 my $x = "<pre>blob $oid $size bytes $raw_more</pre>" .
556 "<hr /><table\nclass=blob>".
557 "<tr><td\nclass=linenumbers><pre>";
558 # scratchpad in this loop is faster here than `printf $zfh':
559 $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
560 $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
561 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
562 html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
563 '</code></pre></td></tr></table>'.dbg_log($ctx));
566 # GET /$INBOX/$GIT_OBJECT_ID/s/
567 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
569 my ($ctx, $oid_b, $fn) = @_;
571 my $hints = $ctx->{hints} = {};
572 while (my ($from, $to) = each %QP_MAP) {
573 defined(my $v = $qp->{$from}) or next;
574 $hints->{$to} = $v if $v ne '';
577 $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
578 open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
579 my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
580 \&solve_result, $ctx);
581 $solver->{gits} //= [ $ctx->{git} ];
582 $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
583 # PSGI server will call this immediately and give us a callback (-wcb)
585 $ctx->{-wcb} = $_[0]; # HTTP write callback
586 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);