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);
25 use PublicInbox::View;
27 use Text::Wrap qw(wrap);
28 use PublicInbox::Hval qw(ascii_html to_filename);
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');
40 sub html_page ($$;@) {
41 my ($ctx, $code) = @_[0, 1];
42 my $wcb = delete $ctx->{-wcb};
43 $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
44 my $res = html_oneshot($ctx, $code, @_[2..$#_]);
45 $wcb ? $wcb->($res) : $res;
50 my $log = delete $ctx->{lh} // die 'BUG: already captured debug log';
51 if (!seek($log, 0, 0)) {
53 return '<pre>debug log seek error</pre>';
55 $log = do { local $/; <$log> } // do {
56 warn "readline(log): $!";
57 return '<pre>debug log read error</pre>';
59 $ctx->{-linkify} //= PublicInbox::Linkify->new;
60 '<pre>debug log:</pre><hr /><pre>'.
61 $ctx->{-linkify}->to_html($log).'</pre>';
64 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
65 my ($r, $bref, $ctx) = @_;
66 my ($git, $oid, $type, $size, $di) = @{$ctx->{-res}};
67 my @cl = ('Content-Length', $size);
68 if (!defined $r) { # sysread error
69 html_page($ctx, 500, dbg_log($ctx));
70 } elsif (index($$bref, "\0") >= 0) {
71 [200, [qw(Content-Type application/octet-stream), @cl] ];
73 my $n = length($$bref);
74 if ($n >= $BIN_DETECT || $n == $size) {
75 return [200, [ 'Content-Type',
76 'text/plain; charset=UTF-8', @cl ] ];
79 my $log = dbg_log($ctx);
80 warn "premature EOF on $oid $log";
81 return html_page($ctx, 500, $log);
83 undef; # bref keeps growing
87 sub stream_large_blob ($$) {
90 my ($git, $oid, $type, $size, $di) = @$res;
91 my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
92 my $qsp = PublicInbox::Qspawn->new($cmd);
93 my $env = $ctx->{env};
94 $env->{'qspawn.wcb'} = delete $ctx->{-wcb};
95 $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
98 sub show_other_result ($$) { # tag, tree, ...
99 my ($bref, $ctx) = @_;
100 if (my $qsp_err = delete $ctx->{-qsp_err}) {
101 return html_page($ctx, 500, dbg_log($ctx) .
102 "git show error:$qsp_err");
104 my $l = PublicInbox::Linkify->new;
105 utf8::decode($$bref);
106 html_page($ctx, 200, '<pre>', $l->to_html($$bref), '</pre><hr>',
110 sub cmt_title { # git->cat_async callback
111 my ($bref, $oid, $type, $size, $ctx) = @_;
112 utf8::decode($$bref);
113 my $title = $$bref =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/ ? $1 : '';
114 push(@{$ctx->{-cmt_pt}} , ascii_html($title)) == @{$ctx->{-cmt_P}} and
118 sub show_commit_start { # ->psgi_qx callback
119 my ($bref, $ctx) = @_;
120 if (my $qsp_err = delete $ctx->{-qsp_err}) {
121 return html_page($ctx, 500, dbg_log($ctx) .
122 "git show/patch-id error:$qsp_err");
124 my $patchid = (split(/ /, $$bref))[0]; # ignore commit
125 $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
126 open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
127 die "open $ctx->{-tmp}/h: $!";
128 chop(my $buf = do { local $/ = "\0"; <$fh> });
131 ($P, $p, @$ctx{qw(cmt_H cmt_T cmt_s cmt_f cmt_au cmt_co cmt_b)})
132 = split(/\n/, $buf, 9);
133 return cmt_finalize($ctx) if !$P;
134 @{$ctx->{-cmt_P}} = split(/ /, $P);
135 @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
136 if ($ctx->{env}->{'pi-httpd.async'}) {
137 for (@{$ctx->{-cmt_P}}) {
138 ibx_async_cat($ctx, $_, \&cmt_title, $ctx);
140 } else { # synchronous
141 for (@{$ctx->{-cmt_P}}) {
142 $ctx->{git}->cat_async($_, \&cmt_title, $ctx);
144 $ctx->{git}->cat_async_wait;
150 $ctx->{-linkify} //= PublicInbox::Linkify->new;
151 my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
152 # try to keep author and committer dates lined up
153 my ($au, $co) = delete @$ctx{qw(cmt_au cmt_co)};
154 my $x = length($au) - length($co);
162 $_ = ascii_html($_) for ($au, $co);
163 $au =~ s!(> +)([0-9]{4,}-\S+ \S+)!
164 my ($gt, $t) = ($1, $2);
168 title="list contemporary emails">$2</a>)
170 my $s = $ctx->{-linkify}->to_html(delete $ctx->{cmt_s});
171 $ctx->{-title_html} = $s;
172 my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
173 $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
176 href="$ctx->{cmt_f}.patch">patch</a>)\n parent $P->[0]};
178 $x = qq(\n parents $P->[0]\n);
180 $x .= qq( $_\n) for @$P;
183 $x = ' (root commit)';
185 PublicInbox::WwwStream::html_init($ctx);
187 <pre> commit $ctx->{cmt_H}$x
188 tree <a href="$upfx$ctx->{cmt_T}/s/">$ctx->{cmt_T}</a>
194 $x = delete $ctx->{cmt_b};
195 $ctx->zmore("\n", $ctx->{-linkify}->to_html($x)) if length($x);
197 open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
198 die "open $ctx->{-tmp}/p: $!";
199 if (-s $fh > $MAX_SIZE) {
200 $ctx->zmore("---\n patch is too large to show\n");
201 } else { # prepare flush_diff:
203 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
204 read($fh, my $bdy, -s _);
205 $bdy =~ s/\r?\n/\n/gs;
206 $ctx->{-anchors} = {} if $bdy =~ /^diff --git /sm;
207 flush_diff($ctx, \$bdy); # undefs $bdy
210 # TODO: should there be another textarea which attempts to
211 # search for the exact email which was applied to make this
213 if (my $qry = delete $ctx->{-qry}) {
215 for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
216 # keep blobs as short as reasonable, emails
217 # are going to be older than what's in git
218 substr($_, 7, 64, '');
221 chop $q; # no trailing SP
222 local $Text::Wrap::columns = PublicInbox::View::COLS;
223 local $Text::Wrap::huge = 'overflow';
224 $q = wrap('', '', $q);
225 my $rows = ($q =~ tr/\n/\n/) + 1;
228 <hr><form action=$upfx
229 id=related><pre>find related emails, including ancestors/descendants/conflicts
230 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
231 <input type=submit value=search
232 />\t(<a href=${upfx}_/text/help/>help</a>)</pre></form>
236 $x = $ctx->zflush($ctx->_html_end);
237 my $res_hdr = delete $ctx->{-res_hdr};
238 push @$res_hdr, 'Content-Length', length($x);
239 delete($ctx->{env}->{'qspawn.wcb'})->([200, $res_hdr, [$x]]);
242 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
243 my ($r, $bref, $ctx) = @_;
244 if (!defined $r) { # sysread error
245 html_page($ctx, 500, dbg_log($ctx));
246 } elsif (index($$bref, "\n\n") >= 0) {
247 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
248 my $fn = to_filename($eml->header('Subject') // '');
249 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
250 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
251 'Content-Disposition',
252 qq(inline; filename=$fn.patch) ] ];
254 my $log = dbg_log($ctx);
255 warn "premature EOF on $ctx->{patch_oid} $log";
256 return html_page($ctx, 500, $log);
258 undef; # bref keeps growing until "\n\n"
262 sub show_patch ($$) {
263 my ($ctx, $res) = @_;
264 my ($git, $oid) = @$res;
265 my @cmd = ('git', "--git-dir=$git->{git_dir}",
266 qw(format-patch -1 --stdout -C),
267 "--signature=git format-patch -1 --stdout -C $oid", $oid);
268 my $qsp = PublicInbox::Qspawn->new(\@cmd);
269 $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
270 $ctx->{patch_oid} = $oid;
271 $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
274 sub show_commit ($$) {
275 my ($ctx, $res) = @_;
276 return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
277 my ($git, $oid) = @$res;
278 # patch-id needs two passes, and we use the initial show to ensure
279 # a patch embedded inside the commit message body doesn't get fed
281 my $cmd = [ '/bin/sh', '-c',
282 "git show --encoding=UTF-8 '$SHOW_FMT'".
283 " -z --no-notes --no-patch $oid >h && ".
284 'git show --encoding=UTF-8 --pretty=format:%n -M'.
285 " --stat -p $oid >p && ".
286 "git patch-id --stable <p" ];
287 my $e = { GIT_DIR => $git->{git_dir} };
288 my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
289 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
290 $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
292 $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
295 sub show_other ($$) {
296 my ($ctx, $res) = @_;
297 my ($git, $oid, $type, $size) = @$res;
298 $size > $MAX_SIZE and return html_page($ctx, 200,
299 "$oid is too big to show\n". dbg_log($ctx));
300 my $cmd = ['git', "--git-dir=$git->{git_dir}",
301 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
302 my $qsp = PublicInbox::Qspawn->new($cmd);
303 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
304 $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
307 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
309 my ($res, $ctx) = @_;
310 my $hints = delete $ctx->{hints};
311 $res or return html_page($ctx, 404, dbg_log($ctx));
312 ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
314 my ($git, $oid, $type, $size, $di) = @$res;
315 return show_commit($ctx, $res) if $type eq 'commit';
316 return show_other($ctx, $res) if $type ne 'blob';
317 my $path = to_filename($di->{path_b} // $hints->{path_b} // 'blob');
318 my $raw_link = "(<a\nhref=$path>raw</a>)";
319 if ($size > $MAX_SIZE) {
320 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
321 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
322 <pre><b>Too big to show, download available</b>
323 "$oid $type $size bytes $raw_link</pre>
327 my $blob = $git->cat_file($oid);
329 my $e = "Failed to retrieve generated blob ($oid)";
330 warn "$e ($git->{git_dir})";
331 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
334 my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
335 if (defined $ctx->{fn}) {
336 my $h = [ 'Content-Length', $size, 'Content-Type' ];
337 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
338 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
341 $bin and return html_page($ctx, 200,
342 "<pre>$oid $type $size bytes (binary)" .
343 " $raw_link</pre>".dbg_log($ctx));
345 # TODO: detect + convert to ensure validity
346 utf8::decode($$blob);
347 my $nl = ($$blob =~ s/\r?\n/\n/sg);
348 my $pad = length($nl);
350 ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
351 my $ok = $hl->do_hl($blob, $path) if $hl;
355 $$blob = ascii_html($$blob);
358 my $x = "<pre>$oid $type $size bytes $raw_link</pre>" .
359 "<hr /><table\nclass=blob>".
360 "<tr><td\nclass=linenumbers><pre>";
361 $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
362 $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
363 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
365 # using some of the same CSS class names and ids as cgit
366 html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
367 '</code></pre></td></tr></table>'.dbg_log($ctx));
370 # GET /$INBOX/$GIT_OBJECT_ID/s/
371 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
373 my ($ctx, $oid_b, $fn) = @_;
375 my $hints = $ctx->{hints} = {};
376 while (my ($from, $to) = each %QP_MAP) {
377 defined(my $v = $qp->{$from}) or next;
378 $hints->{$to} = $v if $v ne '';
381 $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
382 open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
383 my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
384 \&solve_result, $ctx);
385 $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
386 # PSGI server will call this immediately and give us a callback (-wcb)
388 $ctx->{-wcb} = $_[0]; # HTTP write callback
389 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);