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 use constant MAX_INFLIGHT =>
21 ($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF())
23 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
36 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
39 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
41 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
43 $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
44 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
49 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
50 '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
57 my ($class, $git_dir) = @_;
58 # may contain {-tmp} field for File::Temp::Dir
59 bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
63 my ($self, $path) = @_;
64 $self->{-git_path}->{$path} ||= do {
66 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
68 # git prior to 2.5.0 did not understand --git-path
69 if ($str eq "--git-path\n$path") {
70 $str = "$self->{git_dir}/$path";
76 sub alternates_changed {
78 my $alt = git_path($self, 'objects/info/alternates');
79 my @st = stat($alt) or return 0;
81 # can't rely on 'q' on some 32-bit builds, but `d' works
82 my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
83 return 0 if $self->{alt_st} eq $st;
84 $self->{alt_st} = $st; # always a true value
89 my $fh = $self->{err_c} or return;
90 sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
91 defined(sysread($fh, my $buf, -s $fh)) or
92 fail($self, "sysread failed: $!");
97 my ($self, $batch, $in, $out, $pid, $err) = @_;
99 if (defined $err) { # "err_c"
100 my $fh = $self->{$err};
101 sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
102 truncate($fh, 0) or fail($self, "truncate failed: $!");
107 pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
108 my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
109 qw(-c core.abbrev=40 cat-file), $batch);
110 my $redir = { 0 => $out_r };
112 my $id = "git.$self->{git_dir}$batch.err";
113 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
117 my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
119 $out_w->autoflush(1);
120 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
121 fcntl($out_w, 1031, 4096);
122 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
124 $self->{$out} = $out_w;
125 $self->{$in} = $in_r;
128 sub read_cat_in_full ($$) {
129 my ($self, $len) = @_;
130 ++$len; # for final "\n" added by git
131 read($self->{in}, my $buf, $len) == $len or fail($self, 'short read');
132 chop($buf) eq "\n" or fail($self, 'newline missing after blob');
136 sub _cat_async_step ($$) {
137 my ($self, $inflight) = @_;
138 my $pair = shift @$inflight or die 'BUG: inflight empty';
139 my ($cb, $arg) = @$pair;
141 my $head = readline($self->{in});
142 $head =~ / missing$/ and return
143 eval { $cb->(undef, undef, undef, undef, $arg) };
145 $head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/ or
146 fail($self, "Unexpected result from async git cat-file: $head");
147 my ($oid_hex, $type, $size) = ($1, $2, $3 + 0);
148 my $bref = read_cat_in_full($self, $size);
149 eval { $cb->($bref, $oid_hex, $type, $size, $arg) };
150 warn "E: $oid_hex $@\n" if $@;
153 sub cat_async_wait ($) {
155 my $inflight = delete $self->{inflight} or return;
156 while (scalar(@$inflight)) {
157 _cat_async_step($self, $inflight);
162 my ($self, $obj, $ref) = @_;
163 my ($retried, $head);
164 cat_async_wait($self);
166 batch_prepare($self);
167 print { $self->{out} } $obj, "\n" or fail($self, "write error: $!");
170 $head = readline($self->{in});
171 if ($head =~ / missing$/) {
172 if (!$retried && alternates_changed($self)) {
179 $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
180 fail($self, "Unexpected result from git cat-file: $head");
183 $$ref = $size if $ref;
184 read_cat_in_full($self, $size);
187 sub batch_prepare ($) { _bidi_pipe($_[0], qw(--batch in out pid)) }
190 my ($self, $obj) = @_;
191 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
192 print { $self->{out_c} } $obj, "\n" or fail($self, "write error: $!");
194 chomp(my $line = readline($self->{in_c}));
195 my ($hex, $type, $size) = split(' ', $line);
197 # Future versions of git.git may show 'ambiguous', but for now,
198 # we must handle 'dangling' below (and maybe some other oddball
200 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
201 return if $type eq 'missing' || $type eq 'ambiguous';
203 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
204 $size = $type + length("\n");
205 my $r = read($self->{in_c}, my $buf, $size);
206 defined($r) or fail($self, "read failed: $!");
210 ($hex, $type, $size);
214 my ($self, $in, $out, $pid, $err) = @_;
215 my $p = delete $self->{$pid} or return;
216 delete @$self{($in, $out)};
217 delete $self->{$err} if $err; # `err_c'
219 # PublicInbox::DS may not be loaded
220 eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
221 waitpid($p, 0) if $@; # wait synchronously if not in event loop
224 sub cat_async_abort ($) {
226 my $inflight = delete $self->{inflight} or die 'BUG: not in async';
231 my ($self, $msg) = @_;
232 $self->{inflight} ? cat_async_abort($self) : cleanup($self);
237 my ($self, @cmd) = @_;
238 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
243 my ($self, @cmd) = @_;
244 my $fh = $self->popen(@cmd);
246 return <$fh> if wantarray;
251 # returns true if there are pending "git cat-file" processes
254 _destroy($self, qw(in out pid));
255 _destroy($self, qw(in_c out_c pid_c err_c));
256 !!($self->{pid} || $self->{pid_c});
259 # assuming a well-maintained repo, this should be a somewhat
260 # accurate estimation of its size
261 # TODO: show this in the WWW UI as a hint to potential cloners
265 my $pack_dir = git_path($self, 'objects/pack');
266 foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
272 sub DESTROY { cleanup(@_) }
277 # don't show full FS path, basename should be OK:
278 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
279 $ret = "/path/to/$1";
281 wantarray ? ($ret) : $ret;
284 sub host_prefix_url ($$) {
285 my ($env, $url) = @_;
286 return $url if index($url, '//') >= 0;
287 my $scheme = $env->{'psgi.url_scheme'};
288 my $host_port = $env->{HTTP_HOST} //
289 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
290 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
294 my ($self, $env) = @_;
295 if (my $urls = $self->{cgit_url}) {
296 return map { host_prefix_url($env, $_) } @$urls;
301 sub cat_async_begin {
303 cleanup($self) if alternates_changed($self);
304 batch_prepare($self);
305 die 'BUG: already in async' if $self->{inflight};
306 $self->{inflight} = [];
309 sub cat_async ($$$;$) {
310 my ($self, $oid, $cb, $arg) = @_;
311 my $inflight = $self->{inflight} or die 'BUG: not in async';
312 if (scalar(@$inflight) >= MAX_INFLIGHT) {
313 _cat_async_step($self, $inflight);
316 print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
317 push(@$inflight, [ $cb, $arg ]);
320 sub extract_cmt_time {
321 my ($bref, undef, undef, undef, $modified) = @_;
323 if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
324 my $cmt_time = $1 + 0;
325 $$modified = $cmt_time if $cmt_time > $$modified;
329 # returns the modified time of a git repo, same as the "modified" field
330 # of a grokmirror manifest
334 my $fh = popen($self, qw(rev-parse --branches));
335 cat_async_begin($self);
337 while (my $oid = <$fh>) {
339 cat_async($self, $oid, \&extract_cmt_time, \$modified);
341 cat_async_wait($self);
351 PublicInbox::Git - git wrapper
359 use PublicInbox::Git;
360 chomp(my $git_dir = `git rev-parse --git-dir`);
361 $git_dir or die "GIT_DIR= must be specified\n";
362 my $git = PublicInbox::Git->new($git_dir);
366 Unstable API outside of the L</new> method.
367 It requires L<git(1)> to be installed.
375 my $git = PublicInbox::Git->new($git_dir);
377 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
378 This is the only public API method we support. Everything else
379 in this module is subject to change.
383 L<Git>, L<PublicInbox::Import>
387 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
389 The mail archives are hosted at L<https://public-inbox.org/meta/>
393 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
395 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>