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;
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);
20 our $PIPE_BUFSIZ = 65536; # Linux default
22 use constant MAX_INFLIGHT =>
23 (($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF()) * 3)
25 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
38 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
41 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
43 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
45 $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
46 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
51 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
52 '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
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
65 my ($self, $path) = @_;
66 $self->{-git_path}->{$path} ||= do {
68 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
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";
78 sub alternates_changed {
80 my $alt = git_path($self, 'objects/info/alternates');
81 my @st = stat($alt) or return 0;
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
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: $!");
99 my ($self, $batch, $in, $out, $pid, $err) = @_;
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: $!");
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 };
114 my $id = "git.$self->{git_dir}$batch.err";
115 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
119 my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
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';
126 $self->{$out} = $out_w;
127 $self->{$in} = $in_r;
131 my ($fh, $rbuf, $len) = @_;
132 my $left = $len - length($$rbuf);
135 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
139 next if (!defined($r) && $! == EINTR);
143 \substr($$rbuf, 0, $len, '');
146 sub my_readline ($$) {
147 my ($fh, $rbuf) = @_;
149 if ((my $n = index($$rbuf, "\n")) >= 0) {
150 return substr($$rbuf, 0, $n + 1, '');
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
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$/) {
174 fail($self, "Unexpected result from async git cat-file: $head");
176 eval { $cb->($bref, $oid, $type, $size, $arg) };
177 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
178 warn "E: $oid: $@\n" if $@;
181 sub cat_async_wait ($) {
183 my $inflight = delete $self->{inflight} or return;
184 while (scalar(@$inflight)) {
185 cat_async_step($self, $inflight);
189 sub batch_prepare ($) {
190 _bidi_pipe($_[0], qw(--batch in out pid));
194 my ($self, $obj, $sizeref) = @_;
195 my ($retried, $head, $rbuf);
196 cat_async_wait($self);
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)) {
210 $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
211 fail($self, "Unexpected result from git cat-file: $head");
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');
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);
230 # Future versions of git.git may show 'ambiguous', but for now,
231 # we must handle 'dangling' below (and maybe some other oddball
233 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
234 return if $type eq 'missing' || $type eq 'ambiguous';
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;
242 ($hex, $type, $size);
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'
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
256 sub cat_async_abort ($) {
258 my $inflight = delete $self->{inflight} or die 'BUG: not in async';
263 my ($self, $msg) = @_;
264 $self->{inflight} ? cat_async_abort($self) : cleanup($self);
269 my ($self, @cmd) = @_;
270 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
275 my ($self, @cmd) = @_;
276 my $fh = $self->popen(@cmd);
278 return <$fh> if wantarray;
283 # returns true if there are pending "git cat-file" processes
286 cat_async_wait($self);
287 _destroy($self, qw(cat_rbuf in out pid));
288 _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
289 !!($self->{pid} || $self->{pid_c});
292 # assuming a well-maintained repo, this should be a somewhat
293 # accurate estimation of its size
294 # TODO: show this in the WWW UI as a hint to potential cloners
298 my $pack_dir = git_path($self, 'objects/pack');
299 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
305 sub DESTROY { cleanup(@_) }
310 # don't show full FS path, basename should be OK:
311 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
312 $ret = "/path/to/$1";
314 wantarray ? ($ret) : $ret;
317 sub host_prefix_url ($$) {
318 my ($env, $url) = @_;
319 return $url if index($url, '//') >= 0;
320 my $scheme = $env->{'psgi.url_scheme'};
321 my $host_port = $env->{HTTP_HOST} //
322 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
323 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
327 my ($self, $env) = @_;
328 if (my $urls = $self->{cgit_url}) {
329 return map { host_prefix_url($env, $_) } @$urls;
334 sub cat_async_begin {
336 cleanup($self) if alternates_changed($self);
337 batch_prepare($self);
338 die 'BUG: already in async' if $self->{inflight};
339 $self->{inflight} = [];
342 sub cat_async ($$$;$) {
343 my ($self, $oid, $cb, $arg) = @_;
344 my $inflight = $self->{inflight} // cat_async_begin($self);
345 if (scalar(@$inflight) >= MAX_INFLIGHT) {
346 cat_async_step($self, $inflight);
349 print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
350 push(@$inflight, $oid, $cb, $arg);
353 sub extract_cmt_time {
354 my ($bref, undef, undef, undef, $modified) = @_;
356 if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
357 my $cmt_time = $1 + 0;
358 $$modified = $cmt_time if $cmt_time > $$modified;
362 # returns the modified time of a git repo, same as the "modified" field
363 # of a grokmirror manifest
367 my $fh = popen($self, qw(rev-parse --branches));
369 while (my $oid = <$fh>) {
371 cat_async($self, $oid, \&extract_cmt_time, \$modified);
373 cat_async_wait($self);
383 PublicInbox::Git - git wrapper
391 use PublicInbox::Git;
392 chomp(my $git_dir = `git rev-parse --git-dir`);
393 $git_dir or die "GIT_DIR= must be specified\n";
394 my $git = PublicInbox::Git->new($git_dir);
398 Unstable API outside of the L</new> method.
399 It requires L<git(1)> to be installed.
407 my $git = PublicInbox::Git->new($git_dir);
409 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
410 This is the only public API method we support. Everything else
411 in this module is subject to change.
415 L<Git>, L<PublicInbox::Import>
419 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
421 The mail archives are hosted at L<https://public-inbox.org/meta/>
425 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
427 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>