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);
18 use Time::HiRes qw(stat);
19 use PublicInbox::Spawn qw(popen_rd);
20 use PublicInbox::Tmpfile;
23 our @EXPORT_OK = qw(git_unquote git_quote);
24 our $PIPE_BUFSIZ = 65536; # Linux default
27 use constant MAX_INFLIGHT =>
28 (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
30 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
43 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
46 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
48 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
50 $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
51 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
56 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
57 '\\'.($ESC_GIT{$1}||sprintf("%0o",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 fail($self, "sysseek failed: $!");
98 defined(sysread($fh, my $buf, -s $fh)) or
99 fail($self, "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 fail($self, "sysseek failed: $!");
109 truncate($fh, 0) or fail($self, "truncate failed: $!");
114 pipe($out_r, $out_w) or fail($self, "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 fail($self, "tmpfile($id): $!");
124 my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
126 $out_w->autoflush(1);
127 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
128 fcntl($out_w, 1031, 4096);
129 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
131 $self->{$out} = $out_w;
132 $self->{$in} = $in_r;
136 my ($fh, $rbuf, $len) = @_;
137 my $left = $len - length($$rbuf);
140 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
144 next if (!defined($r) && $! == EINTR);
148 \substr($$rbuf, 0, $len, '');
151 sub my_readline ($$) {
152 my ($fh, $rbuf) = @_;
154 if ((my $n = index($$rbuf, "\n")) >= 0) {
155 return substr($$rbuf, 0, $n + 1, '');
157 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
158 next if $r || (!defined($r) && $! == EINTR);
159 return defined($r) ? '' : undef; # EOF or error
163 sub cat_async_retry ($$$$$) {
164 my ($self, $inflight, $req, $cb, $arg) = @_;
166 # {inflight} may be non-existent, but if it isn't we delete it
167 # here to prevent cleanup() from waiting:
168 delete $self->{inflight};
171 $self->{inflight} = $inflight;
172 batch_prepare($self);
174 for (my $i = 0; $i < @$inflight; $i += 3) {
175 $buf .= "$inflight->[$i]\n";
177 print { $self->{out} } $buf or fail($self, "write error: $!");
178 unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
180 cat_async_step($self, $inflight); # take one step
183 sub cat_async_step ($$) {
184 my ($self, $inflight) = @_;
185 die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
186 my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
187 my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
188 my ($bref, $oid, $type, $size);
189 my $head = my_readline($self->{in}, $rbuf);
190 # ->fail may be called via Gcf2Client.pm
191 if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
192 ($oid, $type, $size) = ($1, $2, $3 + 0);
193 $bref = my_read($self->{in}, $rbuf, $size + 1) or
194 $self->fail(defined($bref) ? 'read EOF' : "read: $!");
195 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
196 } elsif ($head =~ s/ missing\n//s) {
198 # ref($req) indicates it's already been retried
199 # -gcf2 retries internally, so it never hits this path:
200 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
201 return cat_async_retry($self, $inflight,
205 $oid = ref($req) ? $$req : $req if $oid eq '';
207 $self->fail("Unexpected result from async git cat-file: $head");
209 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
210 eval { $cb->($bref, $oid, $type, $size, $arg) };
211 warn "E: $oid: $@\n" if $@;
214 sub cat_async_wait ($) {
216 my $inflight = $self->{inflight} or return;
217 while (scalar(@$inflight)) {
218 cat_async_step($self, $inflight);
222 sub batch_prepare ($) {
223 _bidi_pipe($_[0], qw(--batch in out pid));
227 my ($bref, undef, undef, $size, $result) = @_;
228 @$result = ($bref, $size);
232 my ($self, $oid, $sizeref) = @_;
234 cat_async($self, $oid, \&_cat_file_cb, $result);
235 cat_async_wait($self);
236 $$sizeref = $result->[1] if $sizeref;
240 sub check_async_step ($$) {
241 my ($self, $inflight_c) = @_;
242 die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
243 my ($req, $cb, $arg) = splice(@$inflight_c, 0, 3);
244 my $rbuf = delete($self->{chk_rbuf}) // \(my $new = '');
245 chomp(my $line = my_readline($self->{in_c}, $rbuf));
246 my ($hex, $type, $size) = split(/ /, $line);
248 # Future versions of git.git may have type=ambiguous, but for now,
249 # we must handle 'dangling' below (and maybe some other oddball
251 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
252 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
253 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
254 fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
256 $self->{chk_rbuf} = $rbuf if $$rbuf ne '';
257 eval { $cb->($hex, $type, $size, $arg, $self) };
258 warn "E: check($req) $@\n" if $@;
261 sub check_async_wait ($) {
263 my $inflight_c = $self->{inflight_c} or return;
264 while (scalar(@$inflight_c)) {
265 check_async_step($self, $inflight_c);
269 sub check_async_begin ($) {
271 cleanup($self) if alternates_changed($self);
272 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
273 die 'BUG: already in async check' if $self->{inflight_c};
274 $self->{inflight_c} = [];
277 sub check_async ($$$$) {
278 my ($self, $oid, $cb, $arg) = @_;
279 my $inflight_c = $self->{inflight_c} // check_async_begin($self);
280 while (scalar(@$inflight_c) >= MAX_INFLIGHT) {
281 check_async_step($self, $inflight_c);
283 print { $self->{out_c} } $oid, "\n" or fail($self, "write error: $!");
284 push(@$inflight_c, $oid, $cb, $arg);
287 sub _check_cb { # check_async callback
288 my ($hex, $type, $size, $result) = @_;
289 @$result = ($hex, $type, $size);
293 my ($self, $oid) = @_;
295 check_async($self, $oid, \&_check_cb, $result);
296 check_async_wait($self);
297 my ($hex, $type, $size) = @$result;
299 # Future versions of git.git may show 'ambiguous', but for now,
300 # we must handle 'dangling' below (and maybe some other oddball
302 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
303 return if $type eq 'missing' || $type eq 'ambiguous';
304 return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
305 ($hex, $type, $size);
309 my ($self, $rbuf, $in, $out, $pid, $err) = @_;
310 delete @$self{($rbuf, $in, $out)};
311 delete $self->{$err} if $err; # `err_c'
313 # GitAsyncCat::event_step may delete {pid}
314 my $p = delete $self->{$pid} or return;
316 # PublicInbox::DS may not be loaded
317 eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
318 waitpid($p, 0) if $@; # wait synchronously if not in event loop
321 sub cat_async_abort ($) {
323 if (my $inflight = $self->{inflight}) {
325 my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
326 $req =~ s/ .*//; # drop git_dir for Gcf2Client
327 eval { $cb->(undef, $req, undef, undef, $arg) };
328 warn "E: $req: $@ (in abort)\n" if $@;
330 delete $self->{cat_rbuf};
331 delete $self->{inflight};
337 my ($self, $msg) = @_;
338 cat_async_abort($self);
339 croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
343 my ($self, @cmd) = @_;
344 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
349 my ($self, @cmd) = @_;
350 my $fh = $self->popen(@cmd);
352 return <$fh> if wantarray;
357 # check_async and cat_async may trigger the other, so ensure they're
358 # both completely done by using this:
359 sub async_wait_all ($) {
361 while (scalar(@{$self->{inflight_c} // []}) ||
362 scalar(@{$self->{inflight} // []})) {
363 $self->check_async_wait;
364 $self->cat_async_wait;
368 # returns true if there are pending "git cat-file" processes
371 local $in_cleanup = 1;
372 delete $self->{async_cat};
373 async_wait_all($self);
374 delete $self->{inflight};
375 delete $self->{inflight_c};
376 _destroy($self, qw(cat_rbuf in out pid));
377 _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
378 !!($self->{pid} || $self->{pid_c});
382 # assuming a well-maintained repo, this should be a somewhat
383 # accurate estimation of its size
384 # TODO: show this in the WWW UI as a hint to potential cloners
388 my $pack_dir = git_path($self, 'objects/pack');
389 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
395 sub DESTROY { cleanup(@_) }
400 # don't show full FS path, basename should be OK:
401 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
402 $ret = "/path/to/$1";
404 wantarray ? ($ret) : $ret;
407 sub host_prefix_url ($$) {
408 my ($env, $url) = @_;
409 return $url if index($url, '//') >= 0;
410 my $scheme = $env->{'psgi.url_scheme'};
411 my $host_port = $env->{HTTP_HOST} //
412 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
413 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
417 my ($self, $env) = @_;
418 if (my $urls = $self->{cgit_url}) {
419 return map { host_prefix_url($env, $_) } @$urls;
424 sub cat_async_begin {
426 cleanup($self) if $self->alternates_changed;
427 $self->batch_prepare;
428 die 'BUG: already in async' if $self->{inflight};
429 $self->{inflight} = [];
432 sub cat_async ($$$;$) {
433 my ($self, $oid, $cb, $arg) = @_;
434 my $inflight = $self->{inflight} // cat_async_begin($self);
435 while (scalar(@$inflight) >= MAX_INFLIGHT) {
436 cat_async_step($self, $inflight);
438 print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
439 push(@$inflight, $oid, $cb, $arg);
443 my ($self, $oid, $cb, $arg) = @_;
444 if (my $inflight = $self->{inflight}) {
445 # we could use MAX_INFLIGHT here w/o the halving,
446 # but lets not allow one client to monopolize a git process
447 if (scalar(@$inflight) < int(MAX_INFLIGHT/2)) {
448 print { $self->{out} } $oid, "\n" or
449 fail($self, "write error: $!");
450 return push(@$inflight, $oid, $cb, $arg);
456 sub extract_cmt_time {
457 my ($bref, undef, undef, undef, $modified) = @_;
459 if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
460 my $cmt_time = $1 + 0;
461 $$modified = $cmt_time if $cmt_time > $$modified;
465 # returns the modified time of a git repo, same as the "modified" field
466 # of a grokmirror manifest
470 my $fh = popen($self, qw(rev-parse --branches));
472 while (my $oid = <$fh>) {
474 cat_async($self, $oid, \&extract_cmt_time, \$modified);
476 cat_async_wait($self);
480 # for grokmirror, which doesn't read gitweb.description
481 # templates/hooks--update.sample and git-multimail in git.git
482 # only match "Unnamed repository", not the full contents of
483 # templates/this--description in git.git
485 my ($self, $epoch, $default_desc) = @_;
486 my ($fh, $pid) = $self->popen('show-ref');
487 my $dig = Digest::SHA->new(1);
488 while (read($fh, my $buf, 65536)) {
493 return if $?; # empty, uninitialized git repo
494 my $git_dir = $self->{git_dir};
496 fingerprint => $dig->hexdigest,
498 modified => modified($self),
500 chomp(my $owner = $self->qx('config', 'gitweb.owner'));
501 utf8::decode($owner);
502 $ent->{owner} = $owner eq '' ? undef : $owner;
504 if (open($fh, '<', "$git_dir/description")) {
506 chomp($desc = <$fh>);
509 $desc = 'Unnamed repository' if $desc eq '';
510 if (defined $epoch && $desc =~ /\AUnnamed repository/) {
511 $desc = "$default_desc [epoch $epoch]";
513 $ent->{description} = $desc;
514 if (open($fh, '<', "$git_dir/objects/info/alternates")) {
515 # n.b.: GitPython doesn't seem to handle comments or C-quoted
516 # strings like native git does; and we don't for now, either.
518 chomp(my @alt = <$fh>);
520 # grokmirror only supports 1 alternate for "reference",
521 if (scalar(@alt) == 1) {
522 my $objdir = "$git_dir/objects";
523 my $ref = File::Spec->rel2abs($alt[0], $objdir);
524 $ref =~ s!/[^/]+/?\z!!; # basename
525 $ent->{reference} = $ref;
537 PublicInbox::Git - git wrapper
545 use PublicInbox::Git;
546 chomp(my $git_dir = `git rev-parse --git-dir`);
547 $git_dir or die "GIT_DIR= must be specified\n";
548 my $git = PublicInbox::Git->new($git_dir);
552 Unstable API outside of the L</new> method.
553 It requires L<git(1)> to be installed.
561 my $git = PublicInbox::Git->new($git_dir);
563 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
564 This is the only public API method we support. Everything else
565 in this module is subject to change.
569 L<Git>, L<PublicInbox::Import>
573 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
575 The mail archives are hosted at L<https://public-inbox.org/meta/>
579 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
581 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>