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;
26 use Text::Wrap qw(wrap);
27 use PublicInbox::Hval qw(ascii_html to_filename);
29 require PublicInbox::HlMod;
30 PublicInbox::HlMod->new;
33 my %QP_MAP = ( A => 'oid_a', a => 'path_a', b => 'path_b' );
34 our $MAX_SIZE = 1024 * 1024; # TODO: configurable
35 my $BIN_DETECT = 8000; # same as git
36 my $SHOW_FMT = '--pretty=format:'.join('%n', '%P', '%p', '%H', '%T', '%s',
37 '%an <%ae> %ai', '%cn <%ce> %ci', '%b%x00');
40 my ($ctx, $code, $str) = @_;
41 my $wcb = delete $ctx->{-wcb};
42 $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
43 my $res = html_oneshot($ctx, $code, \$str);
44 $wcb ? $wcb->($res) : $res;
49 my $log = delete $ctx->{lh} // die 'BUG: already captured debug log';
50 if (!seek($log, 0, 0)) {
52 return '<pre>debug log seek error</pre>';
54 $log = do { local $/; <$log> } // do {
55 warn "readline(log): $!";
56 return '<pre>debug log read error</pre>';
58 $ctx->{-linkify} //= PublicInbox::Linkify->new;
59 '<pre>debug log:</pre><hr /><pre>'.
60 $ctx->{-linkify}->to_html($log).'</pre>';
63 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
64 my ($r, $bref, $ctx) = @_;
65 my ($git, $oid, $type, $size, $di) = @{$ctx->{-res}};
66 my @cl = ('Content-Length', $size);
67 if (!defined $r) { # sysread error
68 html_page($ctx, 500, dbg_log($ctx));
69 } elsif (index($$bref, "\0") >= 0) {
70 [200, [qw(Content-Type application/octet-stream), @cl] ];
72 my $n = length($$bref);
73 if ($n >= $BIN_DETECT || $n == $size) {
74 return [200, [ 'Content-Type',
75 'text/plain; charset=UTF-8', @cl ] ];
78 my $log = dbg_log($ctx);
79 warn "premature EOF on $oid $log";
80 return html_page($ctx, 500, $log);
82 undef; # bref keeps growing
86 sub stream_large_blob ($$) {
89 my ($git, $oid, $type, $size, $di) = @$res;
90 my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
91 my $qsp = PublicInbox::Qspawn->new($cmd);
92 my $env = $ctx->{env};
93 $env->{'qspawn.wcb'} = delete $ctx->{-wcb};
94 $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
97 sub show_other_result ($$) { # tag, tree, ...
98 my ($bref, $ctx) = @_;
99 if (my $qsp_err = delete $ctx->{-qsp_err}) {
100 return html_page($ctx, 500, dbg_log($ctx) .
101 "git show error:$qsp_err");
103 my $l = PublicInbox::Linkify->new;
104 utf8::decode($$bref);
105 html_page($ctx, 200, '<pre>', $l->to_html($$bref), '</pre><hr>',
109 sub cmt_title { # git->cat_async callback
110 my ($bref, $oid, $type, $size, $ctx) = @_;
111 utf8::decode($$bref);
112 my $title = $$bref =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/ ? $1 : '';
113 push(@{$ctx->{-cmt_pt}} , ascii_html($title)) == @{$ctx->{-cmt_P}} and
117 sub show_commit_start { # ->psgi_qx callback
118 my ($bref, $ctx) = @_;
119 if (my $qsp_err = delete $ctx->{-qsp_err}) {
120 return html_page($ctx, 500, dbg_log($ctx) .
121 "git show/patch-id error:$qsp_err");
123 my $patchid = (split(/ /, $$bref))[0]; # ignore commit
124 $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
125 open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
126 die "open $ctx->{-tmp}/h: $!";
127 chop(my $buf = do { local $/ = "\0"; <$fh> });
130 ($P, $p, @$ctx{qw(cmt_H cmt_T cmt_s cmt_au cmt_co cmt_b)})
131 = split(/\n/, $buf, 8);
132 return cmt_finalize($ctx) if !$P;
133 @{$ctx->{-cmt_P}} = split(/ /, $P);
134 @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
135 if ($ctx->{env}->{'pi-httpd.async'}) {
136 for (@{$ctx->{-cmt_P}}) {
137 ibx_async_cat($ctx, $_, \&cmt_title, $ctx);
139 } else { # synchronous
140 for (@{$ctx->{-cmt_P}}) {
141 $ctx->{git}->cat_async($_, \&cmt_title, $ctx);
143 $ctx->{git}->cat_async_wait;
149 $ctx->{-linkify} //= PublicInbox::Linkify->new;
150 # try to keep author and committer dates lined up
151 my ($au, $co) = delete @$ctx{qw(cmt_au cmt_co)};
152 my $x = length($au) - length($co);
160 $_ = ascii_html($_) for ($au, $co);
161 my $s = $ctx->{-linkify}->to_html(delete $ctx->{cmt_s});
162 $ctx->{-title_html} = $s;
163 my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
164 my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
165 $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
167 $x = qq(\n parent $P->[0]);
169 $x = qq(\n parents $P->[0]\n);
171 $x .= qq( $_\n) for @$P;
174 $x = ' (root commit)';
176 PublicInbox::WwwStream::html_init($ctx);
178 <pre> commit $ctx->{cmt_H}$x
179 tree <a href="$upfx$ctx->{cmt_T}/s/">$ctx->{cmt_T}</a>
185 $x = delete $ctx->{cmt_b};
186 $ctx->zmore("\n", $ctx->{-linkify}->to_html($x)) if length($x);
188 open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
189 die "open $ctx->{-tmp}/p: $!";
190 if (-s $fh > $MAX_SIZE) {
191 $ctx->zmore("---\n patch is too large to show\n");
192 } else { # prepare flush_diff:
194 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
195 read($fh, my $bdy, -s _);
196 $bdy =~ s/\r?\n/\n/gs;
197 $ctx->{-anchors} = {} if $bdy =~ /^diff --git /sm;
198 flush_diff($ctx, \$bdy); # undefs $bdy
201 # TODO: should there be another textarea which attempts to
202 # search for the exact email which was applied to make this
204 if (my $qry = delete $ctx->{-qry}) {
206 for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
207 # keep blobs as short as reasonable, emails
208 # are going to be older than what's in git
209 substr($_, 7, 64, '');
212 chop $q; # no trailing SP
213 local $Text::Wrap::columns = PublicInbox::View::COLS;
214 local $Text::Wrap::huge = 'overflow';
215 $q = wrap('', '', $q);
216 my $rows = ($q =~ tr/\n/\n/) + 1;
219 <hr><form action=$upfx
220 id=related><pre>find related emails, including ancestors/descendants/conflicts
221 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
222 <input type=submit value=search
223 />\t(<a href=${upfx}_/text/help/>help</a>)</pre></form>
227 $x = $ctx->zflush($ctx->_html_end);
228 my $res_hdr = delete $ctx->{-res_hdr};
229 push @$res_hdr, 'Content-Length', length($x);
230 delete($ctx->{env}->{'qspawn.wcb'})->([200, $res_hdr, [$x]]);
233 sub show_commit ($$) {
234 my ($ctx, $res) = @_;
235 my ($git, $oid) = @$res;
236 # patch-id needs two passes, and we use the initial show to ensure
237 # a patch embedded inside the commit message body doesn't get fed
239 my $cmd = [ '/bin/sh', '-c',
240 "git show --encoding=UTF-8 '$SHOW_FMT'".
241 " -z --no-notes --no-patch $oid >h && ".
242 'git show --encoding=UTF-8 --pretty=format:%n -M'.
243 " --stat -p $oid >p && ".
244 "git patch-id --stable <p" ];
245 my $e = { GIT_DIR => $git->{git_dir} };
246 my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
247 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
248 $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
250 $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
253 sub show_other ($$) {
254 my ($ctx, $res) = @_;
255 my ($git, $oid, $type, $size) = @$res;
256 $size > $MAX_SIZE and return html_page($ctx, 200,
257 "$oid is too big to show\n". dbg_log($ctx));
258 my $cmd = ['git', "--git-dir=$git->{git_dir}",
259 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
260 my $qsp = PublicInbox::Qspawn->new($cmd);
261 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
262 $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
265 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
267 my ($res, $ctx) = @_;
268 my $hints = delete $ctx->{hints};
269 $res or return html_page($ctx, 404, dbg_log($ctx));
270 ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
272 my ($git, $oid, $type, $size, $di) = @$res;
273 return show_commit($ctx, $res) if $type eq 'commit';
274 return show_other($ctx, $res) if $type ne 'blob';
275 my $path = to_filename($di->{path_b} // $hints->{path_b} // 'blob');
276 my $raw_link = "(<a\nhref=$path>raw</a>)";
277 if ($size > $MAX_SIZE) {
278 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
279 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
280 <pre><b>Too big to show, download available</b>
281 "$oid $type $size bytes $raw_link</pre>
285 my $blob = $git->cat_file($oid);
287 my $e = "Failed to retrieve generated blob ($oid)";
288 warn "$e ($git->{git_dir})";
289 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
292 my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
293 if (defined $ctx->{fn}) {
294 my $h = [ 'Content-Length', $size, 'Content-Type' ];
295 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
296 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
299 $bin and return html_page($ctx, 200,
300 "<pre>$oid $type $size bytes (binary)" .
301 " $raw_link</pre>".dbg_log($ctx));
303 # TODO: detect + convert to ensure validity
304 utf8::decode($$blob);
305 my $nl = ($$blob =~ s/\r?\n/\n/sg);
306 my $pad = length($nl);
308 ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
309 my $ok = $hl->do_hl($blob, $path) if $hl;
313 $$blob = ascii_html($$blob);
316 # using some of the same CSS class names and ids as cgit
317 html_page($ctx, 200, "<pre>$oid $type $size bytes $raw_link</pre>" .
318 "<hr /><table\nclass=blob>".
319 "<tr><td\nclass=linenumbers><pre>" . join('', map {
320 sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_)
321 } (1..$nl)) . '</pre></td>' .
322 '<td><pre> </pre></td>'. # pad for non-CSS users
323 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>" .
324 $ctx->{-linkify}->linkify_2($$blob) .
325 '</code></pre></td></tr></table>'.dbg_log($ctx));
328 # GET /$INBOX/$GIT_OBJECT_ID/s/
329 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
331 my ($ctx, $oid_b, $fn) = @_;
333 my $hints = $ctx->{hints} = {};
334 while (my ($from, $to) = each %QP_MAP) {
335 defined(my $v = $qp->{$from}) or next;
336 $hints->{$to} = $v if $v ne '';
339 $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
340 open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
341 my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
342 \&solve_result, $ctx);
343 $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
344 # PSGI server will call this immediately and give us a callback (-wcb)
346 $ctx->{-wcb} = $_[0]; # HTTP write callback
347 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);