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