]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ViewVCS.pm
96883f6ccbda5fe15c25b9e0463ae8bae7f3573d
[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, '<', "$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 '$SHOW_FMT' -z --no-notes --no-patch $oid >h && ".
175                 "git show --pretty=format:%n -M --stat -p $oid >p && ".
176                 "git patch-id --stable <p" ];
177         my $xenv = { GIT_DIR => $git->{git_dir} };
178         my $tmp = File::Temp->newdir("show-$oid-XXXX", TMPDIR => 1);
179         my $qsp = PublicInbox::Qspawn->new($cmd, $xenv, { -C => "$tmp" });
180         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
181         $ctx->{-logref} = $logref;
182         $ctx->{-tmp} = $tmp;
183         $ctx->{env}->{'qspawn.wcb'} = delete $ctx->{-wcb};
184         $qsp->psgi_qx($ctx->{env}, undef, \&show_commit_result, $ctx);
185 }
186
187 sub show_other ($$$$) {
188         my ($ctx, $res, $logref, $fn) = @_;
189         my ($git, $oid, $type, $size) = @$res;
190         if ($size > $MAX_SIZE) {
191                 $$logref = "$oid is too big to show\n" . $$logref;
192                 return html_page($ctx, 200, $logref);
193         }
194         my $cmd = ['git', "--git-dir=$git->{git_dir}",
195                 qw(show --encoding=UTF-8 --no-color --no-abbrev), $oid ];
196         my $qsp = PublicInbox::Qspawn->new($cmd);
197         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
198         $ctx->{-logref} = $logref;
199         $qsp->psgi_qx($ctx->{env}, undef, \&show_other_result, $ctx);
200 }
201
202 # user_cb for SolverGit, called as: user_cb->($result_or_error, $uarg)
203 sub solve_result {
204         my ($res, $ctx) = @_;
205         my ($log, $hints, $fn) = delete @$ctx{qw(log hints fn)};
206
207         unless (seek($log, 0, 0)) {
208                 warn "seek(log): $!";
209                 return html_page($ctx, 500, \'seek error');
210         }
211         $log = do { local $/; <$log> };
212
213         my $l = PublicInbox::Linkify->new;
214         $log = '<pre>debug log:</pre><hr /><pre>' .
215                 $l->to_html($log) . '</pre>';
216
217         $res or return html_page($ctx, 404, \$log);
218         ref($res) eq 'ARRAY' or return html_page($ctx, 500, \$log);
219
220         my ($git, $oid, $type, $size, $di) = @$res;
221         return show_commit($ctx, $res, \$log, $fn) if $type eq 'commit';
222         return show_other($ctx, $res, \$log, $fn) if $type ne 'blob';
223         my $path = to_filename($di->{path_b} // $hints->{path_b} // 'blob');
224         my $raw_link = "(<a\nhref=$path>raw</a>)";
225         if ($size > $MAX_SIZE) {
226                 return stream_large_blob($ctx, $res, \$log, $fn) if defined $fn;
227                 $log = "<pre><b>Too big to show, download available</b>\n" .
228                         "$oid $type $size bytes $raw_link</pre>" . $log;
229                 return html_page($ctx, 200, \$log);
230         }
231
232         my $blob = $git->cat_file($oid);
233         if (!$blob) { # WTF?
234                 my $e = "Failed to retrieve generated blob ($oid)";
235                 warn "$e ($git->{git_dir})";
236                 $log = "<pre><b>$e</b></pre>" . $log;
237                 return html_page($ctx, 500, \$log);
238         }
239
240         my $bin = index(substr($$blob, 0, $BIN_DETECT), "\0") >= 0;
241         if (defined $fn) {
242                 my $h = [ 'Content-Length', $size, 'Content-Type' ];
243                 push(@$h, ($bin ? 'application/octet-stream' : 'text/plain'));
244                 return delete($ctx->{-wcb})->([200, $h, [ $$blob ]]);
245         }
246
247         if ($bin) {
248                 $log = "<pre>$oid $type $size bytes (binary)" .
249                         " $raw_link</pre>" . $log;
250                 return html_page($ctx, 200, \$log);
251         }
252
253         # TODO: detect + convert to ensure validity
254         utf8::decode($$blob);
255         my $nl = ($$blob =~ s/\r?\n/\n/sg);
256         my $pad = length($nl);
257
258         $l->linkify_1($$blob);
259         my $ok = $hl->do_hl($blob, $path) if $hl;
260         if ($ok) {
261                 $blob = $ok;
262         } else {
263                 $$blob = ascii_html($$blob);
264         }
265
266         # using some of the same CSS class names and ids as cgit
267         $log = "<pre>$oid $type $size bytes $raw_link</pre>" .
268                 "<hr /><table\nclass=blob>".
269                 "<tr><td\nclass=linenumbers><pre>" . join('', map {
270                         sprintf("<a id=n$_ href=#n$_>% ${pad}u</a>\n", $_)
271                 } (1..$nl)) . '</pre></td>' .
272                 '<td><pre> </pre></td>'. # pad for non-CSS users
273                 "<td\nclass=lines><pre\nstyle='white-space:pre'><code>" .
274                 $l->linkify_2($$blob) .
275                 '</code></pre></td></tr></table>' . $log;
276
277         html_page($ctx, 200, \$log);
278 }
279
280 # GET /$INBOX/$GIT_OBJECT_ID/s/
281 # GET /$INBOX/$GIT_OBJECT_ID/s/$FILENAME
282 sub show ($$;$) {
283         my ($ctx, $oid_b, $fn) = @_;
284         my $qp = $ctx->{qp};
285         my $hints = $ctx->{hints} = {};
286         while (my ($from, $to) = each %QP_MAP) {
287                 defined(my $v = $qp->{$from}) or next;
288                 $hints->{$to} = $v if $v ne '';
289         }
290
291         $ctx->{'log'} = tmpfile("solve.$oid_b") // die "tmpfile: $!";
292         $ctx->{fn} = $fn;
293         my $solver = PublicInbox::SolverGit->new($ctx->{ibx},
294                                                 \&solve_result, $ctx);
295         # PSGI server will call this immediately and give us a callback (-wcb)
296         sub {
297                 $ctx->{-wcb} = $_[0]; # HTTP write callback
298                 $solver->solve($ctx->{env}, $ctx->{log}, $oid_b, $hints);
299         };
300 }
301
302 1;