]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewVCS.pm
viewvcs: don't wait on slow disks for git commit titles
[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);
25 use PublicInbox::View;
26 use Text::Wrap qw(wrap);
27 use PublicInbox::Hval qw(ascii_html to_filename);
28 my $hl = eval {
29         require PublicInbox::HlMod;
30         PublicInbox::HlMod->new;
31 };
32
33 my %QP_MAP = ( A => 'oid_a', a => 'path_a', b => 'path_b' );
34 our $MAX_SIZE = 1024 * 1024; # TODO: configurable
35 my $BIN_DETECT = 8000; # same as git
36 my $SHOW_FMT = '--pretty=format:'.join('%n', '%P', '%p', '%H', '%T', '%s',
37         '%an <%ae>  %ai', '%cn <%ce>  %ci', '%b%x00');
38
39 sub html_page ($$$) {
40         my ($ctx, $code, $strref) = @_;
41         my $wcb = delete $ctx->{-wcb};
42         $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
43         my $res = html_oneshot($ctx, $code, $strref);
44         $wcb ? $wcb->($res) : $res;
45 }
46
47 sub stream_blob_parse_hdr { # {parse_hdr} for Qspawn
48         my ($r, $bref, $ctx) = @_;
49         my ($res, $logref) = delete @$ctx{qw(-res -logref)};
50         my ($git, $oid, $type, $size, $di) = @$res;
51         my @cl = ('Content-Length', $size);
52         if (!defined $r) { # error
53                 html_page($ctx, 500, $logref);
54         } elsif (index($$bref, "\0") >= 0) {
55                 [200, [qw(Content-Type application/octet-stream), @cl] ];
56         } else {
57                 my $n = length($$bref);
58                 if ($n >= $BIN_DETECT || $n == $size) {
59                         return [200, [ 'Content-Type',
60                                 'text/plain; charset=UTF-8', @cl ] ];
61                 }
62                 if ($r == 0) {
63                         warn "premature EOF on $oid $$logref";
64                         return html_page($ctx, 500, $logref);
65                 }
66                 @$ctx{qw(-res -logref)} = ($res, $logref);
67                 undef; # bref keeps growing
68         }
69 }
70
71 sub stream_large_blob ($$$$) {
72         my ($ctx, $res, $logref, $fn) = @_;
73         $ctx->{-logref} = $logref;
74         $ctx->{-res} = $res;
75         my ($git, $oid, $type, $size, $di) = @$res;
76         my $cmd = ['git', "--git-dir=$git->{git_dir}", 'cat-file', $type, $oid];
77         my $qsp = PublicInbox::Qspawn->new($cmd);
78         my $env = $ctx->{env};
79         $env->{'qspawn.wcb'} = delete $ctx->{-wcb};
80         $qsp->psgi_return($env, undef, \&stream_blob_parse_hdr, $ctx);
81 }
82
83 sub show_other_result ($$) {
84         my ($bref, $ctx) = @_;
85         my ($qsp_err, $logref) = delete @$ctx{qw(-qsp_err -logref)};
86         if ($qsp_err) {
87                 $$logref .= "git show error:$qsp_err";
88                 return html_page($ctx, 500, $logref);
89         }
90         my $l = PublicInbox::Linkify->new;
91         utf8::decode($$bref);
92         $$bref = '<pre>'. $l->to_html($$bref);
93         $$bref .= '</pre><hr>' . $$logref;
94         html_page($ctx, 200, $bref);
95 }
96
97 sub cmt_title { # git->cat_async callback
98         my ($bref, $oid, $type, $size, $ctx) = @_;
99         utf8::decode($$bref);
100         my $title = $$bref =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/ ? $1 : '';
101         push(@{$ctx->{-cmt_pt}} , ascii_html($title)) == @{$ctx->{-cmt_P}} and
102                 cmt_finalize($ctx);
103 }
104
105 sub show_commit_start { # ->psgi_qx callback
106         my ($bref, $ctx) = @_;
107         my ($qsp_err, $logref) = delete @$ctx{qw(-qsp_err -logref)};
108         if ($qsp_err) {
109                 $$logref .= "git show/patch-id error:$qsp_err";
110                 return html_page($ctx, 500, $logref);
111         }
112         my $patchid = (split(/ /, $$bref))[0]; # ignore commit
113         $ctx->{-q_value_html} = "patchid:$patchid" if defined $patchid;
114         open my $fh, '<:utf8', "$ctx->{-tmp}/h" or
115                 die "open $ctx->{-tmp}/h: $!";
116         chop(my $buf = do { local $/ = "\0"; <$fh> });
117         chomp $buf;
118         my ($P, $p);
119         ($P, $p, @$ctx{qw(cmt_H cmt_T cmt_s cmt_au cmt_co cmt_b)})
120                 = split(/\n/, $buf, 8);
121         return cmt_finalize($ctx) if !$P;
122         @{$ctx->{-cmt_P}} = split(/ /, $P);
123         @{$ctx->{-cmt_p}} = split(/ /, $p); # abbreviated
124         if ($ctx->{env}->{'pi-httpd.async'}) {
125                 for (@{$ctx->{-cmt_P}}) {
126                         ibx_async_cat($ctx, $_, \&cmt_title, $ctx);
127                 }
128         } else { # synchronous
129                 for (@{$ctx->{-cmt_P}}) {
130                         $ctx->{git}->cat_async($_, \&cmt_title, $ctx);
131                 }
132                 $ctx->{git}->cat_async_wait;
133         }
134 }
135
136 sub cmt_finalize {
137         my ($ctx) = @_;
138         $ctx->{-linkify} = PublicInbox::Linkify->new;
139         # try to keep author and committer dates lined up
140         my ($au, $co) = delete @$ctx{qw(cmt_au cmt_co)};
141         my $x = length($au) - length($co);
142         if ($x > 0) {
143                 $x = ' ' x $x;
144                 $co =~ s/>/>$x/;
145         } elsif ($x < 0) {
146                 $x = ' ' x (-$x);
147                 $au =~ s/>/>$x/;
148         }
149         $_ = ascii_html($_) for ($au, $co);
150         my $s = $ctx->{-linkify}->to_html(delete $ctx->{cmt_s});
151         $ctx->{-title_html} = $s;
152         my $upfx = $ctx->{-upfx} = '../../'; # from "/$INBOX/$OID/s/"
153         my ($P, $p, $pt) = delete @$ctx{qw(-cmt_P -cmt_p -cmt_pt)};
154         $_ = qq(<a href="$upfx$_/s/">).shift(@$p).'</a> '.shift(@$pt) for @$P;
155         if (@$P == 1) {
156                 $x = qq(\n   parent $P->[0]);
157         } elsif (@$P > 1) {
158                 $x = qq(\n  parents $P->[0]\n);
159                 shift @$P;
160                 $x .= qq(          $_\n) for @$P;
161                 chop $x;
162         } else {
163                 $x = ' (root commit)';
164         }
165         PublicInbox::WwwStream::html_init($ctx);
166         $ctx->zmore(<<EOM);
167 <pre>   commit $ctx->{cmt_H}$x
168      tree <a href="$upfx$ctx->{cmt_T}/s/">$ctx->{cmt_T}</a>
169    author $au
170 committer $co
171
172 <b>$s</b>
173 EOM
174         $x = delete $ctx->{cmt_b};
175         $ctx->zmore("\n", $ctx->{-linkify}->to_html($x)) if length($x);
176         undef $x;
177         open my $fh, '<:utf8', "$ctx->{-tmp}/p" or
178                 die "open $ctx->{-tmp}/p: $!";
179         if (-s $fh > $MAX_SIZE) {
180                 $ctx->zmore("---\n patch is too large to show\n");
181         } else { # prepare flush_diff:
182                 $ctx->{obuf} = \$x;
183                 $ctx->{-apfx} = $ctx->{-spfx} = $upfx;
184                 read($fh, my $bdy, -s _);
185                 $bdy =~ s/\r?\n/\n/gs;
186                 $ctx->{-anchors} = {} if $bdy =~ /^diff --git /sm;
187                 flush_diff($ctx, \$bdy); # undefs $bdy
188                 $ctx->zmore($x);
189                 undef $x;
190                 # TODO: should there be another textarea which attempts to
191                 # search for the exact email which was applied to make this
192                 # commit?
193                 if (my $qry = delete $ctx->{-qry}) {
194                         my $q = '';
195                         for (@{$qry->{dfpost}}, @{$qry->{dfpre}}) {
196                                 # keep blobs as short as reasonable, emails
197                                 # are going to be older than what's in git
198                                 substr($_, 7, 64, '');
199                                 $q .= "dfblob:$_ ";
200                         }
201                         chop $q; # no trailing SP
202                         local $Text::Wrap::columns = PublicInbox::View::COLS;
203                         local $Text::Wrap::huge = 'overflow';
204                         $q = wrap('', '', $q);
205                         my $rows = ($q =~ tr/\n/\n/) + 1;
206                         $q = ascii_html($q);
207                         $ctx->zmore(<<EOM);
208 <hr><form action=$upfx
209 id=related><pre>find related emails, including ancestors/descendants/conflicts
210 <textarea name=q cols=${\PublicInbox::View::COLS} rows=$rows>$q</textarea>
211 <input type=submit value=search
212 />\t(<a href=${upfx}_/text/help/>help</a>)</pre></form>
213 EOM
214                 }
215         }
216         $x = $ctx->zflush($ctx->_html_end);
217         my $res_hdr = delete $ctx->{-res_hdr};
218         push @$res_hdr, 'Content-Length', length($x);
219         delete($ctx->{env}->{'qspawn.wcb'})->([200, $res_hdr, [$x]]);
220 }
221
222 sub show_commit ($$$$) {
223         my ($ctx, $res, $logref, $fn) = @_;
224         my ($git, $oid) = @$res;
225         # patch-id needs two passes, and we use the initial show to ensure
226         # a patch embedded inside the commit message body doesn't get fed
227         # to patch-id:
228         my $cmd = [ '/bin/sh', '-c',
229                 "git show --encoding=UTF-8 '$SHOW_FMT'".
230                 " -z --no-notes --no-patch $oid >h && ".
231                 'git show --encoding=UTF-8 --pretty=format:%n -M'.
232                 " --stat -p $oid >p && ".
233                 "git patch-id --stable <p" ];
234         my $xenv = { GIT_DIR => $git->{git_dir} };
235         my $tmp = File::Temp->newdir("show-$oid-XXXX", TMPDIR => 1);
236         my $qsp = PublicInbox::Qspawn->new($cmd, $xenv, { -C => "$tmp" });
237         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
238         $ctx->{-logref} = $logref;
239         $ctx->{-tmp} = $tmp;
240         $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
241         $ctx->{git} = $git;
242         $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_start, $ctx);
243 }
244
245 sub show_other ($$$$) {
246         my ($ctx, $res, $logref, $fn) = @_;
247         my ($git, $oid, $type, $size) = @$res;
248         if ($size > $MAX_SIZE) {
249                 $$logref = "$oid is too big to show\n" . $$logref;
250                 return html_page($ctx, 200, $logref);
251         }
252         my $cmd = ['git', "--git-dir=$git->{git_dir}",
253                 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
254         my $qsp = PublicInbox::Qspawn->new($cmd);
255         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
256         $ctx->{-logref} = $logref;
257         $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
258 }
259
260 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
261 sub solve_result {
262         my ($res, $ctx) = @_;
263         my ($log, $hints, $fn) = delete @$ctx{qw(log hints fn)};
264
265         unless (seek($log, 0, 0)) {
266                 warn "seek(log): $!";
267                 return html_page($ctx, 500, \'seek error');
268         }
269         $log = do { local $/; <$log> };
270
271         my $l = PublicInbox::Linkify->new;
272         $log = '<pre>debug log:</pre><hr /><pre>' .
273                 $l->to_html($log) . '</pre>';
274
275         $res or return html_page($ctx, 404, \$log);
276         ref($res) eq 'ARRAY' or return html_page($ctx, 500, \$log);
277
278         my ($git, $oid, $type, $size, $di) = @$res;
279         return show_commit($ctx, $res, \$log, $fn) if $type eq 'commit';
280         return show_other($ctx, $res, \$log, $fn) if $type ne 'blob';
281         my $path = to_filename($di->{path_b} // $hints->{path_b} // 'blob');
282         my $raw_link = "(<a\nhref=$path>raw</a>)";
283         if ($size > $MAX_SIZE) {
284                 return stream_large_blob($ctx, $res, \$log, $fn) if defined $fn;
285                 $log = "<pre><b>Too big to show, download available</b>\n" .
286                         "$oid $type $size bytes $raw_link</pre>" . $log;
287                 return html_page($ctx, 200, \$log);
288         }
289
290         my $blob = $git->cat_file($oid);
291         if (!$blob) { # WTF?
292                 my $e = "Failed to retrieve generated blob ($oid)";
293                 warn "$e ($git->{git_dir})";
294                 $log = "<pre><b>$e</b></pre>" . $log;
295                 return html_page($ctx, 500, \$log);
296         }
297
298         my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
299         if (defined $fn) {
300                 my $h = [ 'Content-Length', $size, 'Content-Type' ];
301                 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
302                 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
303         }
304
305         if ($bin) {
306                 $log = "<pre>$oid $type $size bytes (binary)" .
307                         " $raw_link</pre>" . $log;
308                 return html_page($ctx, 200, \$log);
309         }
310
311         # TODO: detect + convert to ensure validity
312         utf8::decode($$blob);
313         my $nl = ($$blob =~ s/\r?\n/\n/sg);
314         my $pad = length($nl);
315
316         $l->linkify_1($$blob);
317         my $ok = $hl->do_hl($blob, $path) if $hl;
318         if ($ok) {
319                 $blob = $ok;
320         } else {
321                 $$blob = ascii_html($$blob);
322         }
323
324         # using some of the same CSS class names and ids as cgit
325         $log = "<pre>$oid $type $size bytes $raw_link</pre>" .
326                 "<hr /><table\nclass=blob>".
327                 "<tr><td\nclass=linenumbers><pre>" . join('', map {
328                         sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_)
329                 } (1..$nl)) . '</pre></td>' .
330                 '<td><pre> </pre></td>'. # pad for non-CSS users
331                 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>" .
332                 $l->linkify_2($$blob) .
333                 '</code></pre></td></tr></table>' . $log;
334
335         html_page($ctx, 200, \$log);
336 }
337
338 # GET /$INBOX/$GIT_OBJECT_ID/s/
339 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
340 sub show ($$;$) {
341         my ($ctx, $oid_b, $fn) = @_;
342         my $qp = $ctx->{qp};
343         my $hints = $ctx->{hints} = {};
344         while (my ($from, $to) = each %QP_MAP) {
345                 defined(my $v = $qp->{$from}) or next;
346                 $hints->{$to} = $v if $v ne '';
347         }
348
349         $ctx->{'log'} = tmpfile("solve.$oid_b") // die "tmpfile: $!";
350         $ctx->{fn} = $fn;
351         my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
352                                                 \&solve_result, $ctx);
353         # PSGI server will call this immediately and give us a callback (-wcb)
354         sub {
355                 $ctx->{-wcb} = $_[0]; # HTTP write callback
356                 $solver->solve($ctx->{env}, $ctx->{log}, $oid_b, $hints);
357         };
358 }
359
360 1;