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