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
128 sub show_commit_start { # ->psgi_qx callback
129 my ($bref, $ctx) = @_;
130 if (my $qsp_err = delete $ctx->{-qsp_err}) {
131 return html_page($ctx, 500, dbg_log($ctx) .
132 "git show/patch-id error:$qsp_err");
134 my $patchid = (split(/ /, $$bref))[0]; # ignore commit
135 $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
136 open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
137 die "open $ctx->{-tmp}/h: $!";
138 chop(my $buf = do { local $/ = "\0"; <$fh> });
141 ($P, $p, @{$ctx->{cmt_info}}) = split(/\n/, $buf, 9);
142 return cmt_finalize($ctx) if !$P;
143 @{$ctx->{-cmt_P}} = split(/ /, $P);
144 @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
145 if ($ctx->{env}->{'pi-httpd.async'}) {
146 for (@{$ctx->{-cmt_P}}) {
147 ibx_async_cat($ctx, $_, \&cmt_title, $ctx);
149 } else { # synchronous
150 for (@{$ctx->{-cmt_P}}) {
151 $ctx->{git}->cat_async($_, \&cmt_title, $ctx);
153 $ctx->{git}->cat_async_wait;
159 $ctx->{ibx} and return; # fall back to $upfx
160 $ctx->{git} or die 'BUG: no {git}';
161 if (my $ALL = $ctx->{www}->{pi_cfg}->ALL) {
162 if (defined(my $u = $ALL->base_url($ctx->{env}))) {
163 return wantarray ? ($u) : $u;
167 if (my $ibx_names = $ctx->{git}->{ibx_names}) {
168 my $by_name = $ctx->{www}->{pi_cfg}->{-by_name};
169 for my $name (@$ibx_names) {
170 my $ibx = $by_name->{$name} // do {
171 warn "inbox `$name' no longer exists\n";
175 my $u = defined($ibx->{url}) ?
176 prurl($ctx->{env}, $ibx->{url}) : $name;
177 $u .= '/' if substr($u, -1) ne '/';
181 wantarray ? (@ret) : $ret[0];
186 $ctx->{-linkify} //= PublicInbox::Linkify->new;
187 my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
188 my ($H, $T, $s, $f, $au, $co, $bdy) = @{delete $ctx->{cmt_info}};
189 # try to keep author and committer dates lined up
190 my $x = length($au) - length($co);
198 $_ = ascii_html($_) for ($au, $co);
199 $au =~ s!(> +)([0-9]{4,}-\S+ \S+)!
200 my ($gt, $t) = ($1, $2);
204 title="list contemporary emails">$2</a>)
206 $ctx->{-title_html} = $s = $ctx->{-linkify}->to_html($s);
207 my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
208 $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
211 href="$f.patch">patch</a>)\n <a href=#parent>parent</a> $P->[0]};
213 $x = qq(\n <a href=#parents>parents</a> $P->[0]\n);
215 $x .= qq( $_\n) for @$P;
218 $x = ' (<a href=#root_commit>root commit</a>)';
220 PublicInbox::WwwStream::html_init($ctx);
223 <pre> <a href=#commit>commit</a> $H$x
224 <a href=#tree>tree</a> <a href="$upfx$T/s/?b=">$T</a>
230 print $zfh "\n", $ctx->{-linkify}->to_html($bdy) if length($bdy);
232 open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
233 die "open $ctx->{-tmp}/p: $!";
234 if (-s $fh > $MAX_SIZE) {
235 print $zfh "---\n patch is too large to show\n";
236 } else { # prepare flush_diff:
238 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
240 $ctx->{-anchors} = {} if $x =~ /^diff --git /sm;
241 flush_diff($ctx, \$x); # undefs $x
242 # TODO: should there be another textarea which attempts to
243 # search for the exact email which was applied to make this
245 if (my $qry = delete $ctx->{-qry}) {
247 for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
248 # keep blobs as short as reasonable, emails
249 # are going to be older than what's in git
250 substr($_, 7, 64, '');
253 chop $q; # no trailing SP
254 local $Text::Wrap::columns = PublicInbox::View::COLS;
255 local $Text::Wrap::huge = 'overflow';
256 $q = wrap('', '', $q);
257 my $rows = ($q =~ tr/\n/\n/) + 1;
259 my $ibx_url = ibx_url_for($ctx);
261 if (defined $ibx_url) {
262 $alt = " `$ibx_url'";
263 $ibx_url =~ m!://! or
264 substr($ibx_url, 0, 0, '../../../');
265 $ibx_url = ascii_html($ibx_url);
271 <hr><form action="$ibx_url"
272 id=related><pre>find related emails, including ancestors/descendants/conflicts
273 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
274 <input type=submit value="search$alt"
275 />\t(<a href="${ibx_url}_/text/help/">help</a>)</pre></form>
283 id=commit>Commit</dfn> objects reference one tree, and zero or more parents.
286 id=parent>parent</dfn> commits can typically generate a patch in
287 unified diff format via `git format-patch'.
289 Multiple <dfn id=parents>parents</dfn> means the commit is a merge.
291 <dfn id=root_commit>Root commits</dfn> have no ancestor. Note that it is
292 possible to have multiple root commits when merging independent histories.
294 Every commit references one top-level <dfn id=tree>tree</dfn> object.</pre>
296 delete($ctx->{-wcb})->($ctx->html_done($x));
299 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
300 my ($r, $bref, $ctx) = @_;
301 if (!defined $r) { # sysread error
302 html_page($ctx, 500, dbg_log($ctx));
303 } elsif (index($$bref, "\n\n") >= 0) {
304 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
305 my $fn = to_filename($eml->header('Subject') // '');
306 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
307 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
308 'Content-Disposition',
309 qq(inline; filename=$fn.patch) ] ];
311 my $log = dbg_log($ctx);
312 warn "premature EOF on $ctx->{patch_oid} $log";
313 return html_page($ctx, 500, $log);
315 undef; # bref keeps growing until "\n\n"
319 sub show_patch ($$) {
320 my ($ctx, $res) = @_;
321 my ($git, $oid) = @$res;
322 my @cmd = ('git', "--git-dir=$git->{git_dir}",
323 qw(format-patch -1 --stdout -C),
324 "--signature=git format-patch -1 --stdout -C $oid", $oid);
325 my $qsp = PublicInbox::Qspawn->new(\@cmd);
326 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
327 $ctx->{patch_oid} = $oid;
328 $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
331 sub show_commit ($$) {
332 my ($ctx, $res) = @_;
333 return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
334 my ($git, $oid) = @$res;
335 # patch-id needs two passes, and we use the initial show to ensure
336 # a patch embedded inside the commit message body doesn't get fed
338 my $cmd = [ '/bin/sh', '-c',
339 "git show --encoding=UTF-8 '$SHOW_FMT'".
340 " -z --no-notes --no-patch $oid >h && ".
341 'git show --encoding=UTF-8 --pretty=format:%n -M'.
342 " --stat -p $oid >p && ".
343 "git patch-id --stable <p" ];
344 my $e = { GIT_DIR => $git->{git_dir} };
345 my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
346 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
347 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
349 $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
352 sub show_other ($$) { # just in case...
353 my ($ctx, $res) = @_;
354 my ($git, $oid, $type, $size) = @$res;
355 $size > $MAX_SIZE and return html_page($ctx, 200,
356 ascii_html($type)." $oid is too big to show\n". dbg_log($ctx));
357 my $cmd = ['git', "--git-dir=$git->{git_dir}",
358 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
359 my $qsp = PublicInbox::Qspawn->new($cmd);
360 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
361 $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
364 sub show_tree_result ($$) {
365 my ($bref, $ctx) = @_;
366 if (my $qsp_err = delete $ctx->{-qsp_err}) {
367 return html_page($ctx, 500, dbg_log($ctx) .
368 "git ls-tree -z error:$qsp_err");
370 my @ent = split(/\0/, $$bref);
371 my $qp = delete $ctx->{qp};
372 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
373 my $pfx = $ctx->{-path} // $qp->{b}; # {-path} is from RepoTree
374 $$bref = "<pre><a href=#tree>tree</a> $ctx->{tree_oid}";
375 # $REPO/tree/$path already sets {-upfx}
376 my $upfx = $ctx->{-upfx} //= '../../';
379 if (my $t = $ctx->{-obj}) {
380 my $t = ascii_html($t);
382 \n\$ git ls-tree -l $t # shows similar output on the CLI
384 } elsif ($pfx eq '') {
385 $$bref .= " (root)\n";
387 my $x = ascii_html($pfx);
389 $$bref .= qq( <a href=#path>path</a>: $x</a>\n);
393 $$bref .= qq[ (<a href=#path>path</a> unknown)\n];
395 my ($x, $m, $t, $oid, $sz, $f, $n);
396 $$bref .= "\n size name";
398 ($x, $f) = split(/\t/, $_, 2);
400 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
401 $m = $GIT_MODE{$m} // '?';
404 if ($m eq 'g') { # gitlink submodule commit
405 $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
408 my $q = 'b='.ascii_html(uri_escape_path($pfx.$f));
409 if ($m eq 'd') { $n .= '/' }
410 elsif ($m eq 'x') { $n = "<b>$n</b>" }
411 elsif ($m eq 'l') { $n = "<i>$n</i>" }
412 $$bref .= qq(\n$m\t$sz\t<a\nhref="$upfx$oid/s/?$q">$n</a>);
414 $$bref .= dbg_log($ctx);
419 id=tree>Tree</dfn> objects belong to commits or other tree objects. Trees may
420 reference blobs, sub-trees, or commits of submodules.
423 id=path>Path</dfn> names are stored in tree objects, but trees do not know
424 their own path name. A tree's path name comes from their parent tree,
425 or it is the root tree referenced by a commit object. Thus, this web UI
426 relies on the `b=' URI parameter as a hint to display the path name.
428 <dfn title="submodule commit"
429 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
432 html_page($ctx, 200, $$bref);
435 sub show_tree ($$) { # also used by RepoTree
436 my ($ctx, $res) = @_;
437 my ($git, $oid, undef, $size) = @$res;
438 $size > $MAX_SIZE and return html_page($ctx, 200,
439 "tree $oid is too big to show\n". dbg_log($ctx));
440 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
441 qw(ls-tree -z -l --no-abbrev), $oid ];
442 my $qsp = PublicInbox::Qspawn->new($cmd);
443 $ctx->{tree_oid} = $oid;
444 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
445 $qsp->psgi_qx($ctx->{env}, undef, \&show_tree_result, $ctx);
448 # returns seconds offset from git TZ offset
450 my ($tz) = @_; # e.g "-0700"
452 my $mm = $tz < 0 ? -$tz : $tz;
453 $mm = int($mm / 100) * 60 + ($mm % 100);
454 $mm = $tz < 0 ? -$mm : $mm;
458 sub show_tag_result { # git->cat_async callback
459 my ($bref, $oid, $type, $size, $ctx) = @_;
460 utf8::decode($$bref);
461 my $l = PublicInbox::Linkify->new;
462 $$bref = $l->to_html($$bref);
463 $$bref =~ s!^object ([a-f0-9]+)!object <a
464 href=../../$1/s/>$1</a>!;
466 $$bref =~ s/^(tagger .*> )([0-9]+) ([\-+]?[0-9]+)/$1.strftime(
467 '%Y-%m-%d %H:%M:%S', gmtime($2 + tz_adj($3)))." $3"/sme;
468 # TODO: download link
469 html_page($ctx, 200, '<pre>', $$bref, '</pre>', dbg_log($ctx));
473 my ($ctx, $res) = @_;
474 my ($git, $oid) = @$res;
476 if ($ctx->{env}->{'pi-httpd.async'}) {
477 ibx_async_cat($ctx, $oid, \&show_tag_result, $ctx);
478 } else { # synchronous (generic PSGI)
479 $git->cat_async($oid, \&show_tag_result, $ctx);
480 $git->cat_async_wait;
484 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
486 my ($res, $ctx) = @_;
487 my $hints = delete $ctx->{hints};
488 $res or return html_page($ctx, 404, dbg_log($ctx));
489 ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
491 my ($git, $oid, $type, $size, $di) = @$res;
492 return show_commit($ctx, $res) if $type eq 'commit';
493 return show_tree($ctx, $res) if $type eq 'tree';
494 return show_tag($ctx, $res) if $type eq 'tag';
495 return show_other($ctx, $res) if $type ne 'blob';
496 my $paths = $ctx->{-paths} //= do {
497 my $path = to_filename($di->{path_b}//$hints->{path_b}//'blob');
498 my $raw_more = qq[(<a\nhref="$path">raw</a>)];
499 [ $path, $raw_more ];
502 if ($size > $MAX_SIZE) {
503 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
504 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
505 <pre><b>Too big to show, download available</b>
506 blob $oid $size bytes $paths->[1]</pre>
509 bless $ctx, 'PublicInbox::WwwStream'; # for DESTROY
511 if ($ctx->{env}->{'pi-httpd.async'}) {
512 ibx_async_cat($ctx, $oid, \&show_blob, $ctx);
513 } else { # synchronous
514 $git->cat_async($oid, \&show_blob, $ctx);
515 $git->cat_async_wait;
519 sub show_blob { # git->cat_async callback
520 my ($blob, $oid, $type, $size, $ctx) = @_;
522 my $e = "Failed to retrieve generated blob ($oid)";
523 warn "$e ($ctx->{git}->{git_dir}) type=$type";
524 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
527 my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
528 if (defined $ctx->{fn}) {
529 my $h = [ 'Content-Length', $size, 'Content-Type' ];
530 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
531 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
534 my ($path, $raw_more) = @{delete $ctx->{-paths}};
535 $bin and return html_page($ctx, 200,
536 "<pre>blob $oid $size bytes (binary)" .
537 " $raw_more</pre>".dbg_log($ctx));
539 # TODO: detect + convert to ensure validity
540 utf8::decode($$blob);
541 my $nl = ($$blob =~ s/\r?\n/\n/sg);
542 my $pad = length($nl);
544 ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
545 my $ok = $hl->do_hl($blob, $path) if $hl;
549 $$blob = ascii_html($$blob);
552 # using some of the same CSS class names and ids as cgit
553 my $x = "<pre>blob $oid $size bytes $raw_more</pre>" .
554 "<hr /><table\nclass=blob>".
555 "<tr><td\nclass=linenumbers><pre>";
556 # scratchpad in this loop is faster here than `printf $zfh':
557 $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
558 $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
559 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
560 html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
561 '</code></pre></td></tr></table>'.dbg_log($ctx));
564 # GET /$INBOX/$GIT_OBJECT_ID/s/
565 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
567 my ($ctx, $oid_b, $fn) = @_;
569 my $hints = $ctx->{hints} = {};
570 while (my ($from, $to) = each %QP_MAP) {
571 defined(my $v = $qp->{$from}) or next;
572 $hints->{$to} = $v if $v ne '';
575 $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
576 open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
577 my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
578 \&solve_result, $ctx);
579 $solver->{gits} //= [ $ctx->{git} ];
580 $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
581 # PSGI server will call this immediately and give us a callback (-wcb)
583 $ctx->{-wcb} = $_[0]; # HTTP write callback
584 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);