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 $ctx->{-linkify} //= PublicInbox::Linkify->new;
69 "<hr><pre>debug log:\n\n".
70 $ctx->{-linkify}->to_html($log).'</pre>';
73 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
74 my ($r, $bref, $ctx) = @_;
75 my ($git, $oid, $type, $size, $di) = @{$ctx->{-res}};
76 my @cl = ('Content-Length', $size);
77 if (!defined $r) { # sysread error
78 html_page($ctx, 500, dbg_log($ctx));
79 } elsif (index($$bref, "\0") >= 0) {
80 [200, [qw(Content-Type application/octet-stream), @cl] ];
82 my $n = length($$bref);
83 if ($n >= $BIN_DETECT || $n == $size) {
84 return [200, [ 'Content-Type',
85 'text/plain; charset=UTF-8', @cl ] ];
88 my $log = dbg_log($ctx);
89 warn "premature EOF on $oid $log";
90 return html_page($ctx, 500, $log);
92 undef; # bref keeps growing
96 sub stream_large_blob ($$) {
99 my ($git, $oid, $type, $size, $di) = @$res;
100 my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
101 my $qsp = PublicInbox::Qspawn->new($cmd);
102 my $env = $ctx->{env};
103 $env->{'qspawn.wcb'} = $ctx->{-wcb};
104 $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
107 sub show_other_result ($$) { # future-proofing
108 my ($bref, $ctx) = @_;
109 if (my $qsp_err = delete $ctx->{-qsp_err}) {
110 return html_page($ctx, 500, dbg_log($ctx) .
111 "git show error:$qsp_err");
113 my $l = PublicInbox::Linkify->new;
114 utf8::decode($$bref);
115 html_page($ctx, 200, '<pre>', $l->to_html($$bref), '</pre><hr>',
119 sub cmt_title { # git->cat_async callback
120 my ($bref, $oid, $type, $size, $ctx) = @_;
121 utf8::decode($$bref);
122 my $title = $$bref =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/ ? $1 : '';
123 push(@{$ctx->{-cmt_pt}} , ascii_html($title)) == @{$ctx->{-cmt_P}} and
127 sub show_commit_start { # ->psgi_qx callback
128 my ($bref, $ctx) = @_;
129 if (my $qsp_err = delete $ctx->{-qsp_err}) {
130 return html_page($ctx, 500, dbg_log($ctx) .
131 "git show/patch-id error:$qsp_err");
133 my $patchid = (split(/ /, $$bref))[0]; # ignore commit
134 $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
135 open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
136 die "open $ctx->{-tmp}/h: $!";
137 chop(my $buf = do { local $/ = "\0"; <$fh> });
140 ($P, $p, @{$ctx->{cmt_info}}) = 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);
148 } else { # synchronous
149 for (@{$ctx->{-cmt_P}}) {
150 $ctx->{git}->cat_async($_, \&cmt_title, $ctx);
152 $ctx->{git}->cat_async_wait;
158 $ctx->{ibx} and return; # fall back to $upfx
159 $ctx->{git} or die 'BUG: no {git}';
160 if (my $ALL = $ctx->{www}->{pi_cfg}->ALL) {
161 if (defined(my $u = $ALL->base_url($ctx->{env}))) {
162 return wantarray ? ($u) : $u;
166 if (my $ibx_names = $ctx->{git}->{ibx_names}) {
167 my $by_name = $ctx->{www}->{pi_cfg}->{-by_name};
168 for my $name (@$ibx_names) {
169 my $ibx = $by_name->{$name} // do {
170 warn "inbox `$name' no longer exists\n";
174 my $u = defined($ibx->{url}) ?
175 prurl($ctx->{env}, $ibx->{url}) : $name;
176 $u .= '/' if substr($u, -1) ne '/';
180 wantarray ? (@ret) : $ret[0];
185 $ctx->{-linkify} //= PublicInbox::Linkify->new;
186 my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
187 my ($H, $T, $s, $f, $au, $co, $bdy) = @{delete $ctx->{cmt_info}};
188 # try to keep author and committer dates lined up
189 my $x = length($au) - length($co);
197 $_ = ascii_html($_) for ($au, $co);
198 $au =~ s!(> +)([0-9]{4,}-\S+ \S+)!
199 my ($gt, $t) = ($1, $2);
203 title="list contemporary emails">$2</a>)
205 $ctx->{-title_html} = $s = $ctx->{-linkify}->to_html($s);
206 my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
207 $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
210 href="$f.patch">patch</a>)\n <a href=#parent>parent</a> $P->[0]};
212 $x = qq(\n <a href=#parents>parents</a> $P->[0]\n);
214 $x .= qq( $_\n) for @$P;
217 $x = ' (<a href=#root_commit>root commit</a>)';
219 PublicInbox::WwwStream::html_init($ctx);
222 <pre> <a href=#commit>commit</a> $H$x
223 <a href=#tree>tree</a> <a href="$upfx$T/s/?b=">$T</a>
229 print $zfh "\n", $ctx->{-linkify}->to_html($bdy) if length($bdy);
231 open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
232 die "open $ctx->{-tmp}/p: $!";
233 if (-s $fh > $MAX_SIZE) {
234 print $zfh "---\n patch is too large to show\n";
235 } else { # prepare flush_diff:
237 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
239 $ctx->{-anchors} = {} if $x =~ /^diff --git /sm;
240 flush_diff($ctx, \$x); # undefs $x
241 # TODO: should there be another textarea which attempts to
242 # search for the exact email which was applied to make this
244 if (my $qry = delete $ctx->{-qry}) {
246 for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
247 # keep blobs as short as reasonable, emails
248 # are going to be older than what's in git
249 substr($_, 7, 64, '');
252 chop $q; # no trailing SP
253 local $Text::Wrap::columns = PublicInbox::View::COLS;
254 local $Text::Wrap::huge = 'overflow';
255 $q = wrap('', '', $q);
256 my $rows = ($q =~ tr/\n/\n/) + 1;
258 my $ibx_url = ibx_url_for($ctx);
260 if (defined $ibx_url) {
261 $alt = " `$ibx_url'";
262 $ibx_url =~ m!://! or
263 substr($ibx_url, 0, 0, '../../../');
264 $ibx_url = ascii_html($ibx_url);
270 <hr><form action="$ibx_url"
271 id=related><pre>find related emails, including ancestors/descendants/conflicts
272 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
273 <input type=submit value="search$alt"
274 />\t(<a href="${ibx_url}_/text/help/">help</a>)</pre></form>
282 id=commit>Commit</dfn> objects reference one tree, and zero or more parents.
285 id=parent>parent</dfn> commits can typically generate a patch in
286 unified diff format via `git format-patch'.
288 Multiple <dfn id=parents>parents</dfn> means the commit is a merge.
290 <dfn id=root_commit>Root commits</dfn> have no ancestor. Note that it is
291 possible to have multiple root commits when merging independent histories.
293 Every commit references one top-level <dfn id=tree>tree</dfn> object.</pre>
295 delete($ctx->{-wcb})->($ctx->html_done($x));
298 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
299 my ($r, $bref, $ctx) = @_;
300 if (!defined $r) { # sysread error
301 html_page($ctx, 500, dbg_log($ctx));
302 } elsif (index($$bref, "\n\n") >= 0) {
303 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
304 my $fn = to_filename($eml->header('Subject') // '');
305 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
306 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
307 'Content-Disposition',
308 qq(inline; filename=$fn.patch) ] ];
310 my $log = dbg_log($ctx);
311 warn "premature EOF on $ctx->{patch_oid} $log";
312 return html_page($ctx, 500, $log);
314 undef; # bref keeps growing until "\n\n"
318 sub show_patch ($$) {
319 my ($ctx, $res) = @_;
320 my ($git, $oid) = @$res;
321 my @cmd = ('git', "--git-dir=$git->{git_dir}",
322 qw(format-patch -1 --stdout -C),
323 "--signature=git format-patch -1 --stdout -C $oid", $oid);
324 my $qsp = PublicInbox::Qspawn->new(\@cmd);
325 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
326 $ctx->{patch_oid} = $oid;
327 $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
330 sub show_commit ($$) {
331 my ($ctx, $res) = @_;
332 return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
333 my ($git, $oid) = @$res;
334 # patch-id needs two passes, and we use the initial show to ensure
335 # a patch embedded inside the commit message body doesn't get fed
337 my $cmd = [ '/bin/sh', '-c',
338 "git show --encoding=UTF-8 '$SHOW_FMT'".
339 " -z --no-notes --no-patch $oid >h && ".
340 'git show --encoding=UTF-8 --pretty=format:%n -M'.
341 " --stat -p $oid >p && ".
342 "git patch-id --stable <p" ];
343 my $e = { GIT_DIR => $git->{git_dir} };
344 my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
345 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
346 $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
348 $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
351 sub show_other ($$) { # just in case...
352 my ($ctx, $res) = @_;
353 my ($git, $oid, $type, $size) = @$res;
354 $size > $MAX_SIZE and return html_page($ctx, 200,
355 ascii_html($type)." $oid is too big to show\n". dbg_log($ctx));
356 my $cmd = ['git', "--git-dir=$git->{git_dir}",
357 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
358 my $qsp = PublicInbox::Qspawn->new($cmd);
359 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
360 $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
363 sub show_tree_result ($$) {
364 my ($bref, $ctx) = @_;
365 if (my $qsp_err = delete $ctx->{-qsp_err}) {
366 return html_page($ctx, 500, dbg_log($ctx) .
367 "git ls-tree -z error:$qsp_err");
369 my @ent = split(/\0/, $$bref);
370 my $qp = delete $ctx->{qp};
371 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
373 $$bref = "<pre><a href=#tree>tree</a> $ctx->{tree_oid}";
376 $$bref .= " (root)\n";
378 my $x = ascii_html($pfx);
380 $$bref .= qq( <a href=#path>path</a>: $x</a>\n);
384 $$bref .= qq[ (<a href=#path>path</a> unknown)\n];
386 my ($x, $m, $t, $oid, $sz, $f, $n);
387 $$bref .= "\n size name";
389 ($x, $f) = split(/\t/, $_, 2);
391 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
392 $m = $GIT_MODE{$m} // '?';
395 if ($m eq 'g') { # gitlink submodule commit
396 $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
399 my $q = 'b='.ascii_html(uri_escape_path($pfx.$f));
400 if ($m eq 'd') { $n .= '/' }
401 elsif ($m eq 'x') { $n = "<b>$n</b>" }
402 elsif ($m eq 'l') { $n = "<i>$n</i>" }
403 $$bref .= qq(\n$m\t$sz\t<a\nhref="../../$oid/s/?$q">$n</a>);
405 $$bref .= dbg_log($ctx);
410 id=tree>Tree</dfn> objects belong to commits or other tree objects. Trees may
411 reference blobs, sub-trees, or commits of submodules.
414 id=path>Path</dfn> names are stored in tree objects, but trees do not know
415 their own path name. A tree's path name comes from their parent tree,
416 or it is the root tree referenced by a commit object. Thus, this web UI
417 relies on the `b=' URI parameter as a hint to display the path name.
419 <dfn title="submodule commit"
420 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
423 html_page($ctx, 200, $$bref);
427 my ($ctx, $res) = @_;
428 my ($git, $oid, undef, $size) = @$res;
429 $size > $MAX_SIZE and return html_page($ctx, 200,
430 "tree $oid is too big to show\n". dbg_log($ctx));
431 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
432 qw(ls-tree -z -l --no-abbrev), $oid ];
433 my $qsp = PublicInbox::Qspawn->new($cmd);
434 $ctx->{tree_oid} = $oid;
435 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
436 $qsp->psgi_qx($ctx->{env}, undef, \&show_tree_result, $ctx);
439 # returns seconds offset from git TZ offset
441 my ($tz) = @_; # e.g "-0700"
443 my $mm = $tz < 0 ? -$tz : $tz;
444 $mm = int($mm / 100) * 60 + ($mm % 100);
445 $mm = $tz < 0 ? -$mm : $mm;
449 sub show_tag_result { # git->cat_async callback
450 my ($bref, $oid, $type, $size, $ctx) = @_;
451 utf8::decode($$bref);
452 my $l = PublicInbox::Linkify->new;
453 $$bref = $l->to_html($$bref);
454 $$bref =~ s!^object ([a-f0-9]+)!object <a
455 href=../../$1/s/>$1</a>!;
457 $$bref =~ s/^(tagger .*> )([0-9]+) ([\-+]?[0-9]+)/$1.strftime(
458 '%Y-%m-%d %H:%M:%S', gmtime($2 + tz_adj($3)))." $3"/sme;
459 # TODO: download link
460 html_page($ctx, 200, '<pre>', $$bref, '</pre>', dbg_log($ctx));
464 my ($ctx, $res) = @_;
465 my ($git, $oid) = @$res;
467 if ($ctx->{env}->{'pi-httpd.async'}) {
468 ibx_async_cat($ctx, $oid, \&show_tag_result, $ctx);
469 } else { # synchronous (generic PSGI)
470 $git->cat_async($oid, \&show_tag_result, $ctx);
471 $git->cat_async_wait;
475 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
477 my ($res, $ctx) = @_;
478 my $hints = delete $ctx->{hints};
479 $res or return html_page($ctx, 404, dbg_log($ctx));
480 ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
482 my ($git, $oid, $type, $size, $di) = @$res;
483 return show_commit($ctx, $res) if $type eq 'commit';
484 return show_tree($ctx, $res) if $type eq 'tree';
485 return show_tag($ctx, $res) if $type eq 'tag';
486 return show_other($ctx, $res) if $type ne 'blob';
487 my $path = to_filename($di->{path_b} // $hints->{path_b} // 'blob');
488 my $raw_link = "(<a\nhref=$path>raw</a>)";
489 if ($size > $MAX_SIZE) {
490 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
491 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
492 <pre><b>Too big to show, download available</b>
493 blob $oid $size bytes $raw_link</pre>
496 @{$ctx->{-paths}} = ($path, $raw_link);
497 bless $ctx, 'PublicInbox::WwwStream'; # for DESTROY
499 if ($ctx->{env}->{'pi-httpd.async'}) {
500 ibx_async_cat($ctx, $oid, \&show_blob, $ctx);
501 } else { # synchronous
502 $git->cat_async($oid, \&show_blob, $ctx);
503 $git->cat_async_wait;
507 sub show_blob { # git->cat_async callback
508 my ($blob, $oid, $type, $size, $ctx) = @_;
510 my $e = "Failed to retrieve generated blob ($oid)";
511 warn "$e ($ctx->{git}->{git_dir}) type=$type";
512 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
515 my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
516 if (defined $ctx->{fn}) {
517 my $h = [ 'Content-Length', $size, 'Content-Type' ];
518 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
519 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
522 my ($path, $raw_link) = @{delete $ctx->{-paths}};
523 $bin and return html_page($ctx, 200,
524 "<pre>blob $oid $size bytes (binary)" .
525 " $raw_link</pre>".dbg_log($ctx));
527 # TODO: detect + convert to ensure validity
528 utf8::decode($$blob);
529 my $nl = ($$blob =~ s/\r?\n/\n/sg);
530 my $pad = length($nl);
532 ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
533 my $ok = $hl->do_hl($blob, $path) if $hl;
537 $$blob = ascii_html($$blob);
540 # using some of the same CSS class names and ids as cgit
541 my $x = "<pre>blob $oid $size bytes $raw_link</pre>" .
542 "<hr /><table\nclass=blob>".
543 "<tr><td\nclass=linenumbers><pre>";
544 # scratchpad in this loop is faster here than `printf $zfh':
545 $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
546 $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
547 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
548 html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
549 '</code></pre></td></tr></table>'.dbg_log($ctx));
552 # GET /$INBOX/$GIT_OBJECT_ID/s/
553 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
555 my ($ctx, $oid_b, $fn) = @_;
557 my $hints = $ctx->{hints} = {};
558 while (my ($from, $to) = each %QP_MAP) {
559 defined(my $v = $qp->{$from}) or next;
560 $hints->{$to} = $v if $v ne '';
563 $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
564 open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
565 my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
566 \&solve_result, $ctx);
567 $solver->{gits} //= [ $ctx->{git} ];
568 $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
569 # PSGI server will call this immediately and give us a callback (-wcb)
571 $ctx->{-wcb} = $_[0]; # HTTP write callback
572 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);