]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewVCS.pm
eae5b7f416cf88f8c35823dc5647ef01b0c415ca
[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 do_cat_async {
129         my ($ctx, $cb, @oids) = @_;
130         # favor git(1) over Gcf2 (libgit2) for SHA-256 support
131         $ctx->{git}->cat_async($_, $cb, $ctx) for @oids;
132         if ($ctx->{env}->{'pi-httpd.async'}) {
133                 PublicInbox::GitAsyncCat::watch_cat($ctx->{git});
134         } else { # synchronous, generic PSGI
135                 $ctx->{git}->cat_async_wait;
136         }
137 }
138
139 sub show_commit_start { # ->psgi_qx callback
140         my ($bref, $ctx) = @_;
141         if (my $qsp_err = delete $ctx->{-qsp_err}) {
142                 return html_page($ctx, 500, dbg_log($ctx) .
143                                 "git show/patch-id error:$qsp_err");
144         }
145         my $patchid = (split(/ /, $$bref))[0]; # ignore commit
146         $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
147         open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
148                 die "open $ctx->{-tmp}/h: $!";
149         chop(my $buf = do { local $/ = "\0"; <$fh> });
150         chomp $buf;
151         my ($P, $p);
152         ($P, $p, @{$ctx->{cmt_info}}) = split(/\n/, $buf, 9);
153         return cmt_finalize($ctx) if !$P;
154         @{$ctx->{-cmt_P}} = split(/ /, $P);
155         @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
156         do_cat_async($ctx, \&cmt_title, @{$ctx->{-cmt_P}});
157 }
158
159 sub ibx_url_for {
160         my ($ctx) = @_;
161         $ctx->{ibx} and return; # fall back to $upfx
162         $ctx->{git} or die 'BUG: no {git}';
163         if (my $ALL = $ctx->{www}->{pi_cfg}->ALL) {
164                 if (defined(my $u = $ALL->base_url($ctx->{env}))) {
165                         return wantarray ? ($u) : $u;
166                 }
167         }
168         my @ret;
169         if (my $ibx_names = $ctx->{git}->{ibx_names}) {
170                 my $by_name = $ctx->{www}->{pi_cfg}->{-by_name};
171                 for my $name (@$ibx_names) {
172                         my $ibx = $by_name->{$name} // do {
173                                 warn "inbox `$name' no longer exists\n";
174                                 next;
175                         };
176                         $ibx->isrch // next;
177                         my $u = defined($ibx->{url}) ?
178                                 prurl($ctx->{env}, $ibx->{url}) : $name;
179                         $u .= '/' if substr($u, -1) ne '/';
180                         push @ret, $u;
181                 }
182         }
183         wantarray ? (@ret) : $ret[0];
184 }
185
186 sub cmt_finalize {
187         my ($ctx) = @_;
188         $ctx->{-linkify} //= PublicInbox::Linkify->new;
189         my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
190         my ($H, $T, $s, $f, $au, $co, $bdy) = @{delete $ctx->{cmt_info}};
191         # try to keep author and committer dates lined up
192         my $x = length($au) - length($co);
193         if ($x > 0) {
194                 $x = ' ' x $x;
195                 $co =~ s/>/>$x/;
196         } elsif ($x < 0) {
197                 $x = ' ' x (-$x);
198                 $au =~ s/>/>$x/;
199         }
200         $_ = ascii_html($_) for ($au, $co);
201         $au =~ s!(&gt; +)([0-9]{4,}-\S+ \S+)!
202                 my ($gt, $t) = ($1, $2);
203                 $t =~ tr/ :-//d;
204                 qq($gt<a
205 href="$upfx?t=$t"
206 title="list contemporary emails">$2</a>)
207                 !e;
208         $ctx->{-title_html} = $s = $ctx->{-linkify}->to_html($s);
209         my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
210         $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
211         if (@$P == 1) {
212                 $x = qq{ (<a
213 href="$f.patch">patch</a>)\n   <a href=#parent>parent</a> $P->[0]};
214         } elsif (@$P > 1) {
215                 $x = qq(\n  <a href=#parents>parents</a> $P->[0]\n);
216                 shift @$P;
217                 $x .= qq(          $_\n) for @$P;
218                 chop $x;
219         } else {
220                 $x = ' (<a href=#root_commit>root commit</a>)';
221         }
222         PublicInbox::WwwStream::html_init($ctx);
223         my $zfh = $ctx->zfh;
224         print $zfh <<EOM;
225 <pre>   <a href=#commit>commit</a> $H$x
226      <a href=#tree>tree</a> <a href="$upfx$T/s/?b=">$T</a>
227    author $au
228 committer $co
229
230 <b>$s</b>
231 EOM
232         print $zfh "\n", $ctx->{-linkify}->to_html($bdy) if length($bdy);
233         $bdy = '';
234         open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
235                 die "open $ctx->{-tmp}/p: $!";
236         if (-s $fh > $MAX_SIZE) {
237                 print $zfh "---\n patch is too large to show\n";
238         } else { # prepare flush_diff:
239                 read($fh, $x, -s _);
240                 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
241                 $x =~ s/\r?\n/\n/gs;
242                 $ctx->{-anchors} = {} if $x =~ /^diff --git /sm;
243                 flush_diff($ctx, \$x); # undefs $x
244                 # TODO: should there be another textarea which attempts to
245                 # search for the exact email which was applied to make this
246                 # commit?
247                 if (my $qry = delete $ctx->{-qry}) {
248                         my $q = '';
249                         for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
250                                 # keep blobs as short as reasonable, emails
251                                 # are going to be older than what's in git
252                                 substr($_, 7, 64, '');
253                                 $q .= "dfblob:$_ ";
254                         }
255                         chop $q; # no trailing SP
256                         local $Text::Wrap::columns = PublicInbox::View::COLS;
257                         local $Text::Wrap::huge = 'overflow';
258                         $q = wrap('', '', $q);
259                         my $rows = ($q =~ tr/\n/\n/) + 1;
260                         $q = ascii_html($q);
261                         my $ibx_url = ibx_url_for($ctx);
262                         my $alt;
263                         if (defined $ibx_url) {
264                                 $alt = " `$ibx_url'";
265                                 $ibx_url =~ m!://! or
266                                         substr($ibx_url, 0, 0, '../../../');
267                                 $ibx_url = ascii_html($ibx_url);
268                         } else {
269                                 $ibx_url = $upfx;
270                                 $alt = '';
271                         }
272                         print $zfh <<EOM;
273 <hr><form action="$ibx_url"
274 id=related><pre>find related emails, including ancestors/descendants/conflicts
275 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
276 <input type=submit value="search$alt"
277 />\t(<a href="${ibx_url}_/text/help/">help</a>)</pre></form>
278 EOM
279                 }
280         }
281         chop($x = <<EOM);
282 <hr><pre>glossary
283 --------
284 <dfn
285 id=commit>Commit</dfn> objects reference one tree, and zero or more parents.
286
287 Single <dfn
288 id=parent>parent</dfn> commits can typically generate a patch in
289 unified diff format via `git format-patch'.
290
291 Multiple <dfn id=parents>parents</dfn> means the commit is a merge.
292
293 <dfn id=root_commit>Root commits</dfn> have no ancestor.  Note that it is
294 possible to have multiple root commits when merging independent histories.
295
296 Every commit references one top-level <dfn id=tree>tree</dfn> object.</pre>
297 EOM
298         delete($ctx->{-wcb})->($ctx->html_done($x));
299 }
300
301 sub stream_patch_parse_hdr { # {parse_hdr} for Qspawn
302         my ($r, $bref, $ctx) = @_;
303         if (!defined $r) { # sysread error
304                 html_page($ctx, 500, dbg_log($ctx));
305         } elsif (index($$bref, "\n\n") >= 0) {
306                 my $eml = bless { hdr => $bref }, 'PublicInbox::Eml';
307                 my $fn = to_filename($eml->header('Subject') // '');
308                 $fn = substr($fn // 'PATCH-no-subject', 6); # drop "PATCH-"
309                 return [ 200, [ 'Content-Type', 'text/plain; charset=UTF-8',
310                                 'Content-Disposition',
311                                 qq(inline; filename=$fn.patch) ] ];
312         } elsif ($r == 0) {
313                 my $log = dbg_log($ctx);
314                 warn "premature EOF on $ctx->{patch_oid} $log";
315                 return html_page($ctx, 500, $log);
316         } else {
317                 undef; # bref keeps growing until "\n\n"
318         }
319 }
320
321 sub show_patch ($$) {
322         my ($ctx, $res) = @_;
323         my ($git, $oid) = @$res;
324         my @cmd = ('git', "--git-dir=$git->{git_dir}",
325                 qw(format-patch -1 --stdout -C),
326                 "--signature=git format-patch -1 --stdout -C $oid", $oid);
327         my $qsp = PublicInbox::Qspawn->new(\@cmd);
328         $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
329         $ctx->{patch_oid} = $oid;
330         $qsp->psgi_return($ctx->{env}, undef, \&stream_patch_parse_hdr, $ctx);
331 }
332
333 sub show_commit ($$) {
334         my ($ctx, $res) = @_;
335         return show_patch($ctx, $res) if ($ctx->{fn} // '') =~ /\.patch\z/;
336         my ($git, $oid) = @$res;
337         # patch-id needs two passes, and we use the initial show to ensure
338         # a patch embedded inside the commit message body doesn't get fed
339         # to patch-id:
340         my $cmd = [ '/bin/sh', '-c',
341                 "git show --encoding=UTF-8 '$SHOW_FMT'".
342                 " -z --no-notes --no-patch $oid >h && ".
343                 'git show --encoding=UTF-8 --pretty=format:%n -M'.
344                 " --stat -p $oid >p && ".
345                 "git patch-id --stable <p" ];
346         my $e = { GIT_DIR => $git->{git_dir} };
347         my $qsp = PublicInbox::Qspawn->new($cmd, $e, { -C => "$ctx->{-tmp}" });
348         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
349         $ctx->{env}->{'qspawn.wcb'} = $ctx->{-wcb};
350         $ctx->{git} = $git;
351         $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
352 }
353
354 sub show_other ($$) { # just in case...
355         my ($ctx, $res) = @_;
356         my ($git, $oid, $type, $size) = @$res;
357         $size > $MAX_SIZE and return html_page($ctx, 200,
358                 ascii_html($type)." $oid is too big to show\n". dbg_log($ctx));
359         my $cmd = ['git', "--git-dir=$git->{git_dir}",
360                 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
361         my $qsp = PublicInbox::Qspawn->new($cmd);
362         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
363         $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
364 }
365
366 sub show_tree_result ($$) {
367         my ($bref, $ctx) = @_;
368         if (my $qsp_err = delete $ctx->{-qsp_err}) {
369                 return html_page($ctx, 500, dbg_log($ctx) .
370                                 "git ls-tree -z error:$qsp_err");
371         }
372         my @ent = split(/\0/, $$bref);
373         my $qp = delete $ctx->{qp};
374         my $l = $ctx->{-linkify} //= PublicInbox::Linkify->new;
375         my $pfx = $ctx->{-path} // $qp->{b}; # {-path} is from RepoTree
376         $$bref = "<pre><a href=#tree>tree</a> $ctx->{tree_oid}";
377         # $REPO/tree/$path already sets {-upfx}
378         my $upfx = $ctx->{-upfx} //= '../../';
379         if (defined $pfx) {
380                 $pfx =~ s!/+\z!!s;
381                 if (my $t = $ctx->{-obj}) {
382                         my $t = ascii_html($t);
383                         $$bref .= <<EOM
384 \n\$ git ls-tree -l $t  # shows similar output on the CLI
385 EOM
386                 } elsif ($pfx eq '') {
387                         $$bref .= "  (root)\n";
388                 } else {
389                         my $x = ascii_html($pfx);
390                         $pfx .= '/';
391                         $$bref .= qq(  <a href=#path>path</a>: $x</a>\n);
392                 }
393         } else {
394                 $pfx = '';
395                 $$bref .= qq[  (<a href=#path>path</a> unknown)\n];
396         }
397         my ($x, $m, $t, $oid, $sz, $f, $n);
398         $$bref .= "\n   size    name";
399         for (@ent) {
400                 ($x, $f) = split(/\t/, $_, 2);
401                 undef $_;
402                 ($m, $t, $oid, $sz) = split(/ +/, $x, 4);
403                 $m = $GIT_MODE{$m} // '?';
404                 utf8::decode($f);
405                 $n = ascii_html($f);
406                 if ($m eq 'g') { # gitlink submodule commit
407                         $$bref .= "\ng\t\t$n @ <a\nhref=#g>commit</a>$oid";
408                         next;
409                 }
410                 my $q = 'b='.ascii_html(uri_escape_path($pfx.$f));
411                 if ($m eq 'd') { $n .= '/' }
412                 elsif ($m eq 'x') { $n = "<b>$n</b>" }
413                 elsif ($m eq 'l') { $n = "<i>$n</i>" }
414                 $$bref .= qq(\n$m\t$sz\t<a\nhref="$upfx$oid/s/?$q">$n</a>);
415         }
416         $$bref .= dbg_log($ctx);
417         $$bref .= <<EOM;
418 <pre>glossary
419 --------
420 <dfn
421 id=tree>Tree</dfn> objects belong to commits or other tree objects.  Trees may
422 reference blobs, sub-trees, or commits of submodules.
423
424 <dfn
425 id=path>Path</dfn> names are stored in tree objects, but trees do not know
426 their own path name.  A tree's path name comes from their parent tree,
427 or it is the root tree referenced by a commit object.  Thus, this web UI
428 relies on the `b=' URI parameter as a hint to display the path name.
429
430 <dfn title="submodule commit"
431 id=g>Commit</dfn> objects may be stored in trees to reference submodules.</pre>
432 EOM
433         chop $$bref;
434         html_page($ctx, 200, $$bref);
435 }
436
437 sub show_tree ($$) { # also used by RepoTree
438         my ($ctx, $res) = @_;
439         my ($git, $oid, undef, $size) = @$res;
440         $size > $MAX_SIZE and return html_page($ctx, 200,
441                         "tree $oid is too big to show\n". dbg_log($ctx));
442         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
443                 qw(ls-tree -z -l --no-abbrev), $oid ];
444         my $qsp = PublicInbox::Qspawn->new($cmd);
445         $ctx->{tree_oid} = $oid;
446         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
447         $qsp->psgi_qx($ctx->{env}, undef, \&show_tree_result, $ctx);
448 }
449
450 # returns seconds offset from git TZ offset
451 sub tz_adj ($) {
452         my ($tz) = @_; # e.g "-0700"
453         $tz = int($tz);
454         my $mm = $tz < 0 ? -$tz : $tz;
455         $mm = int($mm / 100) * 60 + ($mm % 100);
456         $mm = $tz < 0 ? -$mm : $mm;
457         ($mm * 60);
458 }
459
460 sub show_tag_result { # git->cat_async callback
461         my ($bref, $oid, $type, $size, $ctx) = @_;
462         utf8::decode($$bref);
463         my $l = PublicInbox::Linkify->new;
464         $$bref = $l->to_html($$bref);
465         $$bref =~ s!^object ([a-f0-9]+)!object <a
466 href=../../$1/s/>$1</a>!;
467
468         $$bref =~ s/^(tagger .*&gt; )([0-9]+) ([\-+]?[0-9]+)/$1.strftime(
469                 '%Y-%m-%d %H:%M:%S', gmtime($2 + tz_adj($3)))." $3"/sme;
470         # TODO: download link
471         html_page($ctx, 200, '<pre>', $$bref, '</pre>', dbg_log($ctx));
472 }
473
474 sub show_tag ($$) {
475         my ($ctx, $res) = @_;
476         my ($git, $oid) = @$res;
477         $ctx->{git} = $git;
478         do_cat_async($ctx, \&show_tag_result, $oid);
479 }
480
481 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
482 sub solve_result {
483         my ($res, $ctx) = @_;
484         my $hints = delete $ctx->{hints};
485         $res or return html_page($ctx, 404, dbg_log($ctx));
486         ref($res) eq 'ARRAY' or return html_page($ctx, 500, dbg_log($ctx));
487
488         my ($git, $oid, $type, $size, $di) = @$res;
489         return show_commit($ctx, $res) if $type eq 'commit';
490         return show_tree($ctx, $res) if $type eq 'tree';
491         return show_tag($ctx, $res) if $type eq 'tag';
492         return show_other($ctx, $res) if $type ne 'blob';
493         my $paths = $ctx->{-paths} //= do {
494                 my $path = to_filename($di->{path_b}//$hints->{path_b}//'blob');
495                 my $raw_more = qq[(<a\nhref="$path">raw</a>)];
496                 [ $path, $raw_more ];
497         };
498
499         if ($size > $MAX_SIZE) {
500                 return stream_large_blob($ctx, $res) if defined $ctx->{fn};
501                 return html_page($ctx, 200, <<EOM . dbg_log($ctx));
502 <pre><b>Too big to show, download available</b>
503 blob $oid $size bytes $paths->[1]</pre>
504 EOM
505         }
506         bless $ctx, 'PublicInbox::WwwStream'; # for DESTROY
507         $ctx->{git} = $git;
508         do_cat_async($ctx, \&show_blob, $oid);
509 }
510
511 sub show_blob { # git->cat_async callback
512         my ($blob, $oid, $type, $size, $ctx) = @_;
513         if (!$blob) {
514                 my $e = "Failed to retrieve generated blob ($oid)";
515                 warn "$e ($ctx->{git}->{git_dir}) type=$type";
516                 return html_page($ctx, 500, "<pre><b>$e</b></pre>".dbg_log($ctx))
517         }
518
519         my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
520         if (defined $ctx->{fn}) {
521                 my $h = [ 'Content-Length', $size, 'Content-Type' ];
522                 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
523                 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
524         }
525
526         my ($path, $raw_more) = @{delete $ctx->{-paths}};
527         $bin and return html_page($ctx, 200,
528                                 "<pre>blob $oid $size bytes (binary)" .
529                                 " $raw_more</pre>".dbg_log($ctx));
530
531         # TODO: detect + convert to ensure validity
532         utf8::decode($$blob);
533         my $nl = ($$blob =~ s/\r?\n/\n/sg);
534         my $pad = length($nl);
535
536         ($ctx->{-linkify} //= PublicInbox::Linkify->new)->linkify_1($$blob);
537         my $ok = $hl->do_hl($blob, $path) if $hl;
538         if ($ok) {
539                 $blob = $ok;
540         } else {
541                 $$blob = ascii_html($$blob);
542         }
543
544         # using some of the same CSS class names and ids as cgit
545         my $x = "<pre>blob $oid $size bytes $raw_more</pre>" .
546                 "<hr /><table\nclass=blob>".
547                 "<tr><td\nclass=linenumbers><pre>";
548         # scratchpad in this loop is faster here than `printf $zfh':
549         $x .= sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_) for (1..$nl);
550         $x .= '</pre></td><td><pre> </pre></td>'. # pad for non-CSS users
551                 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>";
552         html_page($ctx, 200, $x, $ctx->{-linkify}->linkify_2($$blob),
553                 '</code></pre></td></tr></table>'.dbg_log($ctx));
554 }
555
556 # GET /$INBOX/$GIT_OBJECT_ID/s/
557 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
558 sub show ($$;$) {
559         my ($ctx, $oid_b, $fn) = @_;
560         my $qp = $ctx->{qp};
561         my $hints = $ctx->{hints} = {};
562         while (my ($from, $to) = each %QP_MAP) {
563                 defined(my $v = $qp->{$from}) or next;
564                 $hints->{$to} = $v if $v ne '';
565         }
566         $ctx->{fn} = $fn;
567         $ctx->{-tmp} = File::Temp->newdir("solver.$oid_b-XXXX", TMPDIR => 1);
568         open $ctx->{lh}, '+>>', "$ctx->{-tmp}/solve.log" or die "open: $!";
569         my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
570                                                 \&solve_result, $ctx);
571         $solver->{gits} //= [ $ctx->{git} ];
572         $solver->{tmp} = $ctx->{-tmp}; # share tmpdir
573         # PSGI server will call this immediately and give us a callback (-wcb)
574         sub {
575                 $ctx->{-wcb} = $_[0]; # HTTP write callback
576                 $solver->solve($ctx->{env}, $ctx->{lh}, $oid_b, $hints);
577         };
578 }
579
580 1;