]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
git: move async_cat reference to PublicInbox::Git
[public-inbox.git] / lib / PublicInbox / Git.pm
1 # Copyright (C) 2014-2020 all contributors <meta@public-inbox.org>
2 # License: GPLv2 or later <https://www.gnu.org/licenses/gpl-2.0.txt>
3 #
4 # Used to read files from a git repository without excessive forking.
5 # Used in our web interfaces as well as our -nntpd server.
6 # This is based on code in Git.pm which is GPLv2+, but modified to avoid
7 # dependence on environment variables for compatibility with mod_perl.
8 # There are also API changes to simplify our usage and data set.
9 package PublicInbox::Git;
10 use strict;
11 use warnings;
12 use POSIX ();
13 use IO::Handle; # ->autoflush
14 use File::Glob qw(bsd_glob GLOB_NOSORT);
15 use PublicInbox::Spawn qw(popen_rd);
16 use PublicInbox::Tmpfile;
17 use base qw(Exporter);
18 our @EXPORT_OK = qw(git_unquote git_quote);
19 use Errno qw(EINTR);
20 our $PIPE_BUFSIZ = 65536; # Linux default
21
22 use constant MAX_INFLIGHT =>
23         (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
24         /
25         65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
26
27 my %GIT_ESC = (
28         a => "\a",
29         b => "\b",
30         f => "\f",
31         n => "\n",
32         r => "\r",
33         t => "\t",
34         v => "\013",
35         '"' => '"',
36         '\\' => '\\',
37 );
38 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
39
40
41 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
42 sub git_unquote ($) {
43         return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
44         $_[0] = $1;
45         $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
46         $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
47         $_[0];
48 }
49
50 sub git_quote ($) {
51         if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
52                       '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
53                 return qq{"$_[0]"};
54         }
55         $_[0];
56 }
57
58 sub new {
59         my ($class, $git_dir) = @_;
60         # may contain {-tmp} field for File::Temp::Dir
61         bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
62 }
63
64 sub git_path ($$) {
65         my ($self, $path) = @_;
66         $self->{-git_path}->{$path} ||= do {
67                 local $/ = "\n";
68                 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
69
70                 # git prior to 2.5.0 did not understand --git-path
71                 if ($str eq "--git-path\n$path") {
72                         $str = "$self->{git_dir}/$path";
73                 }
74                 $str;
75         };
76 }
77
78 sub alternates_changed {
79         my ($self) = @_;
80         my $alt = git_path($self, 'objects/info/alternates');
81         my @st = stat($alt) or return 0;
82
83         # can't rely on 'q' on some 32-bit builds, but `d' works
84         my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
85         return 0 if $self->{alt_st} eq $st;
86         $self->{alt_st} = $st; # always a true value
87 }
88
89 sub last_check_err {
90         my ($self) = @_;
91         my $fh = $self->{err_c} or return;
92         sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
93         defined(sysread($fh, my $buf, -s $fh)) or
94                         fail($self, "sysread failed: $!");
95         $buf;
96 }
97
98 sub _bidi_pipe {
99         my ($self, $batch, $in, $out, $pid, $err) = @_;
100         if ($self->{$pid}) {
101                 if (defined $err) { # "err_c"
102                         my $fh = $self->{$err};
103                         sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
104                         truncate($fh, 0) or fail($self, "truncate failed: $!");
105                 }
106                 return;
107         }
108         my ($out_r, $out_w);
109         pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
110         my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
111                         qw(-c core.abbrev=40 cat-file), $batch);
112         my $redir = { 0 => $out_r };
113         if ($err) {
114                 my $id = "git.$self->{git_dir}$batch.err";
115                 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
116                 $self->{$err} = $fh;
117                 $redir->{2} = $fh;
118         }
119         my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
120         $self->{$pid} = $p;
121         $out_w->autoflush(1);
122         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
123                 fcntl($out_w, 1031, 4096);
124                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
125         }
126         $self->{$out} = $out_w;
127         $self->{$in} = $in_r;
128 }
129
130 sub my_read ($$$) {
131         my ($fh, $rbuf, $len) = @_;
132         my $left = $len - length($$rbuf);
133         my $r;
134         while ($left > 0) {
135                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
136                 if ($r) {
137                         $left -= $r;
138                 } else {
139                         next if (!defined($r) && $! == EINTR);
140                         return $r;
141                 }
142         }
143         \substr($$rbuf, 0, $len, '');
144 }
145
146 sub my_readline ($$) {
147         my ($fh, $rbuf) = @_;
148         while (1) {
149                 if ((my $n = index($$rbuf, "\n")) >= 0) {
150                         return substr($$rbuf, 0, $n + 1, '');
151                 }
152                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
153                 next if $r || (!defined($r) && $! == EINTR);
154                 return defined($r) ? '' : undef; # EOF or error
155         }
156 }
157
158 sub cat_async_step ($$) {
159         my ($self, $inflight) = @_;
160         die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
161         my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
162         my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
163         my ($bref, $oid, $type, $size);
164         my $head = my_readline($self->{in}, $rbuf);
165         if ($head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/) {
166                 ($oid, $type, $size) = ($1, $2, $3 + 0);
167                 $bref = my_read($self->{in}, $rbuf, $size + 1) or
168                         fail($self, defined($bref) ? 'read EOF' : "read: $!");
169                 chop($$bref) eq "\n" or fail($self, 'LF missing after blob');
170         } elsif ($head =~ / missing$/) {
171                 $type = 'missing';
172                 $oid = $req;
173         } else {
174                 fail($self, "Unexpected result from async git cat-file: $head");
175         }
176         eval { $cb->($bref, $oid, $type, $size, $arg) };
177         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
178         warn "E: $oid: $@\n" if $@;
179 }
180
181 sub cat_async_wait ($) {
182         my ($self) = @_;
183         my $inflight = delete $self->{inflight} or return;
184         while (scalar(@$inflight)) {
185                 cat_async_step($self, $inflight);
186         }
187 }
188
189 sub batch_prepare ($) {
190         _bidi_pipe($_[0], qw(--batch in out pid));
191 }
192
193 sub cat_file {
194         my ($self, $obj, $sizeref) = @_;
195         my ($retried, $head, $rbuf);
196         cat_async_wait($self);
197 again:
198         batch_prepare($self);
199         $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
200         print { $self->{out} } $obj, "\n" or fail($self, "write error: $!");
201         $head = my_readline($self->{in}, $rbuf);
202         if ($head =~ / missing$/) {
203                 if (!$retried && alternates_changed($self)) {
204                         $retried = 1;
205                         cleanup($self);
206                         goto again;
207                 }
208                 return;
209         }
210         $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
211                 fail($self, "Unexpected result from git cat-file: $head");
212
213         my $size = $1 + 0;
214         $$sizeref = $size if $sizeref;
215         my $ret = my_read($self->{in}, $rbuf, $size + 1);
216         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
217         fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
218         chop($$ret) eq "\n" or fail($self, 'newline missing after blob');
219         $ret;
220 }
221
222 sub check {
223         my ($self, $obj) = @_;
224         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
225         print { $self->{out_c} } $obj, "\n" or fail($self, "write error: $!");
226         my $rbuf = ''; # TODO: async + {chk_rbuf}
227         chomp(my $line = my_readline($self->{in_c}, \$rbuf));
228         my ($hex, $type, $size) = split(' ', $line);
229
230         # Future versions of git.git may show 'ambiguous', but for now,
231         # we must handle 'dangling' below (and maybe some other oddball
232         # stuff):
233         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
234         return if $type eq 'missing' || $type eq 'ambiguous';
235
236         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
237                 my $ret = my_read($self->{in_c}, \$rbuf, $type + 1);
238                 fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
239                 return;
240         }
241
242         ($hex, $type, $size);
243 }
244
245 sub _destroy {
246         my ($self, $rbuf, $in, $out, $pid, $err) = @_;
247         my $p = delete $self->{$pid} or return;
248         delete @$self{($rbuf, $in, $out)};
249         delete $self->{$err} if $err; # `err_c'
250
251         # PublicInbox::DS may not be loaded
252         eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
253         waitpid($p, 0) if $@; # wait synchronously if not in event loop
254 }
255
256 sub cat_async_abort ($) {
257         my ($self) = @_;
258         my $inflight = delete $self->{inflight} or die 'BUG: not in async';
259         cleanup($self);
260 }
261
262 sub fail {
263         my ($self, $msg) = @_;
264         $self->{inflight} ? cat_async_abort($self) : cleanup($self);
265         die $msg;
266 }
267
268 sub popen {
269         my ($self, @cmd) = @_;
270         @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
271         popen_rd(\@cmd);
272 }
273
274 sub qx {
275         my ($self, @cmd) = @_;
276         my $fh = $self->popen(@cmd);
277         local $/ = "\n";
278         return <$fh> if wantarray;
279         local $/;
280         <$fh>
281 }
282
283 # returns true if there are pending "git cat-file" processes
284 sub cleanup {
285         my ($self) = @_;
286         if (my $ac = $self->{async_cat}) {
287                 $ac->close; # PublicInbox::GitAsyncCat::close -> EPOLL_CTL_DEL
288         }
289         cat_async_wait($self);
290         _destroy($self, qw(cat_rbuf in out pid));
291         _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
292         !!($self->{pid} || $self->{pid_c});
293 }
294
295 # assuming a well-maintained repo, this should be a somewhat
296 # accurate estimation of its size
297 # TODO: show this in the WWW UI as a hint to potential cloners
298 sub packed_bytes {
299         my ($self) = @_;
300         my $n = 0;
301         my $pack_dir = git_path($self, 'objects/pack');
302         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
303                 $n += -s $p;
304         }
305         $n
306 }
307
308 sub DESTROY { cleanup(@_) }
309
310 sub local_nick ($) {
311         my ($self) = @_;
312         my $ret = '???';
313         # don't show full FS path, basename should be OK:
314         if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
315                 $ret = "/path/to/$1";
316         }
317         wantarray ? ($ret) : $ret;
318 }
319
320 sub host_prefix_url ($$) {
321         my ($env, $url) = @_;
322         return $url if index($url, '//') >= 0;
323         my $scheme = $env->{'psgi.url_scheme'};
324         my $host_port = $env->{HTTP_HOST} //
325                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
326         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
327 }
328
329 sub pub_urls {
330         my ($self, $env) = @_;
331         if (my $urls = $self->{cgit_url}) {
332                 return map { host_prefix_url($env, $_) } @$urls;
333         }
334         local_nick($self);
335 }
336
337 sub cat_async_begin {
338         my ($self) = @_;
339         cleanup($self) if alternates_changed($self);
340         batch_prepare($self);
341         die 'BUG: already in async' if $self->{inflight};
342         $self->{inflight} = [];
343 }
344
345 sub cat_async ($$$;$) {
346         my ($self, $oid, $cb, $arg) = @_;
347         my $inflight = $self->{inflight} // cat_async_begin($self);
348         if (scalar(@$inflight) >= MAX_INFLIGHT) {
349                 cat_async_step($self, $inflight);
350         }
351
352         print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
353         push(@$inflight, $oid, $cb, $arg);
354 }
355
356 sub extract_cmt_time {
357         my ($bref, undef, undef, undef, $modified) = @_;
358
359         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
360                 my $cmt_time = $1 + 0;
361                 $$modified = $cmt_time if $cmt_time > $$modified;
362         }
363 }
364
365 # returns the modified time of a git repo, same as the "modified" field
366 # of a grokmirror manifest
367 sub modified ($) {
368         my ($self) = @_;
369         my $modified = 0;
370         my $fh = popen($self, qw(rev-parse --branches));
371         local $/ = "\n";
372         while (my $oid = <$fh>) {
373                 chomp $oid;
374                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
375         }
376         cat_async_wait($self);
377         $modified || time;
378 }
379
380 1;
381 __END__
382 =pod
383
384 =head1 NAME
385
386 PublicInbox::Git - git wrapper
387
388 =head1 VERSION
389
390 version 1.0
391
392 =head1 SYNOPSIS
393
394         use PublicInbox::Git;
395         chomp(my $git_dir = `git rev-parse --git-dir`);
396         $git_dir or die "GIT_DIR= must be specified\n";
397         my $git = PublicInbox::Git->new($git_dir);
398
399 =head1 DESCRIPTION
400
401 Unstable API outside of the L</new> method.
402 It requires L<git(1)> to be installed.
403
404 =head1 METHODS
405
406 =cut
407
408 =head2 new
409
410         my $git = PublicInbox::Git->new($git_dir);
411
412 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
413 This is the only public API method we support.  Everything else
414 in this module is subject to change.
415
416 =head1 SEE ALSO
417
418 L<Git>, L<PublicInbox::Import>
419
420 =head1 CONTACT
421
422 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
423
424 The mail archives are hosted at L<https://public-inbox.org/meta/>
425
426 =head1 COPYRIGHT
427
428 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
429
430 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
431
432 =cut