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 {
66 warn "readline(log): $!";
67 return '<pre>debug log read error</pre>';
71 return '' if $log eq '';
72 $ctx->{-linkify} //= PublicInbox::Linkify->new;
73 "<hr><pre>debug log:\n\n".
74 $ctx->{-linkify}->to_html($log).'</pre>';
77 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
78 my ($r, $bref, $ctx) = @_;
79 my ($git, $oid, $type, $size, $di) = @{$ctx->{-res}};
80 my @cl = ('Content-Length', $size);
81 if (!defined $r) { # sysread error
82 html_page($ctx, 500, dbg_log($ctx));
83 } elsif (index($$bref, "\0") >= 0) {
84 [200, [qw(Content-Type application/octet-stream), @cl] ];
86 my $n = length($$bref);
87 if ($n >= $BIN_DETECT || $n == $size) {
88 return [200, [ 'Content-Type',
89 'text/plain; charset=UTF-8', @cl ] ];
92 my $log = dbg_log($ctx);
93 warn "premature EOF on $oid $log";
94 return html_page($ctx, 500, $log);
96 undef; # bref keeps growing
100 sub stream_large_blob ($$) {
101 my ($ctx, $res) = @_;
103 my ($git, $oid, $type, $size, $di) = @$res;
104 my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
105 my $qsp = PublicInbox::Qspawn->new($cmd);
106 my $env = $ctx->{env};
107 $env->{'qspawn.wcb'} = $ctx->{-wcb};
108 $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
111 sub show_other_result ($$) { # future-proofing
112 my ($bref, $ctx) = @_;
113 if (my $qsp_err = delete $ctx->{-qsp_err}) {
114 return html_page($ctx, 500, dbg_log($ctx) .
115 "git show error:$qsp_err");
117 my $l = PublicInbox::Linkify->new;
118 utf8::decode($$bref);
119 html_page($ctx, 200, '<pre>', $l->to_html($$bref), '</pre><hr>',
123 sub cmt_title { # git->cat_async callback
124 my ($bref, $oid, $type, $size, $ctx) = @_;
125 utf8::decode($$bref);
126 my $title = $$bref =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/ ? $1 : '';
127 push(@{$ctx->{-cmt_pt}} , ascii_html($title)) == @{$ctx->{-cmt_P}} and
132 my ($ctx, $cb, @req) = @_;
133 # favor git(1) over Gcf2 (libgit2) for SHA-256 support
134 $ctx->{git}->cat_async($_, $cb, $ctx) for @req;
135 if ($ctx->{env}->{'pi-httpd.async'}) {
136 PublicInbox::GitAsyncCat::watch_cat($ctx->{git});
137 } else { # synchronous, generic PSGI
138 $ctx->{git}->cat_async_wait;
143 my ($ctx, $cb, @req) = @_;
144 if ($ctx->{env}->{'pi-httpd.async'}) {
145 async_check($ctx, $_, $cb, $ctx) for @req;
146 } else { # synchronous, generic PSGI
147 $ctx->{git}->check_async($_, $cb, $ctx) for @req;
148 $ctx->{git}->check_async_wait;
152 sub show_commit_start { # ->psgi_qx callback
153 my ($bref, $ctx) = @_;
154 if (my $qsp_err = delete $ctx->{-qsp_err}) {
155 return html_page($ctx, 500, dbg_log($ctx) .
156 "git show/patch-id error:$qsp_err");
158 my $patchid = (split(/ /, $$bref))[0]; # ignore commit
159 $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
160 open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
161 die "open $ctx->{-tmp}/h: $!";
162 chop(my $buf = do { local $/ = "\0"; <$fh> });
165 ($P, $p, @{$ctx->{cmt_info}}) = split(/\n/, $buf, 9);
166 return cmt_finalize($ctx) if !$P;
167 @{$ctx->{-cmt_P}} = split(/ /, $P);
168 @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
169 do_cat_async($ctx, \&cmt_title, @{$ctx->{-cmt_P}});
174 $ctx->{ibx} and return; # fall back to $upfx
175 $ctx->{git} or die 'BUG: no {git}';
176 if (my $ALL = $ctx->{www}->{pi_cfg}->ALL) {
177 if (defined(my $u = $ALL->base_url($ctx->{env}))) {
178 return wantarray ? ($u) : $u;
182 if (my $ibx_names = $ctx->{git}->{ibx_names}) {
183 my $by_name = $ctx->{www}->{pi_cfg}->{-by_name};
184 for my $name (@$ibx_names) {
185 my $ibx = $by_name->{$name} // do {
186 warn "inbox `$name' no longer exists\n";
190 my $u = defined($ibx->{url}) ?
191 prurl($ctx->{env}, $ibx->{url}) : $name;
192 $u .= '/' if substr($u, -1) ne '/';
196 wantarray ? (@ret) : $ret[0];
201 $ctx->{-linkify} //= PublicInbox::Linkify->new;
202 my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
203 my ($H, $T, $s, $f, $au, $co, $bdy) = @{delete $ctx->{cmt_info}};
204 # try to keep author and committer dates lined up
205 my $x = length($au) - length($co);
213 $_ = ascii_html($_) for ($au, $co);
214 my $ibx_url = ibx_url_for($ctx) // $upfx;
215 $au =~ s!(> +)([0-9]{4,}-\S+ \S+)!
216 my ($gt, $t) = ($1, $2);
220 title="list contemporary emails">$2</a>)
223 $ctx->{-title_html} = $s = $ctx->{-linkify}->to_html($s);
224 my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
225 $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
228 href="$f.patch">patch</a>)\n <a href=#parent>parent</a> $P->[0]};
230 $x = qq(\n <a href=#parents>parents</a> $P->[0]\n);
232 $x .= qq( $_\n) for @$P;
235 $x = ' (<a href=#root_commit>root commit</a>)';
237 PublicInbox::WwwStream::html_init($ctx);
240 <pre> <a href=#commit>commit</a> $H$x
241 <a href=#tree>tree</a> <a href="$upfx$T/s/?b=">$T</a>
247 print $zfh "\n", $ctx->{-linkify}->to_html($bdy) if length($bdy);
249 open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
250 die "open $ctx->{-tmp}/p: $!";
251 if (-s $fh > $MAX_SIZE) {
252 print $zfh "---\n patch is too large to show\n";
253 } else { # prepare flush_diff:
255 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
257 $ctx->{-anchors} = {} if $x =~ /^diff --git /sm;
258 flush_diff($ctx, \$x); # undefs $x
259 # TODO: should there be another textarea which attempts to
260 # search for the exact email which was applied to make this
262 if (my $qry = delete $ctx->{-qry}) {
264 for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
265 # keep blobs as short as reasonable, emails
266 # are going to be older than what's in git
267 substr($_, 7, 64, '');
270 chop $q; # no trailing SP
271 local $Text::Wrap::columns = PublicInbox::View::COLS;
272 local $Text::Wrap::huge = 'overflow';
273 $q = wrap('', '', $q);
274 my $rows = ($q =~ tr/\n/\n/) + 1;
276 my $ibx_url = ibx_url_for($ctx);
278 if (defined $ibx_url) {
279 $alt = " `$ibx_url'";
280 $ibx_url =~ m!://! or
281 substr($ibx_url, 0, 0, '../../../');
282 $ibx_url = ascii_html($ibx_url);
288 <hr><form action="$ibx_url"
289 id=related><pre>find related emails, including ancestors/descendants/conflicts
290 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
291 <input type=submit value="search$alt"
292 />\t(<a href="${ibx_url}_/text/help/">help</a>)</pre></form>
300 id=commit>Commit</dfn> objects reference one tree, and zero or more parents.
303 id=parent>parent</dfn> commits can typically generate a patch in
304 unified diff format via `git format-patch'.
306 Multiple <dfn id=parents>parents</dfn> means the commit is a merge.
308 <dfn id=root_commit>Root commits</dfn> have no ancestor. Note that it is
309 possible to have multiple root commits when merging independent histories.
311 Every commit references one top-level <dfn id=tree>tree</dfn> object.</pre>
313 delete($ctx->{-wcb})->($ctx->html_done($x));
316 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
317 my ($r, $bref, $ctx) = @_;
318 if (!defined $r) { # sysread error
319 html_page($ctx, 500, dbg_log($ctx));
320 } elsif (index($$bref, "\n\n") >= 0) {
321 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
322 my $fn = to_filename($eml->header('Subject') // '');
323 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
324 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
325 'Content-Disposition',
326 qq(inline; filename=$fn.patch) ] ];
328 my $log = dbg_log($ctx);
329 warn "premature EOF on $ctx->{patch_oid} $log";
330 return html_page($ctx, 500, $log);
332 undef; # bref keeps growing until "\n\n"
336 sub show_patch ($$) {
337 my ($ctx, $res) = @_;
338 my ($git, $oid) = @$res;
339 my @cmd = ('git', "--git-dir=$git->{git_dir}",
340 qw(format-patch -1 --stdout -C),
341 "--signature=git format-patch -1 --stdout -C $oid", $oid);
342 my $qsp = PublicInbox::Qspawn->new(\@cmd);
343 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
344 $ctx->{patch_oid} = $oid;
345 $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
348 sub show_commit ($$) {
349 my ($ctx, $res) = @_;
350 return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
351 my ($git, $oid) = @$res;
352 # patch-id needs two passes, and we use the initial show to ensure
353 # a patch embedded inside the commit message body doesn't get fed
355 my $cmd = [ '/bin/sh', '-c',
356 "git show --encoding=UTF-8 '$SHOW_FMT'".
357 " -z --no-notes --no-patch $oid >h && ".
358 'git show --encoding=UTF-8 --pretty=format:%n -M'.
359 " --stat -p $oid >p && ".
360 "git patch-id --stable <p" ];
361 my $e = { GIT_DIR => $git->{git_dir} };
362 my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
363 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
364 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
366 $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
369 sub show_other ($$) { # just in case...
370 my ($ctx, $res) = @_;
371 my ($git, $oid, $type, $size) = @$res;
372 $size > $MAX_SIZE and return html_page($ctx, 200,
373 ascii_html($type)." $oid is too big to show\n". dbg_log($ctx));
374 my $cmd = ['git', "--git-dir=$git->{git_dir}",
375 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
376 my $qsp = PublicInbox::Qspawn->new($cmd);
377 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
378 $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
381 sub show_tree_result ($$) {
382 my ($bref, $ctx) = @_;
383 if (my $qsp_err = delete $ctx->{-qsp_err}) {
384 return html_page($ctx, 500, dbg_log($ctx) .
385 "git ls-tree -z error:$qsp_err");
387 my @ent = split(/\0/, $$bref);
388 my $qp = delete $ctx->{qp};
389 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
390 my $pfx = $ctx->{-path} // $qp->{b}; # {-path} is from RepoTree
391 $$bref = "<pre><a href=#tree>tree</a> $ctx->{tree_oid}";
392 # $REPO/tree/$path already sets {-upfx}
393 my $upfx = $ctx->{-upfx} //= '../../';
396 if (my $t = $ctx->{-obj}) {
397 my $t = ascii_html($t);
399 \n\$ git ls-tree -l $t # shows similar output on the CLI
401 } elsif ($pfx eq '') {
402 $$bref .= " (root)\n";
404 my $x = ascii_html($pfx);
406 $$bref .= qq( <a href=#path>path</a>: $x</a>\n);
410 $$bref .= qq[ (<a href=#path>path</a> unknown)\n];
412 my ($x, $m, $t, $oid, $sz, $f, $n);
413 $$bref .= "\n size name";
415 ($x, $f) = split(/\t/, $_, 2);
417 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
418 $m = $GIT_MODE{$m} // '?';
421 if ($m eq 'g') { # gitlink submodule commit
422 $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
425 my $q = 'b='.ascii_html(uri_escape_path($pfx.$f));
426 if ($m eq 'd') { $n .= '/' }
427 elsif ($m eq 'x') { $n = "<b>$n</b>" }
428 elsif ($m eq 'l') { $n = "<i>$n</i>" }
429 $$bref .= qq(\n$m\t$sz\t<a\nhref="$upfx$oid/s/?$q">$n</a>);
431 $$bref .= dbg_log($ctx);
436 id=tree>Tree</dfn> objects belong to commits or other tree objects. Trees may
437 reference blobs, sub-trees, or commits of submodules.
440 id=path>Path</dfn> names are stored in tree objects, but trees do not know
441 their own path name. A tree's path name comes from their parent tree,
442 or it is the root tree referenced by a commit object. Thus, this web UI
443 relies on the `b=' URI parameter as a hint to display the path name.
445 <dfn title="submodule commit"
446 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
449 html_page($ctx, 200, $$bref);
452 sub show_tree ($$) { # also used by RepoTree
453 my ($ctx, $res) = @_;
454 my ($git, $oid, undef, $size) = @$res;
455 $size > $MAX_SIZE and return html_page($ctx, 200,
456 "tree $oid is too big to show\n". dbg_log($ctx));
457 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
458 qw(ls-tree -z -l --no-abbrev), $oid ];
459 my $qsp = PublicInbox::Qspawn->new($cmd);
460 $ctx->{tree_oid} = $oid;
461 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
462 $qsp->psgi_qx($ctx->{env}, undef, \&show_tree_result, $ctx);
465 # returns seconds offset from git TZ offset
467 my ($tz) = @_; # e.g "-0700"
469 my $mm = $tz < 0 ? -$tz : $tz;
470 $mm = int($mm / 100) * 60 + ($mm % 100);
471 $mm = $tz < 0 ? -$mm : $mm;
475 sub show_tag_result { # git->cat_async callback
476 my ($bref, $oid, $type, $size, $ctx) = @_;
477 utf8::decode($$bref);
478 my $l = PublicInbox::Linkify->new;
479 $$bref = $l->to_html($$bref);
480 $$bref =~ s!^object ([a-f0-9]+)!object <a
481 href=../../$1/s/>$1</a>!;
483 $$bref =~ s/^(tagger .*> )([0-9]+) ([\-+]?[0-9]+)/$1.strftime(
484 '%Y-%m-%d %H:%M:%S', gmtime($2 + tz_adj($3)))." $3"/sme;
485 # TODO: download link
486 html_page($ctx, 200, '<pre>', $$bref, '</pre>', dbg_log($ctx));
490 my ($ctx, $res) = @_;
491 my ($git, $oid) = @$res;
493 do_cat_async($ctx, \&show_tag_result, $oid);
496 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
498 my ($res, $ctx) = @_;
499 my $hints = delete $ctx->{hints};
500 $res or return html_page($ctx, 404, 'Not found', dbg_log($ctx));
501 ref($res) eq 'ARRAY' or
502 return html_page($ctx, 500, 'Internal error', dbg_log($ctx));
504 my ($git, $oid, $type, $size, $di) = @$res;
505 return show_commit($ctx, $res) if $type eq 'commit';
506 return show_tree($ctx, $res) if $type eq 'tree';
507 return show_tag($ctx, $res) if $type eq 'tag';
508 return show_other($ctx, $res) if $type ne 'blob';
509 my $fn = $di->{path_b} // $hints->{path_b};
510 my $paths = $ctx->{-paths} //= do {
511 my $path = to_filename($fn // 'blob');
512 my $raw_more = qq[(<a\nhref="$path">raw</a>)];
515 # XXX not sure if this is the correct wording
518 name: ${\ascii_html($fn)} \t # note: path name is non-authoritative<a
519 href="#pathdef" id=top>(*)</a>);
520 $def[0] = "<hr><pre\nid=pathdef>" .
521 '(*) Git path names are given by the tree(s) the blob belongs to.
522 Blobs themselves have no identifier aside from the hash of its contents.'.
523 qq(<a\nhref="#top">^</a></pre>);
525 [ $path, $raw_more, @def ];
527 $ctx->{-q_value_html} //= do {
528 my $s = defined($fn) ? 'dfn:'.ascii_html($fn).' ' : '';
529 $s.'dfpost:'.substr($oid, 0, 7);
532 if ($size > $MAX_SIZE) {
533 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
534 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
535 <pre><b>Too big to show, download available</b>
536 blob $oid $size bytes $paths->[1]</pre>
539 bless $ctx, 'PublicInbox::WwwStream'; # for DESTROY
541 do_cat_async($ctx, \&show_blob, $oid);
544 sub show_blob { # git->cat_async callback
545 my ($blob, $oid, $type, $size, $ctx) = @_;
547 my $e = "Failed to retrieve generated blob ($oid)";
548 warn "$e ($ctx->{git}->{git_dir}) type=$type";
549 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
552 my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
553 if (defined $ctx->{fn}) {
554 my $h = [ 'Content-Length', $size, 'Content-Type' ];
555 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
556 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
559 my ($path, $raw_more, @def) = @{delete $ctx->{-paths}};
560 $bin and return html_page($ctx, 200,
561 "<pre>blob $oid $size bytes (binary)" .
562 " $raw_more</pre>".dbg_log($ctx));
564 # TODO: detect + convert to ensure validity
565 utf8::decode($$blob);
566 my $nl = ($$blob =~ s/\r?\n/\n/sg);
567 my $pad = length($nl);
569 ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
570 my $ok = $hl->do_hl($blob, $path) if $hl;
574 $$blob = ascii_html($$blob);
577 # using some of the same CSS class names and ids as cgit
578 my $x = "<pre>blob $oid $size bytes $raw_more</pre>" .
579 "<hr /><table\nclass=blob>".
580 "<tr><td\nclass=linenumbers><pre>";
581 # scratchpad in this loop is faster here than `printf $zfh':
582 $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
583 $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
584 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
585 html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
586 '</code></pre></td></tr></table>'.dbg_log($ctx), @def);
589 # GET /$INBOX/$GIT_OBJECT_ID/s/
590 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
592 my ($ctx, $oid_b, $fn) = @_;
594 my $hints = $ctx->{hints} = {};
595 while (my ($from, $to) = each %QP_MAP) {
596 defined(my $v = $qp->{$from}) or next;
597 $hints->{$to} = $v if $v ne '';
600 $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
601 unless ($ctx->{lh}) {
602 open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or
605 my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
606 \&solve_result, $ctx);
607 $solver->{gits} //= [ $ctx->{git} ];
608 $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
609 # PSGI server will call this immediately and give us a callback (-wcb)
611 $ctx->{-wcb} = $_[0]; # HTTP write callback
612 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);