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);
30 require PublicInbox::HlMod;
31 PublicInbox::HlMod->new;
34 my %QP_MAP = ( A => 'oid_a', a => 'path_a', b => 'path_b' );
35 our $MAX_SIZE = 1024 * 1024; # TODO: configurable
36 my $BIN_DETECT = 8000; # same as git
37 my $SHOW_FMT = '--pretty=format:'.join('%n', '%P', '%p', '%H', '%T', '%s', '%f',
38 '%an <%ae> %ai', '%cn <%ce> %ci', '%b%x00');
41 '100644' => ' ', # blob
42 '100755' => 'x', # executable blob
43 '040000' => 'd', # tree
44 '120000' => 'l', # symlink
45 '160000' => 'g', # commit (gitlink)
48 sub html_page ($$;@) {
49 my ($ctx, $code) = @_[0, 1];
50 my $wcb = delete $ctx->{-wcb};
51 $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
52 my $res = html_oneshot($ctx, $code, @_[2..$#_]);
53 $wcb ? $wcb->($res) : $res;
58 my $log = delete $ctx->{lh} // die 'BUG: already captured debug log';
59 if (!seek($log, 0, 0)) {
61 return '<pre>debug log seek error</pre>';
63 $log = do { local $/; <$log> } // do {
64 warn "readline(log): $!";
65 return '<pre>debug log read error</pre>';
67 $ctx->{-linkify} //= PublicInbox::Linkify->new;
68 "<hr><pre>debug log:\n\n".
69 $ctx->{-linkify}->to_html($log).'</pre>';
72 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
73 my ($r, $bref, $ctx) = @_;
74 my ($git, $oid, $type, $size, $di) = @{$ctx->{-res}};
75 my @cl = ('Content-Length', $size);
76 if (!defined $r) { # sysread error
77 html_page($ctx, 500, dbg_log($ctx));
78 } elsif (index($$bref, "\0") >= 0) {
79 [200, [qw(Content-Type application/octet-stream), @cl] ];
81 my $n = length($$bref);
82 if ($n >= $BIN_DETECT || $n == $size) {
83 return [200, [ 'Content-Type',
84 'text/plain; charset=UTF-8', @cl ] ];
87 my $log = dbg_log($ctx);
88 warn "premature EOF on $oid $log";
89 return html_page($ctx, 500, $log);
91 undef; # bref keeps growing
95 sub stream_large_blob ($$) {
98 my ($git, $oid, $type, $size, $di) = @$res;
99 my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
100 my $qsp = PublicInbox::Qspawn->new($cmd);
101 my $env = $ctx->{env};
102 $env->{'qspawn.wcb'} = delete $ctx->{-wcb};
103 $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
106 sub show_other_result ($$) { # tag
107 my ($bref, $ctx) = @_;
108 if (my $qsp_err = delete $ctx->{-qsp_err}) {
109 return html_page($ctx, 500, dbg_log($ctx) .
110 "git show error:$qsp_err");
112 my $l = PublicInbox::Linkify->new;
113 utf8::decode($$bref);
114 html_page($ctx, 200, '<pre>', $l->to_html($$bref), '</pre><hr>',
118 sub cmt_title { # git->cat_async callback
119 my ($bref, $oid, $type, $size, $ctx) = @_;
120 utf8::decode($$bref);
121 my $title = $$bref =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/ ? $1 : '';
122 push(@{$ctx->{-cmt_pt}} , ascii_html($title)) == @{$ctx->{-cmt_P}} and
126 sub show_commit_start { # ->psgi_qx callback
127 my ($bref, $ctx) = @_;
128 if (my $qsp_err = delete $ctx->{-qsp_err}) {
129 return html_page($ctx, 500, dbg_log($ctx) .
130 "git show/patch-id error:$qsp_err");
132 my $patchid = (split(/ /, $$bref))[0]; # ignore commit
133 $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
134 open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
135 die "open $ctx->{-tmp}/h: $!";
136 chop(my $buf = do { local $/ = "\0"; <$fh> });
139 ($P, $p, @{$ctx->{cmt_info}}) = split(/\n/, $buf, 9);
140 return cmt_finalize($ctx) if !$P;
141 @{$ctx->{-cmt_P}} = split(/ /, $P);
142 @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
143 if ($ctx->{env}->{'pi-httpd.async'}) {
144 for (@{$ctx->{-cmt_P}}) {
145 ibx_async_cat($ctx, $_, \&cmt_title, $ctx);
147 } else { # synchronous
148 for (@{$ctx->{-cmt_P}}) {
149 $ctx->{git}->cat_async($_, \&cmt_title, $ctx);
151 $ctx->{git}->cat_async_wait;
157 $ctx->{ibx} and return; # just fall back to $upfx
158 $ctx->{git} or return; # /$CODEREPO/$OID/s/ to (eidx|ibx)
159 if (my $ALL = $ctx->{www}->{pi_cfg}->ALL) {
160 $ALL->base_url // $ALL->base_url($ctx->{env});
161 } elsif (my $ibxs = $ctx->{git}->{-ibxs}) {
162 for my $ibx (@$ibxs) {
164 return defined($ibx->{url}) ?
165 prurl($ctx->{env}, $ibx->{url}) :
166 "../../../$ibx->{name}/";
176 $ctx->{-linkify} //= PublicInbox::Linkify->new;
177 my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
178 my ($H, $T, $s, $f, $au, $co, $bdy) = @{delete $ctx->{cmt_info}};
179 # try to keep author and committer dates lined up
180 my $x = length($au) - length($co);
188 $_ = ascii_html($_) for ($au, $co);
189 $au =~ s!(> +)([0-9]{4,}-\S+ \S+)!
190 my ($gt, $t) = ($1, $2);
194 title="list contemporary emails">$2</a>)
196 $ctx->{-title_html} = $s = $ctx->{-linkify}->to_html($s);
197 my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
198 $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
201 href="$f.patch">patch</a>)\n <a href=#parent>parent</a> $P->[0]};
203 $x = qq(\n <a href=#parents>parents</a> $P->[0]\n);
205 $x .= qq( $_\n) for @$P;
208 $x = ' (<a href=#root_commit>root commit</a>)';
210 PublicInbox::WwwStream::html_init($ctx);
213 <pre> <a href=#commit>commit</a> $H$x
214 <a href=#tree>tree</a> <a href="$upfx$T/s/">$T</a>
220 print $zfh "\n", $ctx->{-linkify}->to_html($bdy) if length($bdy);
222 open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
223 die "open $ctx->{-tmp}/p: $!";
224 if (-s $fh > $MAX_SIZE) {
225 print $zfh "---\n patch is too large to show\n";
226 } else { # prepare flush_diff:
228 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
230 $ctx->{-anchors} = {} if $x =~ /^diff --git /sm;
231 flush_diff($ctx, \$x); # undefs $x
232 # TODO: should there be another textarea which attempts to
233 # search for the exact email which was applied to make this
235 if (my $qry = delete $ctx->{-qry}) {
237 for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
238 # keep blobs as short as reasonable, emails
239 # are going to be older than what's in git
240 substr($_, 7, 64, '');
243 chop $q; # no trailing SP
244 local $Text::Wrap::columns = PublicInbox::View::COLS;
245 local $Text::Wrap::huge = 'overflow';
246 $q = wrap('', '', $q);
247 my $rows = ($q =~ tr/\n/\n/) + 1;
249 my $ibx_url = ibx_url_for($ctx);
250 my $alt = $ibx_url ? ' '.ascii_html($ibx_url) : '';
251 $ibx_url = ascii_html($ibx_url) if defined $ibx_url;
254 <hr><form action="$ibx_url"
255 id=related><pre>find related emails, including ancestors/descendants/conflicts
256 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
257 <input type=submit value="search$alt"
258 />\t(<a href="${ibx_url}_/text/help/">help</a>)</pre></form>
266 id=commit>Commit</dfn> objects reference one tree, and zero or more parents.
269 id=parent>parent</dfn> commits can typically generate a patch in
270 unified diff format via `git format-patch'.
272 Multiple <dfn id=parents>parents</dfn> means the commit is a merge.
274 <dfn id=root_commit>Root commits</dfn> have no ancestor. Note that it is
275 possible to have multiple root commits when merging independent histories.
277 Every commit references one top-level <dfn id=tree>tree</dfn> object.</pre>
279 delete($ctx->{env}->{'qspawn.wcb'})->($ctx->html_done($x));
282 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
283 my ($r, $bref, $ctx) = @_;
284 if (!defined $r) { # sysread error
285 html_page($ctx, 500, dbg_log($ctx));
286 } elsif (index($$bref, "\n\n") >= 0) {
287 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
288 my $fn = to_filename($eml->header('Subject') // '');
289 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
290 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
291 'Content-Disposition',
292 qq(inline; filename=$fn.patch) ] ];
294 my $log = dbg_log($ctx);
295 warn "premature EOF on $ctx->{patch_oid} $log";
296 return html_page($ctx, 500, $log);
298 undef; # bref keeps growing until "\n\n"
302 sub show_patch ($$) {
303 my ($ctx, $res) = @_;
304 my ($git, $oid) = @$res;
305 my @cmd = ('git', "--git-dir=$git->{git_dir}",
306 qw(format-patch -1 --stdout -C),
307 "--signature=git format-patch -1 --stdout -C $oid", $oid);
308 my $qsp = PublicInbox::Qspawn->new(\@cmd);
309 $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
310 $ctx->{patch_oid} = $oid;
311 $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
314 sub show_commit ($$) {
315 my ($ctx, $res) = @_;
316 return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
317 my ($git, $oid) = @$res;
318 # patch-id needs two passes, and we use the initial show to ensure
319 # a patch embedded inside the commit message body doesn't get fed
321 my $cmd = [ '/bin/sh', '-c',
322 "git show --encoding=UTF-8 '$SHOW_FMT'".
323 " -z --no-notes --no-patch $oid >h && ".
324 'git show --encoding=UTF-8 --pretty=format:%n -M'.
325 " --stat -p $oid >p && ".
326 "git patch-id --stable <p" ];
327 my $e = { GIT_DIR => $git->{git_dir} };
328 my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
329 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
330 $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
332 $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
335 sub show_other ($$) {
336 my ($ctx, $res) = @_;
337 my ($git, $oid, $type, $size) = @$res;
338 $size > $MAX_SIZE and return html_page($ctx, 200,
339 ascii_html($type)." $oid is too big to show\n". dbg_log($ctx));
340 my $cmd = ['git', "--git-dir=$git->{git_dir}",
341 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
342 my $qsp = PublicInbox::Qspawn->new($cmd);
343 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
344 $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
347 sub show_tree_result ($$) {
348 my ($bref, $ctx) = @_;
349 if (my $qsp_err = delete $ctx->{-qsp_err}) {
350 return html_page($ctx, 500, dbg_log($ctx) .
351 "git ls-tree -z error:$qsp_err");
353 my @ent = split(/\0/, $$bref);
354 my $qp = delete $ctx->{qp};
355 my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
357 $$bref = "<pre><a href=#tree>tree</a> $ctx->{tree_oid}";
359 my $x = ascii_html($pfx);
361 $$bref .= qq( <a href=#path>path</a>: $x</a>\n);
364 $$bref .= qq[ (<a href=#path>path</a> unknown)\n];
366 my ($x, $m, $t, $oid, $sz, $f, $n);
367 $$bref .= "\n size name";
369 ($x, $f) = split(/\t/, $_, 2);
371 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
372 $m = $GIT_MODE{$m} // '?';
375 if ($m eq 'g') { # gitlink submodule commit
376 $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
379 my $q = 'b='.ascii_html(uri_escape_path($pfx.$f));
380 if ($m eq 'd') { $n .= '/' }
381 elsif ($m eq 'x') { $n = "<b>$n</b>" }
382 elsif ($m eq 'l') { $n = "<i>$n</i>" }
383 $$bref .= qq(\n$m\t$sz\t<a\nhref="../../$oid/s/?$q">$n</a>);
385 $$bref .= dbg_log($ctx);
390 id=tree>Tree</dfn> objects belong to commits or other tree objects. Trees may
391 reference blobs, sub-trees, or commits of submodules.
394 id=path>Path</dfn> names are stored in tree objects, but trees do not know
395 their own path name. A tree's path name comes from their parent tree,
396 or it is the root tree referenced by a commit object. Thus, this web UI
397 relies on the `b=' URI parameter as a hint to display the path name.
399 <dfn title="submodule commit"
400 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
403 html_page($ctx, 200, $$bref);
407 my ($ctx, $res) = @_;
408 my ($git, $oid, undef, $size) = @$res;
409 $size > $MAX_SIZE and return html_page($ctx, 200,
410 "tree $oid is too big to show\n". dbg_log($ctx));
411 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
412 qw(ls-tree -z -l --no-abbrev), $oid ];
413 my $qsp = PublicInbox::Qspawn->new($cmd);
414 $ctx->{tree_oid} = $oid;
415 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
416 $qsp->psgi_qx($ctx->{env}, undef, \&show_tree_result, $ctx);
419 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
421 my ($res, $ctx) = @_;
422 my $hints = delete $ctx->{hints};
423 $res or return html_page($ctx, 404, dbg_log($ctx));
424 ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
426 my ($git, $oid, $type, $size, $di) = @$res;
427 return show_commit($ctx, $res) if $type eq 'commit';
428 return show_tree($ctx, $res) if $type eq 'tree';
429 return show_other($ctx, $res) if $type ne 'blob';
430 my $path = to_filename($di->{path_b} // $hints->{path_b} // 'blob');
431 my $raw_link = "(<a\nhref=$path>raw</a>)";
432 if ($size > $MAX_SIZE) {
433 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
434 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
435 <pre><b>Too big to show, download available</b>
436 blob $oid $size bytes $raw_link</pre>
439 @{$ctx->{-paths}} = ($path, $raw_link);
440 bless $ctx, 'PublicInbox::WwwStream'; # for DESTROY
442 if ($ctx->{env}->{'pi-httpd.async'}) {
443 ibx_async_cat($ctx, $oid, \&show_blob, $ctx);
444 } else { # synchronous
445 $git->cat_async($oid, \&show_blob, $ctx);
446 $git->cat_async_wait;
450 sub show_blob { # git->cat_async callback
451 my ($blob, $oid, $type, $size, $ctx) = @_;
453 my $e = "Failed to retrieve generated blob ($oid)";
454 warn "$e ($ctx->{git}->{git_dir}) type=$type";
455 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
458 my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
459 if (defined $ctx->{fn}) {
460 my $h = [ 'Content-Length', $size, 'Content-Type' ];
461 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
462 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
465 my ($path, $raw_link) = @{delete $ctx->{-paths}};
466 $bin and return html_page($ctx, 200,
467 "<pre>blob $oid $size bytes (binary)" .
468 " $raw_link</pre>".dbg_log($ctx));
470 # TODO: detect + convert to ensure validity
471 utf8::decode($$blob);
472 my $nl = ($$blob =~ s/\r?\n/\n/sg);
473 my $pad = length($nl);
475 ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
476 my $ok = $hl->do_hl($blob, $path) if $hl;
480 $$blob = ascii_html($$blob);
483 # using some of the same CSS class names and ids as cgit
484 my $x = "<pre>blob $oid $size bytes $raw_link</pre>" .
485 "<hr /><table\nclass=blob>".
486 "<tr><td\nclass=linenumbers><pre>";
487 # scratchpad in this loop is faster here than `printf $zfh':
488 $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
489 $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
490 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
491 html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
492 '</code></pre></td></tr></table>'.dbg_log($ctx));
495 # GET /$INBOX/$GIT_OBJECT_ID/s/
496 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
498 my ($ctx, $oid_b, $fn) = @_;
500 my $hints = $ctx->{hints} = {};
501 while (my ($from, $to) = each %QP_MAP) {
502 defined(my $v = $qp->{$from}) or next;
503 $hints->{$to} = $v if $v ne '';
506 $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
507 open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
508 my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
509 \&solve_result, $ctx);
510 $solver->{gits} //= [ $ctx->{git} ];
511 $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
512 # PSGI server will call this immediately and give us a callback (-wcb)
514 $ctx->{-wcb} = $_[0]; # HTTP write callback
515 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);