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