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