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 my $ibx_url = ibx_url_for($ctx) // $upfx;
212 $au =~ s!(> +)([0-9]{4,}-\S+ \S+)!
213 my ($gt, $t) = ($1, $2);
217 title="list contemporary emails">$2</a>)
220 $ctx->{-title_html} = $s = $ctx->{-linkify}->to_html($s);
221 my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
222 $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
225 href="$f.patch">patch</a>)\n <a href=#parent>parent</a> $P->[0]};
227 $x = qq(\n <a href=#parents>parents</a> $P->[0]\n);
229 $x .= qq( $_\n) for @$P;
232 $x = ' (<a href=#root_commit>root commit</a>)';
234 PublicInbox::WwwStream::html_init($ctx);
237 <pre> <a href=#commit>commit</a> $H$x
238 <a href=#tree>tree</a> <a href="$upfx$T/s/?b=">$T</a>
244 print $zfh "\n", $ctx->{-linkify}->to_html($bdy) if length($bdy);
246 open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
247 die "open $ctx->{-tmp}/p: $!";
248 if (-s $fh > $MAX_SIZE) {
249 print $zfh "---\n patch is too large to show\n";
250 } else { # prepare flush_diff:
252 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
254 $ctx->{-anchors} = {} if $x =~ /^diff --git /sm;
255 flush_diff($ctx, \$x); # undefs $x
256 # TODO: should there be another textarea which attempts to
257 # search for the exact email which was applied to make this
259 if (my $qry = delete $ctx->{-qry}) {
261 for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
262 # keep blobs as short as reasonable, emails
263 # are going to be older than what's in git
264 substr($_, 7, 64, '');
267 chop $q; # no trailing SP
268 local $Text::Wrap::columns = PublicInbox::View::COLS;
269 local $Text::Wrap::huge = 'overflow';
270 $q = wrap('', '', $q);
271 my $rows = ($q =~ tr/\n/\n/) + 1;
273 my $ibx_url = ibx_url_for($ctx);
275 if (defined $ibx_url) {
276 $alt = " `$ibx_url'";
277 $ibx_url =~ m!://! or
278 substr($ibx_url, 0, 0, '../../../');
279 $ibx_url = ascii_html($ibx_url);
285 <hr><form action="$ibx_url"
286 id=related><pre>find related emails, including ancestors/descendants/conflicts
287 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
288 <input type=submit value="search$alt"
289 />\t(<a href="${ibx_url}_/text/help/">help</a>)</pre></form>
297 id=commit>Commit</dfn> objects reference one tree, and zero or more parents.
300 id=parent>parent</dfn> commits can typically generate a patch in
301 unified diff format via `git format-patch'.
303 Multiple <dfn id=parents>parents</dfn> means the commit is a merge.
305 <dfn id=root_commit>Root commits</dfn> have no ancestor. Note that it is
306 possible to have multiple root commits when merging independent histories.
308 Every commit references one top-level <dfn id=tree>tree</dfn> object.</pre>
310 delete($ctx->{-wcb})->($ctx->html_done($x));
313 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
314 my ($r, $bref, $ctx) = @_;
315 if (!defined $r) { # sysread error
316 html_page($ctx, 500, dbg_log($ctx));
317 } elsif (index($$bref, "\n\n") >= 0) {
318 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
319 my $fn = to_filename($eml->header('Subject') // '');
320 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
321 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
322 'Content-Disposition',
323 qq(inline; filename=$fn.patch) ] ];
325 my $log = dbg_log($ctx);
326 warn "premature EOF on $ctx->{patch_oid} $log";
327 return html_page($ctx, 500, $log);
329 undef; # bref keeps growing until "\n\n"
333 sub show_patch ($$) {
334 my ($ctx, $res) = @_;
335 my ($git, $oid) = @$res;
336 my @cmd = ('git', "--git-dir=$git->{git_dir}",
337 qw(format-patch -1 --stdout -C),
338 "--signature=git format-patch -1 --stdout -C $oid", $oid);
339 my $qsp = PublicInbox::Qspawn->new(\@cmd);
340 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
341 $ctx->{patch_oid} = $oid;
342 $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
345 sub show_commit ($$) {
346 my ($ctx, $res) = @_;
347 return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
348 my ($git, $oid) = @$res;
349 # patch-id needs two passes, and we use the initial show to ensure
350 # a patch embedded inside the commit message body doesn't get fed
352 my $cmd = [ '/bin/sh', '-c',
353 "git show --encoding=UTF-8 '$SHOW_FMT'".
354 " -z --no-notes --no-patch $oid >h && ".
355 'git show --encoding=UTF-8 --pretty=format:%n -M'.
356 " --stat -p $oid >p && ".
357 "git patch-id --stable <p" ];
358 my $e = { GIT_DIR => $git->{git_dir} };
359 my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
360 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
361 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
363 $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
366 sub show_other ($$) { # just in case...
367 my ($ctx, $res) = @_;
368 my ($git, $oid, $type, $size) = @$res;
369 $size > $MAX_SIZE and return html_page($ctx, 200,
370 ascii_html($type)." $oid is too big to show\n". dbg_log($ctx));
371 my $cmd = ['git', "--git-dir=$git->{git_dir}",
372 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
373 my $qsp = PublicInbox::Qspawn->new($cmd);
374 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
375 $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
378 sub show_tree_result ($$) {
379 my ($bref, $ctx) = @_;
380 if (my $qsp_err = delete $ctx->{-qsp_err}) {
381 return html_page($ctx, 500, dbg_log($ctx) .
382 "git ls-tree -z error:$qsp_err");
384 my @ent = split(/\0/, $$bref);
385 my $qp = delete $ctx->{qp};
386 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
387 my $pfx = $ctx->{-path} // $qp->{b}; # {-path} is from RepoTree
388 $$bref = "<pre><a href=#tree>tree</a> $ctx->{tree_oid}";
389 # $REPO/tree/$path already sets {-upfx}
390 my $upfx = $ctx->{-upfx} //= '../../';
393 if (my $t = $ctx->{-obj}) {
394 my $t = ascii_html($t);
396 \n\$ git ls-tree -l $t # shows similar output on the CLI
398 } elsif ($pfx eq '') {
399 $$bref .= " (root)\n";
401 my $x = ascii_html($pfx);
403 $$bref .= qq( <a href=#path>path</a>: $x</a>\n);
407 $$bref .= qq[ (<a href=#path>path</a> unknown)\n];
409 my ($x, $m, $t, $oid, $sz, $f, $n);
410 $$bref .= "\n size name";
412 ($x, $f) = split(/\t/, $_, 2);
414 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
415 $m = $GIT_MODE{$m} // '?';
418 if ($m eq 'g') { # gitlink submodule commit
419 $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
422 my $q = 'b='.ascii_html(uri_escape_path($pfx.$f));
423 if ($m eq 'd') { $n .= '/' }
424 elsif ($m eq 'x') { $n = "<b>$n</b>" }
425 elsif ($m eq 'l') { $n = "<i>$n</i>" }
426 $$bref .= qq(\n$m\t$sz\t<a\nhref="$upfx$oid/s/?$q">$n</a>);
428 $$bref .= dbg_log($ctx);
433 id=tree>Tree</dfn> objects belong to commits or other tree objects. Trees may
434 reference blobs, sub-trees, or commits of submodules.
437 id=path>Path</dfn> names are stored in tree objects, but trees do not know
438 their own path name. A tree's path name comes from their parent tree,
439 or it is the root tree referenced by a commit object. Thus, this web UI
440 relies on the `b=' URI parameter as a hint to display the path name.
442 <dfn title="submodule commit"
443 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
446 html_page($ctx, 200, $$bref);
449 sub show_tree ($$) { # also used by RepoTree
450 my ($ctx, $res) = @_;
451 my ($git, $oid, undef, $size) = @$res;
452 $size > $MAX_SIZE and return html_page($ctx, 200,
453 "tree $oid is too big to show\n". dbg_log($ctx));
454 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
455 qw(ls-tree -z -l --no-abbrev), $oid ];
456 my $qsp = PublicInbox::Qspawn->new($cmd);
457 $ctx->{tree_oid} = $oid;
458 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
459 $qsp->psgi_qx($ctx->{env}, undef, \&show_tree_result, $ctx);
462 # returns seconds offset from git TZ offset
464 my ($tz) = @_; # e.g "-0700"
466 my $mm = $tz < 0 ? -$tz : $tz;
467 $mm = int($mm / 100) * 60 + ($mm % 100);
468 $mm = $tz < 0 ? -$mm : $mm;
472 sub show_tag_result { # git->cat_async callback
473 my ($bref, $oid, $type, $size, $ctx) = @_;
474 utf8::decode($$bref);
475 my $l = PublicInbox::Linkify->new;
476 $$bref = $l->to_html($$bref);
477 $$bref =~ s!^object ([a-f0-9]+)!object <a
478 href=../../$1/s/>$1</a>!;
480 $$bref =~ s/^(tagger .*> )([0-9]+) ([\-+]?[0-9]+)/$1.strftime(
481 '%Y-%m-%d %H:%M:%S', gmtime($2 + tz_adj($3)))." $3"/sme;
482 # TODO: download link
483 html_page($ctx, 200, '<pre>', $$bref, '</pre>', dbg_log($ctx));
487 my ($ctx, $res) = @_;
488 my ($git, $oid) = @$res;
490 do_cat_async($ctx, \&show_tag_result, $oid);
493 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
495 my ($res, $ctx) = @_;
496 my $hints = delete $ctx->{hints};
497 $res or return html_page($ctx, 404, dbg_log($ctx));
498 ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
500 my ($git, $oid, $type, $size, $di) = @$res;
501 return show_commit($ctx, $res) if $type eq 'commit';
502 return show_tree($ctx, $res) if $type eq 'tree';
503 return show_tag($ctx, $res) if $type eq 'tag';
504 return show_other($ctx, $res) if $type ne 'blob';
505 my $fn = $di->{path_b} // $hints->{path_b};
506 my $paths = $ctx->{-paths} //= do {
507 my $path = to_filename($fn // 'blob');
508 my $raw_more = qq[(<a\nhref="$path">raw</a>)];
510 # XXX not sure if this is the correct wording
511 defined($fn) and $raw_more .=
512 "\nname: ${\ascii_html($fn)} \t # note: path name is non-authoritative";
513 [ $path, $raw_more ];
515 $ctx->{-q_value_html} //= do {
516 my $s = defined($fn) ? 'dfn:'.ascii_html($fn).' ' : '';
517 $s.'dfpost:'.substr($oid, 0, 7);
520 if ($size > $MAX_SIZE) {
521 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
522 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
523 <pre><b>Too big to show, download available</b>
524 blob $oid $size bytes $paths->[1]</pre>
527 bless $ctx, 'PublicInbox::WwwStream'; # for DESTROY
529 do_cat_async($ctx, \&show_blob, $oid);
532 sub show_blob { # git->cat_async callback
533 my ($blob, $oid, $type, $size, $ctx) = @_;
535 my $e = "Failed to retrieve generated blob ($oid)";
536 warn "$e ($ctx->{git}->{git_dir}) type=$type";
537 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
540 my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
541 if (defined $ctx->{fn}) {
542 my $h = [ 'Content-Length', $size, 'Content-Type' ];
543 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
544 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
547 my ($path, $raw_more) = @{delete $ctx->{-paths}};
548 $bin and return html_page($ctx, 200,
549 "<pre>blob $oid $size bytes (binary)" .
550 " $raw_more</pre>".dbg_log($ctx));
552 # TODO: detect + convert to ensure validity
553 utf8::decode($$blob);
554 my $nl = ($$blob =~ s/\r?\n/\n/sg);
555 my $pad = length($nl);
557 ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
558 my $ok = $hl->do_hl($blob, $path) if $hl;
562 $$blob = ascii_html($$blob);
565 # using some of the same CSS class names and ids as cgit
566 my $x = "<pre>blob $oid $size bytes $raw_more</pre>" .
567 "<hr /><table\nclass=blob>".
568 "<tr><td\nclass=linenumbers><pre>";
569 # scratchpad in this loop is faster here than `printf $zfh':
570 $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
571 $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
572 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
573 html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
574 '</code></pre></td></tr></table>'.dbg_log($ctx));
577 # GET /$INBOX/$GIT_OBJECT_ID/s/
578 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
580 my ($ctx, $oid_b, $fn) = @_;
582 my $hints = $ctx->{hints} = {};
583 while (my ($from, $to) = each %QP_MAP) {
584 defined(my $v = $qp->{$from}) or next;
585 $hints->{$to} = $v if $v ne '';
588 $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
589 open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
590 my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
591 \&solve_result, $ctx);
592 $solver->{gits} //= [ $ctx->{git} ];
593 $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
594 # PSGI server will call this immediately and give us a callback (-wcb)
596 $ctx->{-wcb} = $_[0]; # HTTP write callback
597 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);