]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
a3813bf2123dc02748a2903f3cdc582ca92db7eb
[public-inbox.git] / lib / PublicInbox / Git.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: GPLv2 or later <https://www.gnu.org/licenses/gpl-2.0.txt>
3 #
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;
10 use strict;
11 use v5.10.1;
12 use parent qw(Exporter);
13 use POSIX ();
14 use IO::Handle; # ->autoflush
15 use Errno qw(EINTR EAGAIN ENOENT);
16 use File::Glob qw(bsd_glob GLOB_NOSORT);
17 use File::Spec ();
18 use Time::HiRes qw(stat);
19 use PublicInbox::Spawn qw(popen_rd which);
20 use PublicInbox::Tmpfile;
21 use IO::Poll qw(POLLIN);
22 use Carp qw(croak carp);
23 use Digest::SHA ();
24 use PublicInbox::DS qw(awaitpid);
25 our @EXPORT_OK = qw(git_unquote git_quote);
26 our $PIPE_BUFSIZ = 65536; # Linux default
27 our $in_cleanup;
28 our $RDTIMEO = 60_000; # milliseconds
29 our $async_warn; # true in read-only daemons
30
31 # 512: POSIX PIPE_BUF minimum (see pipe(7))
32 # 3: @$inflight is flattened [ $OID, $cb, $arg ]
33 # 65: SHA-256 hex size + "\n" in preparation for git using non-SHA1
34 use constant MAX_INFLIGHT => 512 * 3 / 65;
35
36 my %GIT_ESC = (
37         a => "\a",
38         b => "\b",
39         f => "\f",
40         n => "\n",
41         r => "\r",
42         t => "\t",
43         v => "\013",
44         '"' => '"',
45         '\\' => '\\',
46 );
47 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
48
49 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
50 sub git_unquote ($) {
51         return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
52         $_[0] = $1;
53         $_[0] =~ s!\\([\\"abfnrtv]|[0-3][0-7]{2})!$GIT_ESC{$1}//chr(oct($1))!ge;
54         $_[0];
55 }
56
57 sub git_quote ($) {
58         if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
59                       '\\'.($ESC_GIT{$1}||sprintf("%03o",ord($1)))/egs) {
60                 return qq{"$_[0]"};
61         }
62         $_[0];
63 }
64
65 sub new {
66         my ($class, $git_dir) = @_;
67         $git_dir =~ tr!/!/!s;
68         $git_dir =~ s!/*\z!!s;
69         # may contain {-tmp} field for File::Temp::Dir
70         bless { git_dir => $git_dir }, $class
71 }
72
73 sub git_path ($$) {
74         my ($self, $path) = @_;
75         $self->{-git_path}->{$path} //= do {
76                 local $/ = "\n";
77                 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
78
79                 # git prior to 2.5.0 did not understand --git-path
80                 if ($str eq "--git-path\n$path") {
81                         $str = "$self->{git_dir}/$path";
82                 }
83                 $str;
84         };
85 }
86
87 sub alternates_changed {
88         my ($self) = @_;
89         my $alt = git_path($self, 'objects/info/alternates');
90         my @st = stat($alt) or return 0;
91
92         # can't rely on 'q' on some 32-bit builds, but `d' works
93         my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
94         return 0 if ($self->{alt_st} // '') eq $st;
95         $self->{alt_st} = $st; # always a true value
96 }
97
98 sub object_format {
99         $_[0]->{object_format} //= do {
100                 my $fmt = $_[0]->qx(qw(config extensions.objectformat));
101                 $fmt eq "sha256\n" ? \'sha256' : \undef;
102         }
103 }
104
105 sub last_check_err {
106         my ($self) = @_;
107         my $fh = $self->{err_c} or return;
108         sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
109         defined(sysread($fh, my $buf, -s $fh)) or
110                         $self->fail("sysread failed: $!");
111         $buf;
112 }
113
114 sub _bidi_pipe {
115         my ($self, $batch, $in, $out, $pid, $err) = @_;
116         if ($self->{$pid}) {
117                 if (defined $err) { # "err_c"
118                         my $fh = $self->{$err};
119                         sysseek($fh, 0, 0) or $self->fail("sysseek failed: $!");
120                         truncate($fh, 0) or $self->fail("truncate failed: $!");
121                 }
122                 return;
123         }
124
125         state $EXE_ST = ''; # pack('dd', st_ctime, st_size);
126         my $exe = which('git') // die "git not found in $ENV{PATH}";
127         my @st = stat($exe) or die "stat: $!";
128         my $st = pack('dd', $st[10], $st[7]);
129         state $VER;
130         if ($st ne $EXE_ST) {
131                 my $rd = popen_rd([ $exe, '--version' ]);
132                 my $v = readline($rd);
133                 $v =~ /\b([0-9]+(?:\.[0-9]+){2})/ or die
134                         "$exe --version output: $v # unparseable";
135                 my @v = split(/\./, $1, 3);
136                 $VER = ($v[0] << 24) | ($v[1] << 16) | $v[2];
137                 $EXE_ST = $st;
138         }
139
140         # git 2.31.0+ supports -c core.abbrev=no, don't bother with
141         # core.abbrev=64 since not many releases had SHA-256 prior to 2.31
142         my $abbr = $VER < (2 << 24 | 31 << 16) ? 40 : 'no';
143
144         pipe(my ($out_r, $out_w)) or $self->fail("pipe failed: $!");
145         my $rdr = { 0 => $out_r, pgid => 0 };
146         my $gd = $self->{git_dir};
147         if ($gd =~ s!/([^/]+/[^/]+)\z!/!) {
148                 $rdr->{-C} = $gd;
149                 $gd = $1;
150         }
151         my @cmd = ($exe, "--git-dir=$gd", '-c', "core.abbrev=$abbr",
152                         'cat-file', $batch);
153         if ($err) {
154                 my $id = "git.$self->{git_dir}$batch.err";
155                 my $fh = tmpfile($id) or $self->fail("tmpfile($id): $!");
156                 $self->{$err} = $fh;
157                 $rdr->{2} = $fh;
158         }
159         # see lib/PublicInbox/ProcessPipe.pm for why we don't use that here
160         my ($in_r, $p) = popen_rd(\@cmd, undef, $rdr);
161         awaitpid($self->{$pid} = $p, undef);
162         $self->{"$pid.owner"} = $$;
163         $out_w->autoflush(1);
164         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
165                 fcntl($out_w, 1031, 4096);
166                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
167         }
168         $out_w->blocking(0);
169         $self->{$out} = $out_w;
170         $self->{$in} = $in_r;
171 }
172
173 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
174
175 sub my_read ($$$) {
176         my ($fh, $rbuf, $len) = @_;
177         my $left = $len - length($$rbuf);
178         my $r;
179         while ($left > 0) {
180                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
181                 if ($r) {
182                         $left -= $r;
183                 } elsif (defined($r)) { # EOF
184                         return 0;
185                 } else {
186                         next if ($! == EAGAIN and poll_in($fh));
187                         next if $! == EINTR; # may be set by sysread or poll_in
188                         return; # unrecoverable error
189                 }
190         }
191         my $no_pad = substr($$rbuf, 0, $len, '');
192         \$no_pad;
193 }
194
195 sub my_readline ($$) {
196         my ($fh, $rbuf) = @_;
197         while (1) {
198                 if ((my $n = index($$rbuf, "\n")) >= 0) {
199                         return substr($$rbuf, 0, $n + 1, '');
200                 }
201                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
202                                                                 and next;
203
204                 # return whatever's left on EOF
205                 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
206
207                 next if ($! == EAGAIN and poll_in($fh));
208                 next if $! == EINTR; # may be set by sysread or poll_in
209                 return; # unrecoverable error
210         }
211 }
212
213 sub cat_async_retry ($$) {
214         my ($self, $inflight) = @_;
215
216         # {inflight} may be non-existent, but if it isn't we delete it
217         # here to prevent cleanup() from waiting:
218         delete $self->{inflight};
219         cleanup($self);
220
221         $self->{inflight} = $inflight;
222         batch_prepare($self);
223         my $buf = '';
224         for (my $i = 0; $i < @$inflight; $i += 3) {
225                 $buf .= "$inflight->[$i]\n";
226         }
227         $self->{out}->blocking(1); # brand new pipe, should never block
228         print { $self->{out} } $buf or $self->fail("write error: $!");
229         $self->{out}->blocking(0);
230         my $req = shift @$inflight;
231         unshift(@$inflight, \$req); # \$ref to indicate retried
232
233         cat_async_step($self, $inflight); # take one step
234 }
235
236 sub cat_async_step ($$) {
237         my ($self, $inflight) = @_;
238         die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
239         my ($req, $cb, $arg) = @$inflight[0, 1, 2];
240         my $rbuf = delete($self->{rbuf}) // \(my $new = '');
241         my ($bref, $oid, $type, $size);
242         my $head = my_readline($self->{in}, $rbuf);
243         # ->fail may be called via Gcf2Client.pm
244         if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
245                 ($oid, $type, $size) = ($1, $2, $3 + 0);
246                 $bref = my_read($self->{in}, $rbuf, $size + 1) or
247                         $self->fail(defined($bref) ? 'read EOF' : "read: $!");
248                 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
249         } elsif ($head =~ s/ missing\n//s) {
250                 $oid = $head;
251                 # ref($req) indicates it's already been retried
252                 # -gcf2 retries internally, so it never hits this path:
253                 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
254                         return cat_async_retry($self, $inflight);
255                 }
256                 $type = 'missing';
257                 $oid = ref($req) ? $$req : $req if $oid eq '';
258         } else {
259                 my $err = $! ? " ($!)" : '';
260                 $self->fail("bad result from async cat-file: $head$err");
261         }
262         $self->{rbuf} = $rbuf if $$rbuf ne '';
263         splice(@$inflight, 0, 3); # don't retry $cb on ->fail
264         eval { $cb->($bref, $oid, $type, $size, $arg) };
265         async_err($self, $req, $oid, $@, 'cat') if $@;
266 }
267
268 sub cat_async_wait ($) {
269         my ($self) = @_;
270         my $inflight = $self->{inflight} or return;
271         while (scalar(@$inflight)) {
272                 cat_async_step($self, $inflight);
273         }
274 }
275
276 sub batch_prepare ($) {
277         _bidi_pipe($_[0], qw(--batch in out pid));
278 }
279
280 sub _cat_file_cb {
281         my ($bref, $oid, $type, $size, $result) = @_;
282         @$result = ($bref, $oid, $type, $size);
283 }
284
285 sub cat_file {
286         my ($self, $oid) = @_;
287         my $result = [];
288         cat_async($self, $oid, \&_cat_file_cb, $result);
289         cat_async_wait($self);
290         wantarray ? @$result : $result->[0];
291 }
292
293 sub check_async_step ($$) {
294         my ($self, $inflight_c) = @_;
295         die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
296         my ($req, $cb, $arg) = @$inflight_c[0, 1, 2];
297         my $rbuf = delete($self->{rbuf_c}) // \(my $new = '');
298         chomp(my $line = my_readline($self->{in_c}, $rbuf));
299         my ($hex, $type, $size) = split(/ /, $line);
300
301         # Future versions of git.git may have type=ambiguous, but for now,
302         # we must handle 'dangling' below (and maybe some other oddball
303         # stuff):
304         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
305         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
306                 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
307                 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
308         }
309         $self->{rbuf_c} = $rbuf if $$rbuf ne '';
310         splice(@$inflight_c, 0, 3); # don't retry $cb on ->fail
311         eval { $cb->($hex, $type, $size, $arg, $self) };
312         async_err($self, $req, $hex, $@, 'check') if $@;
313 }
314
315 sub check_async_wait ($) {
316         my ($self) = @_;
317         my $inflight_c = $self->{inflight_c} or return;
318         while (scalar(@$inflight_c)) {
319                 check_async_step($self, $inflight_c);
320         }
321 }
322
323 sub check_async_begin ($) {
324         my ($self) = @_;
325         cleanup($self) if alternates_changed($self);
326         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
327         die 'BUG: already in async check' if $self->{inflight_c};
328         $self->{inflight_c} = [];
329 }
330
331 sub write_all {
332         my ($self, $out, $buf, $read_step, $inflight) = @_;
333         $read_step->($self, $inflight) while @$inflight >= MAX_INFLIGHT;
334         do {
335                 my $w = syswrite($out, $buf);
336                 if (defined $w) {
337                         return if $w == length($buf);
338                         substr($buf, 0, $w, ''); # sv_chop
339                 } elsif ($! != EAGAIN) {
340                         $self->fail("write: $!");
341                 }
342                 $read_step->($self, $inflight);
343         } while (1);
344 }
345
346 sub check_async ($$$$) {
347         my ($self, $oid, $cb, $arg) = @_;
348         my $inflight_c = $self->{inflight_c} // check_async_begin($self);
349         write_all($self, $self->{out_c}, $oid."\n",
350                 \&check_async_step, $inflight_c);
351         push(@$inflight_c, $oid, $cb, $arg);
352 }
353
354 sub _check_cb { # check_async callback
355         my ($hex, $type, $size, $result) = @_;
356         @$result = ($hex, $type, $size);
357 }
358
359 sub check {
360         my ($self, $oid) = @_;
361         my $result = [];
362         check_async($self, $oid, \&_check_cb, $result);
363         check_async_wait($self);
364         my ($hex, $type, $size) = @$result;
365
366         # Future versions of git.git may show 'ambiguous', but for now,
367         # we must handle 'dangling' below (and maybe some other oddball
368         # stuff):
369         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
370         return if $type eq 'missing' || $type eq 'ambiguous';
371         return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
372         ($hex, $type, $size);
373 }
374
375 sub _destroy {
376         my ($self, $rbuf, $in, $out, $pid, $err) = @_;
377         delete @$self{($rbuf, $in, $out)};
378         delete $self->{$err} if $err; # `err_c'
379
380         # GitAsyncCat::event_step may delete {$pid}
381         my $p = delete($self->{$pid}) // return;
382         awaitpid($p) if $$ == $self->{"$pid.owner"};
383 }
384
385 sub async_abort ($) {
386         my ($self) = @_;
387         while (scalar(@{$self->{inflight_c} // []}) ||
388                         scalar(@{$self->{inflight} // []})) {
389                 for my $c ('', '_c') {
390                         my $q = $self->{"inflight$c"} or next;
391                         while (@$q) {
392                                 my ($req, $cb, $arg) = splice(@$q, 0, 3);
393                                 $req = $$req if ref($req);
394                                 $req =~ s/ .*//; # drop git_dir for Gcf2Client
395                                 eval { $cb->(undef, $req, undef, undef, $arg) };
396                                 warn "E: (in abort) $req: $@" if $@;
397                         }
398                         delete $self->{"inflight$c"};
399                         delete $self->{"rbuf$c"};
400                 }
401         }
402         cleanup($self);
403 }
404
405 sub fail { # may be augmented in subclasses
406         my ($self, $msg) = @_;
407         async_abort($self);
408         croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
409 }
410
411 sub async_err ($$$$$) {
412         my ($self, $req, $oid, $err, $action) = @_;
413         $req = $$req if ref($req); # retried
414         my $msg = "E: $action $req ($oid): $err";
415         $async_warn ? carp($msg) : $self->fail($msg);
416 }
417
418 # $git->popen(qw(show f00)); # or
419 # $git->popen(qw(show f00), { GIT_CONFIG => ... }, { 2 => ... });
420 sub popen {
421         my ($self, $cmd) = splice(@_, 0, 2);
422         $cmd = [ 'git', "--git-dir=$self->{git_dir}",
423                 ref($cmd) ? @$cmd : ($cmd, grep { defined && !ref } @_) ];
424         popen_rd($cmd, grep { !defined || ref } @_); # env and opt
425 }
426
427 # same args as popen above
428 sub qx {
429         my $fh = popen(@_);
430         if (wantarray) {
431                 my @ret = <$fh>;
432                 close $fh; # caller should check $?
433                 @ret;
434         } else {
435                 local $/;
436                 my $ret = <$fh>;
437                 close $fh; # caller should check $?
438                 $ret;
439         }
440 }
441
442 sub date_parse {
443         my $self = shift;
444         map {
445                 substr($_, length('--max-age='), -1)
446         } $self->qx('rev-parse', map { "--since=$_" } @_);
447 }
448
449 # check_async and cat_async may trigger the other, so ensure they're
450 # both completely done by using this:
451 sub async_wait_all ($) {
452         my ($self) = @_;
453         while (scalar(@{$self->{inflight_c} // []}) ||
454                         scalar(@{$self->{inflight} // []})) {
455                 check_async_wait($self);
456                 cat_async_wait($self);
457         }
458 }
459
460 # returns true if there are pending "git cat-file" processes
461 sub cleanup {
462         my ($self, $lazy) = @_;
463         return 1 if $lazy && (scalar(@{$self->{inflight_c} // []}) ||
464                                 scalar(@{$self->{inflight} // []}));
465         local $in_cleanup = 1;
466         delete $self->{async_cat};
467         delete $self->{async_chk};
468         async_wait_all($self);
469         delete $self->{inflight};
470         delete $self->{inflight_c};
471         _destroy($self, qw(rbuf in out pid));
472         _destroy($self, qw(rbuf_c in_c out_c pid_c err_c));
473         undef;
474 }
475
476 # assuming a well-maintained repo, this should be a somewhat
477 # accurate estimation of its size
478 # TODO: show this in the WWW UI as a hint to potential cloners
479 sub packed_bytes {
480         my ($self) = @_;
481         my $n = 0;
482         my $pack_dir = git_path($self, 'objects/pack');
483         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
484                 $n += -s $p;
485         }
486         $n
487 }
488
489 sub DESTROY { cleanup(@_) }
490
491 sub local_nick ($) {
492         # don't show full FS path, basename should be OK:
493         $_[0]->{nick} // ($_[0]->{git_dir} =~ m!/([^/]+?)(?:/*\.git/*)?\z! ?
494                         "$1.git" : undef);
495 }
496
497 sub host_prefix_url ($$) {
498         my ($env, $url) = @_;
499         return $url if index($url, '//') >= 0;
500         my $host_port = $env->{HTTP_HOST} //
501                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
502         my $sn = $env->{SCRIPT_NAME} // '';
503         "$env->{'psgi.url_scheme'}://$host_port$sn/$url";
504 }
505
506 sub base_url { # for coderepos, PSGI-only
507         my ($self, $env) = @_; # env - PSGI env
508         my $nick = $self->{nick} // return undef;
509         my $url = host_prefix_url($env, '');
510         # for mount in Plack::Builder
511         $url .= '/' if substr($url, -1, 1) ne '/';
512         $url . $nick . '/';
513 }
514
515 sub isrch {} # TODO
516
517 sub pub_urls {
518         my ($self, $env) = @_;
519         if (my $urls = $self->{cgit_url}) {
520                 map { host_prefix_url($env, $_) } @$urls;
521         } else {
522                 (base_url($self, $env) // '???');
523         }
524 }
525
526 sub cat_async_begin {
527         my ($self) = @_;
528         cleanup($self) if $self->alternates_changed;
529         $self->batch_prepare;
530         die 'BUG: already in async' if $self->{inflight};
531         $self->{inflight} = [];
532 }
533
534 sub cat_async ($$$;$) {
535         my ($self, $oid, $cb, $arg) = @_;
536         my $inflight = $self->{inflight} // cat_async_begin($self);
537         write_all($self, $self->{out}, $oid."\n", \&cat_async_step, $inflight);
538         push(@$inflight, $oid, $cb, $arg);
539 }
540
541 # returns the modified time of a git repo, same as the "modified" field
542 # of a grokmirror manifest
543 sub modified ($) {
544         # committerdate:unix is git 2.9.4+ (2017-05-05), so using raw instead
545         my $fh = popen($_[0], qw[for-each-ref --sort=-committerdate
546                                 --format=%(committerdate:raw) --count=1]);
547         (split(/ /, <$fh> // time))[0] + 0; # integerize for JSON
548 }
549
550 sub try_cat {
551         my ($path) = @_;
552         open(my $fh, '<', $path) or return '';
553         local $/;
554         <$fh> // '';
555 }
556
557 sub cat_desc ($) {
558         my $desc = try_cat($_[0]);
559         chomp $desc;
560         utf8::decode($desc);
561         $desc =~ s/\s+/ /smg;
562         $desc eq '' ? undef : $desc;
563 }
564
565 sub description {
566         cat_desc("$_[0]->{git_dir}/description") // 'Unnamed repository';
567 }
568
569 sub cloneurl {
570         my ($self, $env) = @_;
571         $self->{cloneurl} // do {
572                 my @urls = split(/\s+/s, try_cat("$self->{git_dir}/cloneurl"));
573                 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
574         } // [ substr(base_url($self, $env), 0, -1) ];
575 }
576
577 # for grokmirror, which doesn't read gitweb.description
578 # templates/hooks--update.sample and git-multimail in git.git
579 # only match "Unnamed repository", not the full contents of
580 # templates/this--description in git.git
581 sub manifest_entry {
582         my ($self, $epoch, $default_desc) = @_;
583         my $fh = $self->popen('show-ref');
584         my $dig = Digest::SHA->new(1);
585         while (read($fh, my $buf, 65536)) {
586                 $dig->add($buf);
587         }
588         close $fh or return; # empty, uninitialized git repo
589         undef $fh; # for open, below
590         my $git_dir = $self->{git_dir};
591         my $ent = {
592                 fingerprint => $dig->hexdigest,
593                 reference => undef,
594                 modified => modified($self),
595         };
596         chomp(my $owner = $self->qx('config', 'gitweb.owner'));
597         utf8::decode($owner);
598         $ent->{owner} = $owner eq '' ? undef : $owner;
599         my $desc = description($self);
600         if (defined $epoch && index($desc, 'Unnamed repository') == 0) {
601                 $desc = "$default_desc [epoch $epoch]";
602         }
603         $ent->{description} = $desc;
604         if (open($fh, '<', "$git_dir/objects/info/alternates")) {
605                 # n.b.: GitPython doesn't seem to handle comments or C-quoted
606                 # strings like native git does; and we don't for now, either.
607                 local $/ = "\n";
608                 chomp(my @alt = <$fh>);
609
610                 # grokmirror only supports 1 alternate for "reference",
611                 if (scalar(@alt) == 1) {
612                         my $objdir = "$git_dir/objects";
613                         my $ref = File::Spec->rel2abs($alt[0], $objdir);
614                         $ref =~ s!/[^/]+/?\z!!; # basename
615                         $ent->{reference} = $ref;
616                 }
617         }
618         $ent;
619 }
620
621 # returns true if there are pending cat-file processes
622 sub cleanup_if_unlinked {
623         my ($self) = @_;
624         return cleanup($self, 1) if $^O ne 'linux';
625         # Linux-specific /proc/$PID/maps access
626         # TODO: support this inside git.git
627         my $ret = 0;
628         for my $fld (qw(pid pid_c)) {
629                 my $pid = $self->{$fld} // next;
630                 open my $fh, '<', "/proc/$pid/maps" or return cleanup($self, 1);
631                 while (<$fh>) {
632                         # n.b. we do not restart for unlinked multi-pack-index
633                         # since it's not too huge, and the startup cost may
634                         # be higher.
635                         /\.(?:idx|pack) \(deleted\)$/ and
636                                 return cleanup($self, 1);
637                 }
638                 ++$ret;
639         }
640         $ret;
641 }
642
643 1;
644 __END__
645 =pod
646
647 =head1 NAME
648
649 PublicInbox::Git - git wrapper
650
651 =head1 VERSION
652
653 version 1.0
654
655 =head1 SYNOPSIS
656
657         use PublicInbox::Git;
658         chomp(my $git_dir = `git rev-parse --git-dir`);
659         $git_dir or die "GIT_DIR= must be specified\n";
660         my $git = PublicInbox::Git->new($git_dir);
661
662 =head1 DESCRIPTION
663
664 Unstable API outside of the L</new> method.
665 It requires L<git(1)> to be installed.
666
667 =head1 METHODS
668
669 =cut
670
671 =head2 new
672
673         my $git = PublicInbox::Git->new($git_dir);
674
675 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
676 This is the only public API method we support.  Everything else
677 in this module is subject to change.
678
679 =head1 SEE ALSO
680
681 L<Git>, L<PublicInbox::Import>
682
683 =head1 CONTACT
684
685 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
686
687 The mail archives are hosted at L<https://public-inbox.org/meta/>
688
689 =head1 COPYRIGHT
690
691 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
692
693 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
694
695 =cut