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