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