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;
20 our @EXPORT_OK = qw(git_unquote git_quote);
21 our $PIPE_BUFSIZ = 65536; # Linux default
24 use constant MAX_INFLIGHT =>
25 (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
27 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
40 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
43 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
45 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
47 $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
48 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
53 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
54 '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
61 my ($class, $git_dir) = @_;
62 # may contain {-tmp} field for File::Temp::Dir
63 bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
67 my ($self, $path) = @_;
68 $self->{-git_path}->{$path} ||= do {
70 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
72 # git prior to 2.5.0 did not understand --git-path
73 if ($str eq "--git-path\n$path") {
74 $str = "$self->{git_dir}/$path";
80 sub alternates_changed {
82 my $alt = git_path($self, 'objects/info/alternates');
83 my @st = stat($alt) or return 0;
85 # can't rely on 'q' on some 32-bit builds, but `d' works
86 my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
87 return 0 if $self->{alt_st} eq $st;
88 $self->{alt_st} = $st; # always a true value
93 my $fh = $self->{err_c} or return;
94 sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
95 defined(sysread($fh, my $buf, -s $fh)) or
96 fail($self, "sysread failed: $!");
101 my ($self, $batch, $in, $out, $pid, $err) = @_;
103 if (defined $err) { # "err_c"
104 my $fh = $self->{$err};
105 sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
106 truncate($fh, 0) or fail($self, "truncate failed: $!");
111 pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
112 my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
113 qw(-c core.abbrev=40 cat-file), $batch);
114 my $redir = { 0 => $out_r };
116 my $id = "git.$self->{git_dir}$batch.err";
117 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
121 my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
123 $out_w->autoflush(1);
124 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
125 fcntl($out_w, 1031, 4096);
126 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
128 $self->{$out} = $out_w;
129 $self->{$in} = $in_r;
133 my ($fh, $rbuf, $len) = @_;
134 my $left = $len - length($$rbuf);
137 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
141 next if (!defined($r) && $! == EINTR);
145 \substr($$rbuf, 0, $len, '');
148 sub my_readline ($$) {
149 my ($fh, $rbuf) = @_;
151 if ((my $n = index($$rbuf, "\n")) >= 0) {
152 return substr($$rbuf, 0, $n + 1, '');
154 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
155 next if $r || (!defined($r) && $! == EINTR);
156 return defined($r) ? '' : undef; # EOF or error
160 sub cat_async_retry ($$$$$) {
161 my ($self, $inflight, $req, $cb, $arg) = @_;
163 # {inflight} may be non-existent, but if it isn't we delete it
164 # here to prevent cleanup() from waiting:
165 delete $self->{inflight};
168 $self->{inflight} = $inflight;
169 batch_prepare($self);
171 for (my $i = 0; $i < @$inflight; $i += 3) {
172 $buf .= "$inflight->[$i]\n";
174 print { $self->{out} } $buf or fail($self, "write error: $!");
175 unshift(@$inflight, \$req, $cb, $arg); # \$ref to indicate retried
177 cat_async_step($self, $inflight); # take one step
180 sub cat_async_step ($$) {
181 my ($self, $inflight) = @_;
182 die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
183 my ($req, $cb, $arg) = splice(@$inflight, 0, 3);
184 my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
185 my ($bref, $oid, $type, $size);
186 my $head = my_readline($self->{in}, $rbuf);
187 if ($head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/) {
188 ($oid, $type, $size) = ($1, $2, $3 + 0);
189 $bref = my_read($self->{in}, $rbuf, $size + 1) or
190 fail($self, defined($bref) ? 'read EOF' : "read: $!");
191 chop($$bref) eq "\n" or fail($self, 'LF missing after blob');
192 } elsif ($head =~ / missing$/) {
193 # ref($req) indicates it's already been retried
194 if (!ref($req) && !$in_cleanup && alternates_changed($self)) {
195 return cat_async_retry($self, $inflight,
199 $oid = ref($req) ? $$req : $req;
201 fail($self, "Unexpected result from async git cat-file: $head");
203 eval { $cb->($bref, $oid, $type, $size, $arg) };
204 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
205 warn "E: $oid: $@\n" if $@;
208 sub cat_async_wait ($) {
210 my $inflight = delete $self->{inflight} or return;
211 while (scalar(@$inflight)) {
212 cat_async_step($self, $inflight);
216 sub batch_prepare ($) {
217 _bidi_pipe($_[0], qw(--batch in out pid));
221 my ($bref, undef, undef, $size, $result) = @_;
222 @$result = ($bref, $size);
226 my ($self, $oid, $sizeref) = @_;
228 cat_async($self, $oid, \&_cat_file_cb, $result);
229 cat_async_wait($self);
230 $$sizeref = $result->[1] if $sizeref;
234 sub check_async_step ($$) {
235 my ($self, $inflight_c) = @_;
236 die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
237 my ($req, $cb, $arg) = splice(@$inflight_c, 0, 3);
238 my $rbuf = delete($self->{rbuf_c}) // \(my $new = '');
239 chomp(my $line = my_readline($self->{in_c}, $rbuf));
240 my ($hex, $type, $size) = split(/ /, $line);
242 # Future versions of git.git may have type=ambiguous, but for now,
243 # we must handle 'dangling' below (and maybe some other oddball
245 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
246 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
247 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
248 fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
250 eval { $cb->($hex, $type, $size, $arg, $self) };
251 warn "E: check($req) $@\n" if $@;
252 $self->{rbuf_c} = $rbuf if $$rbuf ne '';
255 sub check_async_wait ($) {
257 my $inflight_c = delete $self->{inflight_c} or return;
258 while (scalar(@$inflight_c)) {
259 check_async_step($self, $inflight_c);
263 sub check_async_begin ($) {
265 cleanup($self) if alternates_changed($self);
266 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
267 die 'BUG: already in async check' if $self->{inflight_c};
268 $self->{inflight_c} = [];
271 sub check_async ($$$$) {
272 my ($self, $oid, $cb, $arg) = @_;
273 my $inflight_c = $self->{inflight_c} // check_async_begin($self);
274 if (scalar(@$inflight_c) >= MAX_INFLIGHT) {
275 check_async_step($self, $inflight_c);
277 print { $self->{out_c} } $oid, "\n" or fail($self, "write error: $!");
278 push(@$inflight_c, $oid, $cb, $arg);
281 sub _check_cb { # check_async callback
282 my ($hex, $type, $size, $result) = @_;
283 @$result = ($hex, $type, $size);
287 my ($self, $oid) = @_;
289 check_async($self, $oid, \&_check_cb, $result);
290 check_async_wait($self);
291 my ($hex, $type, $size) = @$result;
293 # Future versions of git.git may show 'ambiguous', but for now,
294 # we must handle 'dangling' below (and maybe some other oddball
296 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
297 return if $type eq 'missing' || $type eq 'ambiguous';
298 return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
299 ($hex, $type, $size);
303 my ($self, $rbuf, $in, $out, $pid, $err) = @_;
304 my $p = delete $self->{$pid} or return;
305 delete @$self{($rbuf, $in, $out)};
306 delete $self->{$err} if $err; # `err_c'
308 # PublicInbox::DS may not be loaded
309 eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
310 waitpid($p, 0) if $@; # wait synchronously if not in event loop
313 sub cat_async_abort ($) {
315 my $inflight = delete $self->{inflight} or die 'BUG: not in async';
320 my ($self, $msg) = @_;
321 $self->{inflight} ? cat_async_abort($self) : cleanup($self);
326 my ($self, @cmd) = @_;
327 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
332 my ($self, @cmd) = @_;
333 my $fh = $self->popen(@cmd);
335 return <$fh> if wantarray;
340 # returns true if there are pending "git cat-file" processes
343 local $in_cleanup = 1;
344 delete $self->{async_cat};
345 check_async_wait($self);
346 cat_async_wait($self);
347 _destroy($self, qw(cat_rbuf in out pid));
348 _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
349 !!($self->{pid} || $self->{pid_c});
352 # assuming a well-maintained repo, this should be a somewhat
353 # accurate estimation of its size
354 # TODO: show this in the WWW UI as a hint to potential cloners
358 my $pack_dir = git_path($self, 'objects/pack');
359 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
365 sub DESTROY { cleanup(@_) }
370 # don't show full FS path, basename should be OK:
371 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
372 $ret = "/path/to/$1";
374 wantarray ? ($ret) : $ret;
377 sub host_prefix_url ($$) {
378 my ($env, $url) = @_;
379 return $url if index($url, '//') >= 0;
380 my $scheme = $env->{'psgi.url_scheme'};
381 my $host_port = $env->{HTTP_HOST} //
382 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
383 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
387 my ($self, $env) = @_;
388 if (my $urls = $self->{cgit_url}) {
389 return map { host_prefix_url($env, $_) } @$urls;
394 sub cat_async_begin {
396 cleanup($self) if alternates_changed($self);
397 batch_prepare($self);
398 die 'BUG: already in async' if $self->{inflight};
399 $self->{inflight} = [];
402 sub cat_async ($$$;$) {
403 my ($self, $oid, $cb, $arg) = @_;
404 my $inflight = $self->{inflight} // cat_async_begin($self);
405 if (scalar(@$inflight) >= MAX_INFLIGHT) {
406 cat_async_step($self, $inflight);
409 print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
410 push(@$inflight, $oid, $cb, $arg);
413 sub extract_cmt_time {
414 my ($bref, undef, undef, undef, $modified) = @_;
416 if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
417 my $cmt_time = $1 + 0;
418 $$modified = $cmt_time if $cmt_time > $$modified;
422 # returns the modified time of a git repo, same as the "modified" field
423 # of a grokmirror manifest
427 my $fh = popen($self, qw(rev-parse --branches));
429 while (my $oid = <$fh>) {
431 cat_async($self, $oid, \&extract_cmt_time, \$modified);
433 cat_async_wait($self);
443 PublicInbox::Git - git wrapper
451 use PublicInbox::Git;
452 chomp(my $git_dir = `git rev-parse --git-dir`);
453 $git_dir or die "GIT_DIR= must be specified\n";
454 my $git = PublicInbox::Git->new($git_dir);
458 Unstable API outside of the L</new> method.
459 It requires L<git(1)> to be installed.
467 my $git = PublicInbox::Git->new($git_dir);
469 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
470 This is the only public API method we support. Everything else
471 in this module is subject to change.
475 L<Git>, L<PublicInbox::Import>
479 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
481 The mail archives are hosted at L<https://public-inbox.org/meta/>
485 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
487 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>