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