1 # Copyright (C) 2014-2021 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
15 use Errno qw(EINTR EAGAIN);
16 use File::Glob qw(bsd_glob GLOB_NOSORT);
18 use Time::HiRes qw(stat);
19 use PublicInbox::Spawn qw(popen_rd spawn);
20 use PublicInbox::Tmpfile;
21 use IO::Poll qw(POLLIN);
24 use PublicInbox::DS qw(dwaitpid);
25 our @EXPORT_OK = qw(git_unquote git_quote);
26 our $PIPE_BUFSIZ = 65536; # Linux default
28 our $RDTIMEO = 60_000; # milliseconds
30 use constant MAX_INFLIGHT => (POSIX::PIPE_BUF * 3) /
31 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
44 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
47 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
49 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
51 $_[0] =~ s!\\([\\"abfnrtv]|[0-3][0-7]{2})!$GIT_ESC{$1}//chr(oct($1))!ge;
56 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
57 '\\'.($ESC_GIT{$1}||sprintf("%03o",ord($1)))/egs) {
64 my ($class, $git_dir) = @_;
65 # may contain {-tmp} field for File::Temp::Dir
66 bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
70 my ($self, $path) = @_;
71 $self->{-git_path}->{$path} ||= do {
73 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
75 # git prior to 2.5.0 did not understand --git-path
76 if ($str eq "--git-path\n$path") {
77 $str = "$self->{git_dir}/$path";
83 sub alternates_changed {
85 my $alt = git_path($self, 'objects/info/alternates');
86 my @st = stat($alt) or return 0;
88 # can't rely on 'q' on some 32-bit builds, but `d' works
89 my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
90 return 0 if $self->{alt_st} eq $st;
91 $self->{alt_st} = $st; # always a true value
96 my $fh = $self->{err_c} or return;
97 sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
98 defined(sysread($fh, my $buf, -s $fh)) or
99 $self->fail("sysread failed: $!");
104 my ($self, $batch, $in, $out, $pid, $err) = @_;
106 if (defined $err) { # "err_c"
107 my $fh = $self->{$err};
108 sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
109 truncate($fh, 0) or $self->fail("truncate failed: $!");
114 pipe($out_r, $out_w) or $self->fail("pipe failed: $!");
115 my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
116 qw(-c core.abbrev=40 cat-file), $batch);
117 my $redir = { 0 => $out_r };
119 my $id = "git.$self->{git_dir}$batch.err";
120 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
124 my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
126 $self->{"$pid.owner"} = $$;
127 $out_w->autoflush(1);
128 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
129 fcntl($out_w, 1031, 4096);
130 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
132 $self->{$out} = $out_w;
133 $self->{$in} = $in_r;
136 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
139 my ($fh, $rbuf, $len) = @_;
140 my $left = $len - length($$rbuf);
143 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
146 } elsif (defined($r)) { # EOF
149 next if ($! == EAGAIN and poll_in($fh));
150 next if $! == EINTR; # may be set by sysread or poll_in
151 return; # unrecoverable error
154 \substr($$rbuf, 0, $len, '');
157 sub my_readline ($$) {
158 my ($fh, $rbuf) = @_;
160 if ((my $n = index($$rbuf, "\n")) >= 0) {
161 return substr($$rbuf, 0, $n + 1, '');
163 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
166 # return whatever's left on EOF
167 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
169 next if ($! == EAGAIN and poll_in($fh));
170 next if $! == EINTR; # may be set by sysread or poll_in
171 return; # unrecoverable error
175 sub cat_async_retry ($$$$$) {
176 my ($self, $inflight, $req, $cb, $arg) = @_;
178 # {inflight} may be non-existent, but if it isn't we delete it
179 # here to prevent cleanup() from waiting:
180 delete $self->{inflight};
183 $self->{inflight} = $inflight;
184 batch_prepare($self);
186 for (my $i = 0; $i < @$inflight; $i += 3) {
187 $buf .= "$inflight->[$i]\n";
189 print { $self->{out} } $buf or $self->fail("write error: $!");
190 unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
192 cat_async_step($self, $inflight); # take one step
195 sub cat_async_step ($$) {
196 my ($self, $inflight) = @_;
197 die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
198 my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
199 my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
200 my ($bref, $oid, $type, $size);
201 my $head = my_readline($self->{in}, $rbuf);
202 # ->fail may be called via Gcf2Client.pm
203 if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
204 ($oid, $type, $size) = ($1, $2, $3 + 0);
205 $bref = my_read($self->{in}, $rbuf, $size + 1) or
206 $self->fail(defined($bref) ? 'read EOF' : "read: $!");
207 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
208 } elsif ($head =~ s/ missing\n//s) {
210 # ref($req) indicates it's already been retried
211 # -gcf2 retries internally, so it never hits this path:
212 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
213 return cat_async_retry($self, $inflight,
217 $oid = ref($req) ? $$req : $req if $oid eq '';
219 my $err = $! ? " ($!)" : '';
220 $self->fail("bad result from async cat-file: $head$err");
222 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
223 eval { $cb->($bref, $oid, $type, $size, $arg) };
224 warn "E: $oid: $@\n" if $@;
227 sub cat_async_wait ($) {
229 my $inflight = $self->{inflight} or return;
230 while (scalar(@$inflight)) {
231 cat_async_step($self, $inflight);
235 sub batch_prepare ($) {
236 _bidi_pipe($_[0], qw(--batch in out pid));
240 my ($bref, $oid, $type, $size, $result) = @_;
241 @$result = ($bref, $oid, $type, $size);
245 my ($self, $oid) = @_;
247 cat_async($self, $oid, \&_cat_file_cb, $result);
248 cat_async_wait($self);
249 wantarray ? @$result : $result->[0];
252 sub check_async_step ($$) {
253 my ($self, $inflight_c) = @_;
254 die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
255 my ($req, $cb, $arg) = splice(@$inflight_c, 0, 3);
256 my $rbuf = delete($self->{chk_rbuf}) // \(my $new = '');
257 chomp(my $line = my_readline($self->{in_c}, $rbuf));
258 my ($hex, $type, $size) = split(/ /, $line);
260 # Future versions of git.git may have type=ambiguous, but for now,
261 # we must handle 'dangling' below (and maybe some other oddball
263 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
264 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
265 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
266 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
268 $self->{chk_rbuf} = $rbuf if $$rbuf ne '';
269 eval { $cb->($hex, $type, $size, $arg, $self) };
270 warn "E: check($req) $@\n" if $@;
273 sub check_async_wait ($) {
275 my $inflight_c = $self->{inflight_c} or return;
276 while (scalar(@$inflight_c)) {
277 check_async_step($self, $inflight_c);
281 sub check_async_begin ($) {
283 cleanup($self) if alternates_changed($self);
284 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
285 die 'BUG: already in async check' if $self->{inflight_c};
286 $self->{inflight_c} = [];
289 sub check_async ($$$$) {
290 my ($self, $oid, $cb, $arg) = @_;
291 my $inflight_c = $self->{inflight_c} // check_async_begin($self);
292 while (scalar(@$inflight_c) >= MAX_INFLIGHT) {
293 check_async_step($self, $inflight_c);
295 print { $self->{out_c} } $oid, "\n" or $self->fail("write error: $!");
296 push(@$inflight_c, $oid, $cb, $arg);
299 sub _check_cb { # check_async callback
300 my ($hex, $type, $size, $result) = @_;
301 @$result = ($hex, $type, $size);
305 my ($self, $oid) = @_;
307 check_async($self, $oid, \&_check_cb, $result);
308 check_async_wait($self);
309 my ($hex, $type, $size) = @$result;
311 # Future versions of git.git may show 'ambiguous', but for now,
312 # we must handle 'dangling' below (and maybe some other oddball
314 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
315 return if $type eq 'missing' || $type eq 'ambiguous';
316 return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
317 ($hex, $type, $size);
321 my ($self, $rbuf, $in, $out, $pid, $err) = @_;
322 delete @$self{($rbuf, $in, $out)};
323 delete $self->{$err} if $err; # `err_c'
325 # GitAsyncCat::event_step may delete {pid}
326 my $p = delete $self->{$pid} or return;
327 dwaitpid($p) if $$ == $self->{"$pid.owner"};
330 sub cat_async_abort ($) {
332 if (my $inflight = $self->{inflight}) {
334 my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
335 $req =~ s/ .*//; # drop git_dir for Gcf2Client
336 eval { $cb->(undef, $req, undef, undef, $arg) };
337 warn "E: $req: $@ (in abort)\n" if $@;
339 delete $self->{cat_rbuf};
340 delete $self->{inflight};
345 sub fail { # may be augmented in subclasses
346 my ($self, $msg) = @_;
347 cat_async_abort($self);
348 croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
351 # $git->popen(qw(show f00)); # or
352 # $git->popen(qw(show f00), { GIT_CONFIG => ... }, { 2 => ... });
354 my ($self, $cmd) = splice(@_, 0, 2);
355 $cmd = [ 'git', "--git-dir=$self->{git_dir}",
356 ref($cmd) ? @$cmd : ($cmd, grep { defined && !ref } @_) ];
357 popen_rd($cmd, grep { !defined || ref } @_); # env and opt
360 # same args as popen above
365 close $fh; # caller should check $?
370 close $fh; # caller should check $?
378 substr($_, length('--max-age='), -1)
379 } $self->qx('rev-parse', map { "--since=$_" } @_);
382 # check_async and cat_async may trigger the other, so ensure they're
383 # both completely done by using this:
384 sub async_wait_all ($) {
386 while (scalar(@{$self->{inflight_c} // []}) ||
387 scalar(@{$self->{inflight} // []})) {
388 $self->check_async_wait;
389 $self->cat_async_wait;
393 # returns true if there are pending "git cat-file" processes
396 local $in_cleanup = 1;
397 delete $self->{async_cat};
398 async_wait_all($self);
399 delete $self->{inflight};
400 delete $self->{inflight_c};
401 _destroy($self, qw(cat_rbuf in out pid));
402 _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
403 !!($self->{pid} || $self->{pid_c});
407 # assuming a well-maintained repo, this should be a somewhat
408 # accurate estimation of its size
409 # TODO: show this in the WWW UI as a hint to potential cloners
413 my $pack_dir = git_path($self, 'objects/pack');
414 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
420 sub DESTROY { cleanup(@_) }
425 # don't show full FS path, basename should be OK:
426 if ($self->{git_dir} =~ m!/([^/]+)(?:/*\.git/*)?\z!) {
429 wantarray ? ($ret) : $ret;
432 sub host_prefix_url ($$) {
433 my ($env, $url) = @_;
434 return $url if index($url, '//') >= 0;
435 my $scheme = $env->{'psgi.url_scheme'};
436 my $host_port = $env->{HTTP_HOST} //
437 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
438 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
442 my ($self, $env) = @_;
443 if (my $urls = $self->{cgit_url}) {
444 return map { host_prefix_url($env, $_) } @$urls;
449 sub cat_async_begin {
451 cleanup($self) if $self->alternates_changed;
452 $self->batch_prepare;
453 die 'BUG: already in async' if $self->{inflight};
454 $self->{inflight} = [];
457 sub cat_async ($$$;$) {
458 my ($self, $oid, $cb, $arg) = @_;
459 my $inflight = $self->{inflight} // cat_async_begin($self);
460 while (scalar(@$inflight) >= MAX_INFLIGHT) {
461 cat_async_step($self, $inflight);
463 print { $self->{out} } $oid, "\n" or $self->fail("write error: $!");
464 push(@$inflight, $oid, $cb, $arg);
467 # returns the modified time of a git repo, same as the "modified" field
468 # of a grokmirror manifest
470 # committerdate:unix is git 2.9.4+ (2017-05-05), so using raw instead
471 my $fh = popen($_[0], qw[for-each-ref --sort=-committerdate
472 --format=%(committerdate:raw) --count=1]);
473 (split(/ /, <$fh> // time))[0] + 0; # integerize for JSON
476 # for grokmirror, which doesn't read gitweb.description
477 # templates/hooks--update.sample and git-multimail in git.git
478 # only match "Unnamed repository", not the full contents of
479 # templates/this--description in git.git
481 my ($self, $epoch, $default_desc) = @_;
482 my $fh = $self->popen('show-ref');
483 my $dig = Digest::SHA->new(1);
484 while (read($fh, my $buf, 65536)) {
487 close $fh or return; # empty, uninitialized git repo
488 undef $fh; # for open, below
489 my $git_dir = $self->{git_dir};
491 fingerprint => $dig->hexdigest,
493 modified => modified($self),
495 chomp(my $owner = $self->qx('config', 'gitweb.owner'));
496 utf8::decode($owner);
497 $ent->{owner} = $owner eq '' ? undef : $owner;
499 if (open($fh, '<', "$git_dir/description")) {
501 chomp($desc = <$fh>);
504 $desc = 'Unnamed repository' if $desc eq '';
505 if (defined $epoch && $desc =~ /\AUnnamed repository/) {
506 $desc = "$default_desc [epoch $epoch]";
508 $ent->{description} = $desc;
509 if (open($fh, '<', "$git_dir/objects/info/alternates")) {
510 # n.b.: GitPython doesn't seem to handle comments or C-quoted
511 # strings like native git does; and we don't for now, either.
513 chomp(my @alt = <$fh>);
515 # grokmirror only supports 1 alternate for "reference",
516 if (scalar(@alt) == 1) {
517 my $objdir = "$git_dir/objects";
518 my $ref = File::Spec->rel2abs($alt[0], $objdir);
519 $ref =~ s!/[^/]+/?\z!!; # basename
520 $ent->{reference} = $ref;
532 PublicInbox::Git - git wrapper
540 use PublicInbox::Git;
541 chomp(my $git_dir = `git rev-parse --git-dir`);
542 $git_dir or die "GIT_DIR= must be specified\n";
543 my $git = PublicInbox::Git->new($git_dir);
547 Unstable API outside of the L</new> method.
548 It requires L<git(1)> to be installed.
556 my $git = PublicInbox::Git->new($git_dir);
558 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
559 This is the only public API method we support. Everything else
560 in this module is subject to change.
564 L<Git>, L<PublicInbox::Import>
568 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
570 The mail archives are hosted at L<https://public-inbox.org/meta/>
574 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
576 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>