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()) * 2)
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) < 2;
161 my ($cb, $arg) = splice(@$inflight, 0, 2);
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$/) {
171 fail($self, "Unexpected result from async git cat-file: $head");
173 eval { $cb->($bref, $oid, $type, $size, $arg) };
174 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
175 warn "E: $oid: $@\n" if $@;
178 sub cat_async_wait ($) {
180 my $inflight = delete $self->{inflight} or return;
181 while (scalar(@$inflight)) {
182 cat_async_step($self, $inflight);
186 sub batch_prepare ($) {
187 _bidi_pipe($_[0], qw(--batch in out pid));
191 my ($self, $obj, $sizeref) = @_;
192 my ($retried, $head, $rbuf);
193 cat_async_wait($self);
195 batch_prepare($self);
196 $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
197 print { $self->{out} } $obj, "\n" or fail($self, "write error: $!");
198 $head = my_readline($self->{in}, $rbuf);
199 if ($head =~ / missing$/) {
200 if (!$retried && alternates_changed($self)) {
207 $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
208 fail($self, "Unexpected result from git cat-file: $head");
211 $$sizeref = $size if $sizeref;
212 my $ret = my_read($self->{in}, $rbuf, $size + 1);
213 $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
214 fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
215 chop($$ret) eq "\n" or fail($self, 'newline missing after blob');
220 my ($self, $obj) = @_;
221 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
222 print { $self->{out_c} } $obj, "\n" or fail($self, "write error: $!");
223 my $rbuf = ''; # TODO: async + {chk_rbuf}
224 chomp(my $line = my_readline($self->{in_c}, \$rbuf));
225 my ($hex, $type, $size) = split(' ', $line);
227 # Future versions of git.git may show 'ambiguous', but for now,
228 # we must handle 'dangling' below (and maybe some other oddball
230 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
231 return if $type eq 'missing' || $type eq 'ambiguous';
233 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
234 my $ret = my_read($self->{in_c}, \$rbuf, $type + 1);
235 fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
239 ($hex, $type, $size);
243 my ($self, $rbuf, $in, $out, $pid, $err) = @_;
244 my $p = delete $self->{$pid} or return;
245 delete @$self{($rbuf, $in, $out)};
246 delete $self->{$err} if $err; # `err_c'
248 # PublicInbox::DS may not be loaded
249 eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
250 waitpid($p, 0) if $@; # wait synchronously if not in event loop
253 sub cat_async_abort ($) {
255 my $inflight = delete $self->{inflight} or die 'BUG: not in async';
260 my ($self, $msg) = @_;
261 $self->{inflight} ? cat_async_abort($self) : cleanup($self);
266 my ($self, @cmd) = @_;
267 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
272 my ($self, @cmd) = @_;
273 my $fh = $self->popen(@cmd);
275 return <$fh> if wantarray;
280 # returns true if there are pending "git cat-file" processes
283 cat_async_wait($self);
284 _destroy($self, qw(cat_rbuf in out pid));
285 _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
286 !!($self->{pid} || $self->{pid_c});
289 # assuming a well-maintained repo, this should be a somewhat
290 # accurate estimation of its size
291 # TODO: show this in the WWW UI as a hint to potential cloners
295 my $pack_dir = git_path($self, 'objects/pack');
296 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
302 sub DESTROY { cleanup(@_) }
307 # don't show full FS path, basename should be OK:
308 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
309 $ret = "/path/to/$1";
311 wantarray ? ($ret) : $ret;
314 sub host_prefix_url ($$) {
315 my ($env, $url) = @_;
316 return $url if index($url, '//') >= 0;
317 my $scheme = $env->{'psgi.url_scheme'};
318 my $host_port = $env->{HTTP_HOST} //
319 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
320 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
324 my ($self, $env) = @_;
325 if (my $urls = $self->{cgit_url}) {
326 return map { host_prefix_url($env, $_) } @$urls;
331 sub cat_async_begin {
333 cleanup($self) if alternates_changed($self);
334 batch_prepare($self);
335 die 'BUG: already in async' if $self->{inflight};
336 $self->{inflight} = [];
339 sub cat_async ($$$;$) {
340 my ($self, $oid, $cb, $arg) = @_;
341 my $inflight = $self->{inflight} // cat_async_begin($self);
342 if (scalar(@$inflight) >= MAX_INFLIGHT) {
343 cat_async_step($self, $inflight);
346 print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
347 push(@$inflight, $cb, $arg);
350 sub extract_cmt_time {
351 my ($bref, undef, undef, undef, $modified) = @_;
353 if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
354 my $cmt_time = $1 + 0;
355 $$modified = $cmt_time if $cmt_time > $$modified;
359 # returns the modified time of a git repo, same as the "modified" field
360 # of a grokmirror manifest
364 my $fh = popen($self, qw(rev-parse --branches));
366 while (my $oid = <$fh>) {
368 cat_async($self, $oid, \&extract_cmt_time, \$modified);
370 cat_async_wait($self);
380 PublicInbox::Git - git wrapper
388 use PublicInbox::Git;
389 chomp(my $git_dir = `git rev-parse --git-dir`);
390 $git_dir or die "GIT_DIR= must be specified\n";
391 my $git = PublicInbox::Git->new($git_dir);
395 Unstable API outside of the L</new> method.
396 It requires L<git(1)> to be installed.
404 my $git = PublicInbox::Git->new($git_dir);
406 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
407 This is the only public API method we support. Everything else
408 in this module is subject to change.
412 L<Git>, L<PublicInbox::Import>
416 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
418 The mail archives are hosted at L<https://public-inbox.org/meta/>
422 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
424 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>