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>
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;
12 use parent qw(Exporter);
14 use IO::Handle; # ->autoflush
16 use File::Glob qw(bsd_glob GLOB_NOSORT);
17 use Time::HiRes qw(stat);
18 use PublicInbox::Spawn qw(popen_rd);
19 use PublicInbox::Tmpfile;
21 our @EXPORT_OK = qw(git_unquote git_quote);
22 our $PIPE_BUFSIZ = 65536; # Linux default
25 use constant MAX_INFLIGHT =>
26 (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
28 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
41 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
44 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
46 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
48 $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
49 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
54 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
55 '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
62 my ($class, $git_dir) = @_;
63 # may contain {-tmp} field for File::Temp::Dir
64 bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
68 my ($self, $path) = @_;
69 $self->{-git_path}->{$path} ||= do {
71 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
73 # git prior to 2.5.0 did not understand --git-path
74 if ($str eq "--git-path\n$path") {
75 $str = "$self->{git_dir}/$path";
81 sub alternates_changed {
83 my $alt = git_path($self, 'objects/info/alternates');
84 my @st = stat($alt) or return 0;
86 # can't rely on 'q' on some 32-bit builds, but `d' works
87 my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
88 return 0 if $self->{alt_st} eq $st;
89 $self->{alt_st} = $st; # always a true value
94 my $fh = $self->{err_c} or return;
95 sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
96 defined(sysread($fh, my $buf, -s $fh)) or
97 fail($self, "sysread failed: $!");
102 my ($self, $batch, $in, $out, $pid, $err) = @_;
104 if (defined $err) { # "err_c"
105 my $fh = $self->{$err};
106 sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
107 truncate($fh, 0) or fail($self, "truncate failed: $!");
112 pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
113 my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
114 qw(-c core.abbrev=40 cat-file), $batch);
115 my $redir = { 0 => $out_r };
117 my $id = "git.$self->{git_dir}$batch.err";
118 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
122 my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
124 $out_w->autoflush(1);
125 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
126 fcntl($out_w, 1031, 4096);
127 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
129 $self->{$out} = $out_w;
130 $self->{$in} = $in_r;
134 my ($fh, $rbuf, $len) = @_;
135 my $left = $len - length($$rbuf);
138 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
142 next if (!defined($r) && $! == EINTR);
146 \substr($$rbuf, 0, $len, '');
149 sub my_readline ($$) {
150 my ($fh, $rbuf) = @_;
152 if ((my $n = index($$rbuf, "\n")) >= 0) {
153 return substr($$rbuf, 0, $n + 1, '');
155 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
156 next if $r || (!defined($r) && $! == EINTR);
157 return defined($r) ? '' : undef; # EOF or error
161 sub cat_async_retry ($$$$$) {
162 my ($self, $inflight, $req, $cb, $arg) = @_;
164 # {inflight} may be non-existent, but if it isn't we delete it
165 # here to prevent cleanup() from waiting:
166 delete $self->{inflight};
169 $self->{inflight} = $inflight;
170 batch_prepare($self);
172 for (my $i = 0; $i < @$inflight; $i += 3) {
173 $buf .= "$inflight->[$i]\n";
175 print { $self->{out} } $buf or fail($self, "write error: $!");
176 unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
178 cat_async_step($self, $inflight); # take one step
181 sub cat_async_step ($$) {
182 my ($self, $inflight) = @_;
183 die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
184 my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
185 my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
186 my ($bref, $oid, $type, $size);
187 my $head = my_readline($self->{in}, $rbuf);
188 if ($head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/) {
189 ($oid, $type, $size) = ($1, $2, $3 + 0);
190 $bref = my_read($self->{in}, $rbuf, $size + 1) or
191 fail($self, defined($bref) ? 'read EOF' : "read: $!");
192 chop($$bref) eq "\n" or fail($self, 'LF missing after blob');
193 } elsif ($head =~ / missing$/) {
194 # ref($req) indicates it's already been retried
195 if (!ref($req) && !$in_cleanup && alternates_changed($self)) {
196 return cat_async_retry($self, $inflight,
200 $oid = ref($req) ? $$req : $req;
202 fail($self, "Unexpected result from async git cat-file: $head");
204 eval { $cb->($bref, $oid, $type, $size, $arg) };
205 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
206 warn "E: $oid: $@\n" if $@;
209 sub cat_async_wait ($) {
211 my $inflight = delete $self->{inflight} or return;
212 while (scalar(@$inflight)) {
213 cat_async_step($self, $inflight);
217 sub batch_prepare ($) {
218 _bidi_pipe($_[0], qw(--batch in out pid));
222 my ($bref, undef, undef, $size, $result) = @_;
223 @$result = ($bref, $size);
227 my ($self, $oid, $sizeref) = @_;
229 cat_async($self, $oid, \&_cat_file_cb, $result);
230 cat_async_wait($self);
231 $$sizeref = $result->[1] if $sizeref;
235 sub check_async_step ($$) {
236 my ($self, $inflight_c) = @_;
237 die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
238 my ($req, $cb, $arg) = splice(@$inflight_c, 0, 3);
239 my $rbuf = delete($self->{rbuf_c}) // \(my $new = '');
240 chomp(my $line = my_readline($self->{in_c}, $rbuf));
241 my ($hex, $type, $size) = split(/ /, $line);
243 # Future versions of git.git may have type=ambiguous, but for now,
244 # we must handle 'dangling' below (and maybe some other oddball
246 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
247 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
248 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
249 fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
251 eval { $cb->($hex, $type, $size, $arg, $self) };
252 warn "E: check($req) $@\n" if $@;
253 $self->{rbuf_c} = $rbuf if $$rbuf ne '';
256 sub check_async_wait ($) {
258 my $inflight_c = delete $self->{inflight_c} or return;
259 while (scalar(@$inflight_c)) {
260 check_async_step($self, $inflight_c);
264 sub check_async_begin ($) {
266 cleanup($self) if alternates_changed($self);
267 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
268 die 'BUG: already in async check' if $self->{inflight_c};
269 $self->{inflight_c} = [];
272 sub check_async ($$$$) {
273 my ($self, $oid, $cb, $arg) = @_;
274 my $inflight_c = $self->{inflight_c} // check_async_begin($self);
275 if (scalar(@$inflight_c) >= MAX_INFLIGHT) {
276 check_async_step($self, $inflight_c);
278 print { $self->{out_c} } $oid, "\n" or fail($self, "write error: $!");
279 push(@$inflight_c, $oid, $cb, $arg);
282 sub _check_cb { # check_async callback
283 my ($hex, $type, $size, $result) = @_;
284 @$result = ($hex, $type, $size);
288 my ($self, $oid) = @_;
290 check_async($self, $oid, \&_check_cb, $result);
291 check_async_wait($self);
292 my ($hex, $type, $size) = @$result;
294 # Future versions of git.git may show 'ambiguous', but for now,
295 # we must handle 'dangling' below (and maybe some other oddball
297 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
298 return if $type eq 'missing' || $type eq 'ambiguous';
299 return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
300 ($hex, $type, $size);
304 my ($self, $rbuf, $in, $out, $pid, $err) = @_;
305 my $p = delete $self->{$pid} or return;
306 delete @$self{($rbuf, $in, $out)};
307 delete $self->{$err} if $err; # `err_c'
309 # PublicInbox::DS may not be loaded
310 eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
311 waitpid($p, 0) if $@; # wait synchronously if not in event loop
314 sub cat_async_abort ($) {
316 my $inflight = delete $self->{inflight} or die 'BUG: not in async';
321 my ($self, $msg) = @_;
322 $self->{inflight} ? cat_async_abort($self) : cleanup($self);
323 croak("git $self->{git_dir}: $msg");
327 my ($self, @cmd) = @_;
328 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
333 my ($self, @cmd) = @_;
334 my $fh = $self->popen(@cmd);
336 return <$fh> if wantarray;
341 # returns true if there are pending "git cat-file" processes
344 local $in_cleanup = 1;
345 delete $self->{async_cat};
346 check_async_wait($self);
347 cat_async_wait($self);
348 _destroy($self, qw(cat_rbuf in out pid));
349 _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
350 !!($self->{pid} || $self->{pid_c});
353 # assuming a well-maintained repo, this should be a somewhat
354 # accurate estimation of its size
355 # TODO: show this in the WWW UI as a hint to potential cloners
359 my $pack_dir = git_path($self, 'objects/pack');
360 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
366 sub DESTROY { cleanup(@_) }
371 # don't show full FS path, basename should be OK:
372 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
373 $ret = "/path/to/$1";
375 wantarray ? ($ret) : $ret;
378 sub host_prefix_url ($$) {
379 my ($env, $url) = @_;
380 return $url if index($url, '//') >= 0;
381 my $scheme = $env->{'psgi.url_scheme'};
382 my $host_port = $env->{HTTP_HOST} //
383 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
384 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
388 my ($self, $env) = @_;
389 if (my $urls = $self->{cgit_url}) {
390 return map { host_prefix_url($env, $_) } @$urls;
395 sub cat_async_begin {
397 cleanup($self) if alternates_changed($self);
398 batch_prepare($self);
399 die 'BUG: already in async' if $self->{inflight};
400 $self->{inflight} = [];
403 sub cat_async ($$$;$) {
404 my ($self, $oid, $cb, $arg) = @_;
405 my $inflight = $self->{inflight} // cat_async_begin($self);
406 if (scalar(@$inflight) >= MAX_INFLIGHT) {
407 cat_async_step($self, $inflight);
410 print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
411 push(@$inflight, $oid, $cb, $arg);
414 # this is safe to call inside $cb, but not guaranteed to enqueue
415 # returns true if successful, undef if not.
417 my ($self, $oid, $cb, $arg) = @_;
418 if (defined($self->{async_cat}) && (my $inflight = $self->{inflight})) {
419 # we could use MAX_INFLIGHT here w/o the halving,
420 # but lets not allow one client to monopolize a git process
421 if (scalar(@$inflight) < int(MAX_INFLIGHT/2)) {
422 print { $self->{out} } $oid, "\n" or
423 fail($self, "write error: $!");
424 return push(@$inflight, $oid, $cb, $arg);
430 sub extract_cmt_time {
431 my ($bref, undef, undef, undef, $modified) = @_;
433 if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
434 my $cmt_time = $1 + 0;
435 $$modified = $cmt_time if $cmt_time > $$modified;
439 # returns the modified time of a git repo, same as the "modified" field
440 # of a grokmirror manifest
444 my $fh = popen($self, qw(rev-parse --branches));
446 while (my $oid = <$fh>) {
448 cat_async($self, $oid, \&extract_cmt_time, \$modified);
450 cat_async_wait($self);
460 PublicInbox::Git - git wrapper
468 use PublicInbox::Git;
469 chomp(my $git_dir = `git rev-parse --git-dir`);
470 $git_dir or die "GIT_DIR= must be specified\n";
471 my $git = PublicInbox::Git->new($git_dir);
475 Unstable API outside of the L</new> method.
476 It requires L<git(1)> to be installed.
484 my $git = PublicInbox::Git->new($git_dir);
486 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
487 This is the only public API method we support. Everything else
488 in this module is subject to change.
492 L<Git>, L<PublicInbox::Import>
496 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
498 The mail archives are hosted at L<https://public-inbox.org/meta/>
502 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
504 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>