1 # Copyright (C) 2014-2019 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 PublicInbox::Spawn qw(spawn popen_rd);
15 use PublicInbox::Tmpfile;
16 use base qw(Exporter);
17 our @EXPORT_OK = qw(git_unquote git_quote);
19 use constant MAX_INFLIGHT =>
20 ($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF())
22 65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
35 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
38 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
40 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
42 $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
43 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
48 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
49 '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
56 my ($class, $git_dir) = @_;
59 # may contain {-tmp} field for File::Temp::Dir
60 bless { git_dir => $git_dir, st => \@st, -git_path => {} }, $class
64 my ($self, $path) = @_;
65 $self->{-git_path}->{$path} ||= do {
67 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
69 # git prior to 2.5.0 did not understand --git-path
70 if ($str eq "--git-path\n$path") {
71 $str = "$self->{git_dir}/$path";
77 sub alternates_changed {
79 my $alt = git_path($self, 'objects/info/alternates');
80 my @st = stat($alt) or return 0;
81 my $old_st = $self->{st};
82 # 10 - ctime, 7 - size
83 return 0 if ($st[10] == $old_st->[10] && $st[7] == $old_st->[7]);
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: $!");
106 my ($in_r, $in_w, $out_r, $out_w);
108 pipe($in_r, $in_w) or fail($self, "pipe failed: $!");
109 pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
110 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
111 fcntl($out_w, 1031, 4096);
112 fcntl($in_w, 1031, 4096) if $batch eq '--batch-check';
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, 1 => $in_w };
119 my $id = "git.$self->{git_dir}$batch.err";
120 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
124 my $p = spawn(\@cmd, undef, $redir);
125 defined $p or fail($self, "spawn failed: $!");
127 $out_w->autoflush(1);
128 $self->{$out} = $out_w;
129 $self->{$in} = $in_r;
132 sub read_cat_in_full ($$$) {
133 my ($self, $in, $left) = @_;
137 my $r = read($in, $buf, $left, $offset);
138 defined($r) or fail($self, "read failed: $!");
139 $r == 0 and fail($self, 'exited unexpectedly');
143 my $r = read($in, my $lf, 1);
144 defined($r) or fail($self, "read failed: $!");
145 fail($self, 'newline missing after blob') if ($r != 1 || $lf ne "\n");
149 sub _cat_async_step ($$$) {
150 my ($self, $inflight, $in) = @_;
151 my $pair = shift @$inflight or die 'BUG: inflight empty';
152 my ($cb, $arg) = @$pair;
154 my $head = $in->getline;
155 $head =~ / missing$/ and return
156 eval { $cb->(undef, undef, undef, undef, $arg) };
158 $head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/ or
159 fail($self, "Unexpected result from async git cat-file: $head");
160 my ($oid_hex, $type, $size) = ($1, $2, $3 + 0);
161 my $bref = read_cat_in_full($self, $in, $size);
162 eval { $cb->($bref, $oid_hex, $type, $size, $arg) };
165 sub cat_async_wait ($) {
167 my $inflight = delete $self->{inflight} or return;
168 my $in = $self->{in};
169 while (scalar(@$inflight)) {
170 _cat_async_step($self, $inflight, $in);
175 my ($self, $obj, $ref) = @_;
176 my ($retried, $in, $head);
177 cat_async_wait($self);
179 batch_prepare($self);
180 $self->{out}->print($obj, "\n") or fail($self, "write error: $!");
184 $head = $in->getline;
185 if ($head =~ / missing$/) {
186 if (!$retried && alternates_changed($self)) {
193 $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
194 fail($self, "Unexpected result from git cat-file: $head");
197 $$ref = $size if $ref;
198 read_cat_in_full($self, $in, $size);
201 sub batch_prepare ($) { _bidi_pipe($_[0], qw(--batch in out pid)) }
204 my ($self, $obj) = @_;
205 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
206 $self->{out_c}->print($obj, "\n") or fail($self, "write error: $!");
208 chomp(my $line = $self->{in_c}->getline);
209 my ($hex, $type, $size) = split(' ', $line);
211 # Future versions of git.git may show 'ambiguous', but for now,
212 # we must handle 'dangling' below (and maybe some other oddball
214 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
215 return if $type eq 'missing' || $type eq 'ambiguous';
217 if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
218 $size = $type + length("\n");
219 my $r = read($self->{in_c}, my $buf, $size);
220 defined($r) or fail($self, "read failed: $!");
224 ($hex, $type, $size);
228 my ($self, $in, $out, $pid, $err) = @_;
229 my $p = delete $self->{$pid} or return;
230 delete @$self{($in, $out)};
231 delete $self->{$err} if $err; # `err_c'
233 # PublicInbox::DS may not be loaded
234 eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
235 waitpid($p, 0) if $@; # wait synchronously if not in event loop
238 sub cat_async_abort ($) {
240 my $inflight = delete $self->{inflight} or die 'BUG: not in async';
245 my ($self, $msg) = @_;
246 $self->{inflight} ? cat_async_abort($self) : cleanup($self);
251 my ($self, @cmd) = @_;
252 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
257 my ($self, @cmd) = @_;
258 my $fh = $self->popen(@cmd);
259 defined $fh or return;
261 return <$fh> if wantarray;
266 # returns true if there are pending "git cat-file" processes
269 _destroy($self, qw(in out pid));
270 _destroy($self, qw(in_c out_c pid_c err_c));
271 !!($self->{pid} || $self->{pid_c});
274 # assuming a well-maintained repo, this should be a somewhat
275 # accurate estimation of its size
276 # TODO: show this in the WWW UI as a hint to potential cloners
280 my $pack_dir = git_path($self, 'objects/pack');
281 foreach my $p (glob("$pack_dir/*.pack")) {
287 sub DESTROY { cleanup(@_) }
292 # don't show full FS path, basename should be OK:
293 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
294 $ret = "/path/to/$1";
296 wantarray ? ($ret) : $ret;
299 sub host_prefix_url ($$) {
300 my ($env, $url) = @_;
301 return $url if index($url, '//') >= 0;
302 my $scheme = $env->{'psgi.url_scheme'};
303 my $host_port = $env->{HTTP_HOST} ||
304 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
305 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
309 my ($self, $env) = @_;
310 if (my $urls = $self->{cgit_url}) {
311 return map { host_prefix_url($env, $_) } @$urls;
316 sub cat_async_begin {
318 cleanup($self) if alternates_changed($self);
319 batch_prepare($self);
320 die 'BUG: already in async' if $self->{inflight};
321 $self->{inflight} = [];
324 sub cat_async ($$$;$) {
325 my ($self, $oid, $cb, $arg) = @_;
326 my $inflight = $self->{inflight} or die 'BUG: not in async';
327 if (scalar(@$inflight) >= MAX_INFLIGHT) {
328 _cat_async_step($self, $inflight, $self->{in});
331 $self->{out}->print($oid, "\n") or fail($self, "write error: $!");
332 push(@$inflight, [ $cb, $arg ]);
335 sub commit_title ($$) {
336 my ($self, $oid) = @_; # PublicInbox::Git, $sha1hex
337 my $buf = cat_file($self, $oid) or return;
339 ($$buf =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/)[0]
342 # returns the modified time of a git repo, same as the "modified" field
343 # of a grokmirror manifest
347 my $fh = popen($self, qw(rev-parse --branches));
348 defined $fh or return $modified;
350 foreach my $oid (<$fh>) {
352 my $buf = cat_file($self, $oid) or next;
353 $$buf =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm or next;
354 my $cmt_time = $1 + 0;
355 $modified = $cmt_time if $cmt_time > $modified;
366 PublicInbox::Git - git wrapper
374 use PublicInbox::Git;
375 chomp(my $git_dir = `git rev-parse --git-dir`);
376 $git_dir or die "GIT_DIR= must be specified\n";
377 my $git = PublicInbox::Git->new($git_dir);
381 Unstable API outside of the L</new> method.
382 It requires L<git(1)> to be installed.
390 my $git = PublicInbox::Git->new($git_dir);
392 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
393 This is the only public API method we support. Everything else
394 in this module is subject to change.
398 L<Git>, L<PublicInbox::Import>
402 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
404 The mail archives are hosted at L<https://public-inbox.org/meta/>
408 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
410 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>