]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewVCS.pm
www_coderepo: tree: do not break #n$LINENO
[public-inbox.git] / lib / PublicInbox / ViewVCS.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # show any VCS object, similar to "git show"
5 #
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).
10 #
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).
14
15 package PublicInbox::ViewVCS;
16 use strict;
17 use v5.10.1;
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;
26 use PublicInbox::Eml;
27 use Text::Wrap qw(wrap);
28 use PublicInbox::Hval qw(ascii_html to_filename prurl);
29 use POSIX qw(strftime);
30 my $hl = eval {
31         require PublicInbox::HlMod;
32         PublicInbox::HlMod->new;
33 };
34
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');
40
41 my %GIT_MODE = (
42         '100644' => ' ', # blob
43         '100755' => 'x', # executable blob
44         '040000' => 'd', # tree
45         '120000' => 'l', # symlink
46         '160000' => 'g', # commit (gitlink)
47 );
48
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;
55 }
56
57 sub dbg_log ($) {
58         my ($ctx) = @_;
59         my $log = delete $ctx->{lh} // die 'BUG: already captured debug log';
60         if (!seek($log, 0, 0)) {
61                 warn "seek(log): $!";
62                 return '<pre>debug log seek error</pre>';
63         }
64         $log = do { local $/; <$log> } // do {
65                 warn "readline(log): $!";
66                 return '<pre>debug log read error</pre>';
67         };
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>';
72 }
73
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] ];
82         } else {
83                 my $n = length($$bref);
84                 if ($n >= $BIN_DETECT || $n == $size) {
85                         return [200, [ 'Content-Type',
86                                 'text/plain; charset=UTF-8', @cl ] ];
87                 }
88                 if ($r == 0) {
89                         my $log = dbg_log($ctx);
90                         warn "premature EOF on $oid $log";
91                         return html_page($ctx, 500, $log);
92                 }
93                 undef; # bref keeps growing
94         }
95 }
96
97 sub stream_large_blob ($$) {
98         my ($ctx, $res) = @_;
99         $ctx->{-res} = $res;
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);
106 }
107
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");
113         }
114         my $l = PublicInbox::Linkify->new;
115         utf8::decode($$bref);
116         html_page($ctx, 200, '<pre>', $l->to_html($$bref), '</pre><hr>',
117                 dbg_log($ctx));
118 }
119
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
125                 cmt_finalize($ctx);
126 }
127
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");
133         }
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> });
139         chomp $buf;
140         my ($P, $p);
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);
148                 }
149         } else { # synchronous
150                 for (@{$ctx->{-cmt_P}}) {
151                         $ctx->{git}->cat_async($_, \&cmt_title, $ctx);
152                 }
153                 $ctx->{git}->cat_async_wait;
154         }
155 }
156
157 sub ibx_url_for {
158         my ($ctx) = @_;
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;
164                 }
165         }
166         my @ret;
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";
172                                 next;
173                         };
174                         $ibx->isrch // next;
175                         my $u = defined($ibx->{url}) ?
176                                 prurl($ctx->{env}, $ibx->{url}) : $name;
177                         $u .= '/' if substr($u, -1) ne '/';
178                         push @ret, $u;
179                 }
180         }
181         wantarray ? (@ret) : $ret[0];
182 }
183
184 sub cmt_finalize {
185         my ($ctx) = @_;
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);
191         if ($x > 0) {
192                 $x = ' ' x $x;
193                 $co =~ s/>/>$x/;
194         } elsif ($x < 0) {
195                 $x = ' ' x (-$x);
196                 $au =~ s/>/>$x/;
197         }
198         $_ = ascii_html($_) for ($au, $co);
199         $au =~ s!(&gt; +)([0-9]{4,}-\S+ \S+)!
200                 my ($gt, $t) = ($1, $2);
201                 $t =~ tr/ :-//d;
202                 qq($gt<a
203 href="$upfx?t=$t"
204 title="list contemporary emails">$2</a>)
205                 !e;
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;
209         if (@$P == 1) {
210                 $x = qq{ (<a
211 href="$f.patch">patch</a>)\n   <a href=#parent>parent</a> $P->[0]};
212         } elsif (@$P > 1) {
213                 $x = qq(\n  <a href=#parents>parents</a> $P->[0]\n);
214                 shift @$P;
215                 $x .= qq(          $_\n) for @$P;
216                 chop $x;
217         } else {
218                 $x = ' (<a href=#root_commit>root commit</a>)';
219         }
220         PublicInbox::WwwStream::html_init($ctx);
221         my $zfh = $ctx->zfh;
222         print $zfh <<EOM;
223 <pre>   <a href=#commit>commit</a> $H$x
224      <a href=#tree>tree</a> <a href="$upfx$T/s/?b=">$T</a>
225    author $au
226 committer $co
227
228 <b>$s</b>
229 EOM
230         print $zfh "\n", $ctx->{-linkify}->to_html($bdy) if length($bdy);
231         $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:
237                 read($fh, $x, -s _);
238                 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
239                 $x =~ s/\r?\n/\n/gs;
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
244                 # commit?
245                 if (my $qry = delete $ctx->{-qry}) {
246                         my $q = '';
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, '');
251                                 $q .= "dfblob:$_ ";
252                         }
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;
258                         $q = ascii_html($q);
259                         my $ibx_url = ibx_url_for($ctx);
260                         my $alt;
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);
266                         } else {
267                                 $ibx_url = $upfx;
268                                 $alt = '';
269                         }
270                         print $zfh <<EOM;
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>
276 EOM
277                 }
278         }
279         chop($x = <<EOM);
280 <hr><pre>glossary
281 --------
282 <dfn
283 id=commit>Commit</dfn> objects reference one tree, and zero or more parents.
284
285 Single <dfn
286 id=parent>parent</dfn> commits can typically generate a patch in
287 unified diff format via `git format-patch'.
288
289 Multiple <dfn id=parents>parents</dfn> means the commit is a merge.
290
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.
293
294 Every commit references one top-level <dfn id=tree>tree</dfn> object.</pre>
295 EOM
296         delete($ctx->{-wcb})->($ctx->html_done($x));
297 }
298
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) ] ];
310         } elsif ($r == 0) {
311                 my $log = dbg_log($ctx);
312                 warn "premature EOF on $ctx->{patch_oid} $log";
313                 return html_page($ctx, 500, $log);
314         } else {
315                 undef; # bref keeps growing until "\n\n"
316         }
317 }
318
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);
329 }
330
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
337         # to patch-id:
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};
348         $ctx->{git} = $git;
349         $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
350 }
351
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);
362 }
363
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");
369         }
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} //= '../../';
377         if (defined $pfx) {
378                 $pfx =~ s!/+\z!!s;
379                 if (my $t = $ctx->{-obj}) {
380                         my $t = ascii_html($t);
381                         $$bref .= <<EOM
382 \n\$ git ls-tree -l $t  # shows similar output on the CLI
383 EOM
384                 } elsif ($pfx eq '') {
385                         $$bref .= "  (root)\n";
386                 } else {
387                         my $x = ascii_html($pfx);
388                         $pfx .= '/';
389                         $$bref .= qq(  <a href=#path>path</a>: $x</a>\n);
390                 }
391         } else {
392                 $pfx = '';
393                 $$bref .= qq[  (<a href=#path>path</a> unknown)\n];
394         }
395         my ($x, $m, $t, $oid, $sz, $f, $n);
396         $$bref .= "\n   size    name";
397         for (@ent) {
398                 ($x, $f) = split(/\t/, $_, 2);
399                 undef $_;
400                 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
401                 $m = $GIT_MODE{$m} // '?';
402                 utf8::decode($f);
403                 $n = ascii_html($f);
404                 if ($m eq 'g') { # gitlink submodule commit
405                         $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
406                         next;
407                 }
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>);
413         }
414         $$bref .= dbg_log($ctx);
415         $$bref .= <<EOM;
416 <pre>glossary
417 --------
418 <dfn
419 id=tree>Tree</dfn> objects belong to commits or other tree objects.  Trees may
420 reference blobs, sub-trees, or commits of submodules.
421
422 <dfn
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.
427
428 <dfn title="submodule commit"
429 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
430 EOM
431         chop $$bref;
432         html_page($ctx, 200, $$bref);
433 }
434
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);
446 }
447
448 # returns seconds offset from git TZ offset
449 sub tz_adj ($) {
450         my ($tz) = @_; # e.g "-0700"
451         $tz = int($tz);
452         my $mm = $tz < 0 ? -$tz : $tz;
453         $mm = int($mm / 100) * 60 + ($mm % 100);
454         $mm = $tz < 0 ? -$mm : $mm;
455         ($mm * 60);
456 }
457
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>!;
465
466         $$bref =~ s/^(tagger .*&gt; )([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));
470 }
471
472 sub show_tag ($$) {
473         my ($ctx, $res) = @_;
474         my ($git, $oid) = @$res;
475         $ctx->{git} = $git;
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;
481         }
482 }
483
484 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
485 sub solve_result {
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));
490
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 ];
500         };
501
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>
507 EOM
508         }
509         bless $ctx, 'PublicInbox::WwwStream'; # for DESTROY
510         $ctx->{git} = $git;
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;
516         }
517 }
518
519 sub show_blob { # git->cat_async callback
520         my ($blob, $oid, $type, $size, $ctx) = @_;
521         if (!$blob) {
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))
525         }
526
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 ]]);
532         }
533
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));
538
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);
543
544         ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
545         my $ok = $hl->do_hl($blob, $path) if $hl;
546         if ($ok) {
547                 $blob = $ok;
548         } else {
549                 $$blob = ascii_html($$blob);
550         }
551
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));
562 }
563
564 # GET /$INBOX/$GIT_OBJECT_ID/s/
565 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
566 sub show ($$;$) {
567         my ($ctx, $oid_b, $fn) = @_;
568         my $qp = $ctx->{qp};
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 '';
573         }
574         $ctx->{fn} = $fn;
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)
582         sub {
583                 $ctx->{-wcb} = $_[0]; # HTTP write callback
584                 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);
585         };
586 }
587
588 1;