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