]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
ff3ac40f59511aab560b114d4ad73eecc3f067b2
[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         my ($in_r, $p) = popen_rd(\@cmd, undef, $rdr);
160         awaitpid($self->{$pid} = $p, undef);
161         $self->{"$pid.owner"} = $$;
162         $out_w->autoflush(1);
163         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
164                 fcntl($out_w, 1031, 4096);
165                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
166         }
167         $out_w->blocking(0);
168         $self->{$out} = $out_w;
169         $self->{$in} = $in_r;
170 }
171
172 sub poll_in ($) { IO::Poll::_poll($RDTIMEO, fileno($_[0]), my $ev = POLLIN) }
173
174 sub my_read ($$$) {
175         my ($fh, $rbuf, $len) = @_;
176         my $left = $len - length($$rbuf);
177         my $r;
178         while ($left > 0) {
179                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
180                 if ($r) {
181                         $left -= $r;
182                 } elsif (defined($r)) { # EOF
183                         return 0;
184                 } else {
185                         next if ($! == EAGAIN and poll_in($fh));
186                         next if $! == EINTR; # may be set by sysread or poll_in
187                         return; # unrecoverable error
188                 }
189         }
190         my $no_pad = substr($$rbuf, 0, $len, '');
191         \$no_pad;
192 }
193
194 sub my_readline ($$) {
195         my ($fh, $rbuf) = @_;
196         while (1) {
197                 if ((my $n = index($$rbuf, "\n")) >= 0) {
198                         return substr($$rbuf, 0, $n + 1, '');
199                 }
200                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf))
201                                                                 and next;
202
203                 # return whatever's left on EOF
204                 return substr($$rbuf, 0, length($$rbuf)+1, '') if defined($r);
205
206                 next if ($! == EAGAIN and poll_in($fh));
207                 next if $! == EINTR; # may be set by sysread or poll_in
208                 return; # unrecoverable error
209         }
210 }
211
212 sub cat_async_retry ($$) {
213         my ($self, $inflight) = @_;
214
215         # {inflight} may be non-existent, but if it isn't we delete it
216         # here to prevent cleanup() from waiting:
217         delete $self->{inflight};
218         cleanup($self);
219
220         $self->{inflight} = $inflight;
221         batch_prepare($self);
222         my $buf = '';
223         for (my $i = 0; $i < @$inflight; $i += 3) {
224                 $buf .= "$inflight->[$i]\n";
225         }
226         $self->{out}->blocking(1); # brand new pipe, should never block
227         print { $self->{out} } $buf or $self->fail("write error: $!");
228         $self->{out}->blocking(0);
229         my $req = shift @$inflight;
230         unshift(@$inflight, \$req); # \$ref to indicate retried
231
232         cat_async_step($self, $inflight); # take one step
233 }
234
235 sub cat_async_step ($$) {
236         my ($self, $inflight) = @_;
237         die 'BUG: inflight empty or odd' if scalar(@$inflight) < 3;
238         my ($req, $cb, $arg) = @$inflight[0, 1, 2];
239         my $rbuf = delete($self->{rbuf}) // \(my $new = '');
240         my ($bref, $oid, $type, $size);
241         my $head = my_readline($self->{in}, $rbuf);
242         # ->fail may be called via Gcf2Client.pm
243         if ($head =~ /^([0-9a-f]{40,}) (\S+) ([0-9]+)$/) {
244                 ($oid, $type, $size) = ($1, $2, $3 + 0);
245                 $bref = my_read($self->{in}, $rbuf, $size + 1) or
246                         $self->fail(defined($bref) ? 'read EOF' : "read: $!");
247                 chop($$bref) eq "\n" or $self->fail('LF missing after blob');
248         } elsif ($head =~ s/ missing\n//s) {
249                 $oid = $head;
250                 # ref($req) indicates it's already been retried
251                 # -gcf2 retries internally, so it never hits this path:
252                 if (!ref($req) && !$in_cleanup && $self->alternates_changed) {
253                         return cat_async_retry($self, $inflight);
254                 }
255                 $type = 'missing';
256                 $oid = ref($req) ? $$req : $req if $oid eq '';
257         } else {
258                 my $err = $! ? " ($!)" : '';
259                 $self->fail("bad result from async cat-file: $head$err");
260         }
261         $self->{rbuf} = $rbuf if $$rbuf ne '';
262         splice(@$inflight, 0, 3); # don't retry $cb on ->fail
263         eval { $cb->($bref, $oid, $type, $size, $arg) };
264         async_err($self, $req, $oid, $@, 'cat') if $@;
265 }
266
267 sub cat_async_wait ($) {
268         my ($self) = @_;
269         my $inflight = $self->{inflight} or return;
270         while (scalar(@$inflight)) {
271                 cat_async_step($self, $inflight);
272         }
273 }
274
275 sub batch_prepare ($) {
276         _bidi_pipe($_[0], qw(--batch in out pid));
277 }
278
279 sub _cat_file_cb {
280         my ($bref, $oid, $type, $size, $result) = @_;
281         @$result = ($bref, $oid, $type, $size);
282 }
283
284 sub cat_file {
285         my ($self, $oid) = @_;
286         my $result = [];
287         cat_async($self, $oid, \&_cat_file_cb, $result);
288         cat_async_wait($self);
289         wantarray ? @$result : $result->[0];
290 }
291
292 sub check_async_step ($$) {
293         my ($self, $inflight_c) = @_;
294         die 'BUG: inflight empty or odd' if scalar(@$inflight_c) < 3;
295         my ($req, $cb, $arg) = @$inflight_c[0, 1, 2];
296         my $rbuf = delete($self->{rbuf_c}) // \(my $new = '');
297         chomp(my $line = my_readline($self->{in_c}, $rbuf));
298         my ($hex, $type, $size) = split(/ /, $line);
299
300         # Future versions of git.git may have type=ambiguous, but for now,
301         # we must handle 'dangling' below (and maybe some other oddball
302         # stuff):
303         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
304         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
305                 my $ret = my_read($self->{in_c}, $rbuf, $type + 1);
306                 $self->fail(defined($ret) ? 'read EOF' : "read: $!") if !$ret;
307         }
308         $self->{rbuf_c} = $rbuf if $$rbuf ne '';
309         splice(@$inflight_c, 0, 3); # don't retry $cb on ->fail
310         eval { $cb->($hex, $type, $size, $arg, $self) };
311         async_err($self, $req, $hex, $@, 'check') if $@;
312 }
313
314 sub check_async_wait ($) {
315         my ($self) = @_;
316         my $inflight_c = $self->{inflight_c} or return;
317         while (scalar(@$inflight_c)) {
318                 check_async_step($self, $inflight_c);
319         }
320 }
321
322 sub check_async_begin ($) {
323         my ($self) = @_;
324         cleanup($self) if alternates_changed($self);
325         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
326         die 'BUG: already in async check' if $self->{inflight_c};
327         $self->{inflight_c} = [];
328 }
329
330 sub write_all {
331         my ($self, $out, $buf, $read_step, $inflight) = @_;
332         $read_step->($self, $inflight) while @$inflight >= MAX_INFLIGHT;
333         do {
334                 my $w = syswrite($out, $buf);
335                 if (defined $w) {
336                         return if $w == length($buf);
337                         substr($buf, 0, $w, ''); # sv_chop
338                 } elsif ($! != EAGAIN) {
339                         $self->fail("write: $!");
340                 }
341                 $read_step->($self, $inflight);
342         } while (1);
343 }
344
345 sub check_async ($$$$) {
346         my ($self, $oid, $cb, $arg) = @_;
347         my $inflight_c = $self->{inflight_c} // check_async_begin($self);
348         write_all($self, $self->{out_c}, $oid."\n",
349                 \&check_async_step, $inflight_c);
350         push(@$inflight_c, $oid, $cb, $arg);
351 }
352
353 sub _check_cb { # check_async callback
354         my ($hex, $type, $size, $result) = @_;
355         @$result = ($hex, $type, $size);
356 }
357
358 sub check {
359         my ($self, $oid) = @_;
360         my $result = [];
361         check_async($self, $oid, \&_check_cb, $result);
362         check_async_wait($self);
363         my ($hex, $type, $size) = @$result;
364
365         # Future versions of git.git may show 'ambiguous', but for now,
366         # we must handle 'dangling' below (and maybe some other oddball
367         # stuff):
368         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
369         return if $type eq 'missing' || $type eq 'ambiguous';
370         return if $hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop';
371         ($hex, $type, $size);
372 }
373
374 sub _destroy {
375         my ($self, $rbuf, $in, $out, $pid, $err) = @_;
376         delete @$self{($rbuf, $in, $out)};
377         delete $self->{$err} if $err; # `err_c'
378
379         # GitAsyncCat::event_step may delete {$pid}
380         my $p = delete($self->{$pid}) // return;
381         awaitpid($p) if $$ == $self->{"$pid.owner"};
382 }
383
384 sub async_abort ($) {
385         my ($self) = @_;
386         while (scalar(@{$self->{inflight_c} // []}) ||
387                         scalar(@{$self->{inflight} // []})) {
388                 for my $c ('', '_c') {
389                         my $q = $self->{"inflight$c"} or next;
390                         while (@$q) {
391                                 my ($req, $cb, $arg) = splice(@$q, 0, 3);
392                                 $req = $$req if ref($req);
393                                 $req =~ s/ .*//; # drop git_dir for Gcf2Client
394                                 eval { $cb->(undef, $req, undef, undef, $arg) };
395                                 warn "E: (in abort) $req: $@" if $@;
396                         }
397                         delete $self->{"inflight$c"};
398                         delete $self->{"rbuf$c"};
399                 }
400         }
401         cleanup($self);
402 }
403
404 sub fail { # may be augmented in subclasses
405         my ($self, $msg) = @_;
406         async_abort($self);
407         croak(ref($self) . ' ' . ($self->{git_dir} // '') . ": $msg");
408 }
409
410 sub async_err ($$$$$) {
411         my ($self, $req, $oid, $err, $action) = @_;
412         $req = $$req if ref($req); # retried
413         my $msg = "E: $action $req ($oid): $err";
414         $async_warn ? carp($msg) : $self->fail($msg);
415 }
416
417 # $git->popen(qw(show f00)); # or
418 # $git->popen(qw(show f00), { GIT_CONFIG => ... }, { 2 => ... });
419 sub popen {
420         my ($self, $cmd) = splice(@_, 0, 2);
421         $cmd = [ 'git', "--git-dir=$self->{git_dir}",
422                 ref($cmd) ? @$cmd : ($cmd, grep { defined && !ref } @_) ];
423         popen_rd($cmd, grep { !defined || ref } @_); # env and opt
424 }
425
426 # same args as popen above
427 sub qx {
428         my $fh = popen(@_);
429         if (wantarray) {
430                 my @ret = <$fh>;
431                 close $fh; # caller should check $?
432                 @ret;
433         } else {
434                 local $/;
435                 my $ret = <$fh>;
436                 close $fh; # caller should check $?
437                 $ret;
438         }
439 }
440
441 sub date_parse {
442         my $self = shift;
443         map {
444                 substr($_, length('--max-age='), -1)
445         } $self->qx('rev-parse', map { "--since=$_" } @_);
446 }
447
448 # check_async and cat_async may trigger the other, so ensure they're
449 # both completely done by using this:
450 sub async_wait_all ($) {
451         my ($self) = @_;
452         while (scalar(@{$self->{inflight_c} // []}) ||
453                         scalar(@{$self->{inflight} // []})) {
454                 check_async_wait($self);
455                 cat_async_wait($self);
456         }
457 }
458
459 # returns true if there are pending "git cat-file" processes
460 sub cleanup {
461         my ($self, $lazy) = @_;
462         return 1 if $lazy && (scalar(@{$self->{inflight_c} // []}) ||
463                                 scalar(@{$self->{inflight} // []}));
464         local $in_cleanup = 1;
465         delete $self->{async_cat};
466         delete $self->{async_chk};
467         async_wait_all($self);
468         delete $self->{inflight};
469         delete $self->{inflight_c};
470         _destroy($self, qw(rbuf in out pid));
471         _destroy($self, qw(rbuf_c in_c out_c pid_c err_c));
472         undef;
473 }
474
475 # assuming a well-maintained repo, this should be a somewhat
476 # accurate estimation of its size
477 # TODO: show this in the WWW UI as a hint to potential cloners
478 sub packed_bytes {
479         my ($self) = @_;
480         my $n = 0;
481         my $pack_dir = git_path($self, 'objects/pack');
482         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
483                 $n += -s $p;
484         }
485         $n
486 }
487
488 sub DESTROY { cleanup(@_) }
489
490 sub local_nick ($) {
491         # don't show full FS path, basename should be OK:
492         $_[0]->{nick} // ($_[0]->{git_dir} =~ m!/([^/]+?)(?:/*\.git/*)?\z! ?
493                         "$1.git" : undef);
494 }
495
496 sub host_prefix_url ($$) {
497         my ($env, $url) = @_;
498         return $url if index($url, '//') >= 0;
499         my $host_port = $env->{HTTP_HOST} //
500                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
501         my $sn = $env->{SCRIPT_NAME} // '';
502         "$env->{'psgi.url_scheme'}://$host_port$sn/$url";
503 }
504
505 sub base_url { # for coderepos, PSGI-only
506         my ($self, $env) = @_; # env - PSGI env
507         my $nick = $self->{nick} // return undef;
508         my $url = host_prefix_url($env, '');
509         # for mount in Plack::Builder
510         $url .= '/' if substr($url, -1, 1) ne '/';
511         $url . $nick . '/';
512 }
513
514 sub isrch {} # TODO
515
516 sub pub_urls {
517         my ($self, $env) = @_;
518         if (my $urls = $self->{cgit_url}) {
519                 map { host_prefix_url($env, $_) } @$urls;
520         } else {
521                 (base_url($self, $env) // '???');
522         }
523 }
524
525 sub cat_async_begin {
526         my ($self) = @_;
527         cleanup($self) if $self->alternates_changed;
528         $self->batch_prepare;
529         die 'BUG: already in async' if $self->{inflight};
530         $self->{inflight} = [];
531 }
532
533 sub cat_async ($$$;$) {
534         my ($self, $oid, $cb, $arg) = @_;
535         my $inflight = $self->{inflight} // cat_async_begin($self);
536         write_all($self, $self->{out}, $oid."\n", \&cat_async_step, $inflight);
537         push(@$inflight, $oid, $cb, $arg);
538 }
539
540 # returns the modified time of a git repo, same as the "modified" field
541 # of a grokmirror manifest
542 sub modified ($) {
543         # committerdate:unix is git 2.9.4+ (2017-05-05), so using raw instead
544         my $fh = popen($_[0], qw[for-each-ref --sort=-committerdate
545                                 --format=%(committerdate:raw) --count=1]);
546         (split(/ /, <$fh> // time))[0] + 0; # integerize for JSON
547 }
548
549 sub try_cat {
550         my ($path) = @_;
551         open(my $fh, '<', $path) or return '';
552         local $/;
553         <$fh> // '';
554 }
555
556 sub cat_desc ($) {
557         my $desc = try_cat($_[0]);
558         chomp $desc;
559         utf8::decode($desc);
560         $desc =~ s/\s+/ /smg;
561         $desc eq '' ? undef : $desc;
562 }
563
564 sub description {
565         cat_desc("$_[0]->{git_dir}/description") // 'Unnamed repository';
566 }
567
568 sub cloneurl {
569         my ($self, $env) = @_;
570         $self->{cloneurl} // do {
571                 my @urls = split(/\s+/s, try_cat("$self->{git_dir}/cloneurl"));
572                 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
573         } // [ substr(base_url($self, $env), 0, -1) ];
574 }
575
576 # for grokmirror, which doesn't read gitweb.description
577 # templates/hooks--update.sample and git-multimail in git.git
578 # only match "Unnamed repository", not the full contents of
579 # templates/this--description in git.git
580 sub manifest_entry {
581         my ($self, $epoch, $default_desc) = @_;
582         my $fh = $self->popen('show-ref');
583         my $dig = Digest::SHA->new(1);
584         while (read($fh, my $buf, 65536)) {
585                 $dig->add($buf);
586         }
587         close $fh or return; # empty, uninitialized git repo
588         undef $fh; # for open, below
589         my $git_dir = $self->{git_dir};
590         my $ent = {
591                 fingerprint => $dig->hexdigest,
592                 reference => undef,
593                 modified => modified($self),
594         };
595         chomp(my $owner = $self->qx('config', 'gitweb.owner'));
596         utf8::decode($owner);
597         $ent->{owner} = $owner eq '' ? undef : $owner;
598         my $desc = description($self);
599         if (defined $epoch && index($desc, 'Unnamed repository') == 0) {
600                 $desc = "$default_desc [epoch $epoch]";
601         }
602         $ent->{description} = $desc;
603         if (open($fh, '<', "$git_dir/objects/info/alternates")) {
604                 # n.b.: GitPython doesn't seem to handle comments or C-quoted
605                 # strings like native git does; and we don't for now, either.
606                 local $/ = "\n";
607                 chomp(my @alt = <$fh>);
608
609                 # grokmirror only supports 1 alternate for "reference",
610                 if (scalar(@alt) == 1) {
611                         my $objdir = "$git_dir/objects";
612                         my $ref = File::Spec->rel2abs($alt[0], $objdir);
613                         $ref =~ s!/[^/]+/?\z!!; # basename
614                         $ent->{reference} = $ref;
615                 }
616         }
617         $ent;
618 }
619
620 # returns true if there are pending cat-file processes
621 sub cleanup_if_unlinked {
622         my ($self) = @_;
623         return cleanup($self, 1) if $^O ne 'linux';
624         # Linux-specific /proc/$PID/maps access
625         # TODO: support this inside git.git
626         my $ret = 0;
627         for my $fld (qw(pid pid_c)) {
628                 my $pid = $self->{$fld} // next;
629                 open my $fh, '<', "/proc/$pid/maps" or return cleanup($self, 1);
630                 while (<$fh>) {
631                         # n.b. we do not restart for unlinked multi-pack-index
632                         # since it's not too huge, and the startup cost may
633                         # be higher.
634                         /\.(?:idx|pack) \(deleted\)$/ and
635                                 return cleanup($self, 1);
636                 }
637                 ++$ret;
638         }
639         $ret;
640 }
641
642 1;
643 __END__
644 =pod
645
646 =head1 NAME
647
648 PublicInbox::Git - git wrapper
649
650 =head1 VERSION
651
652 version 1.0
653
654 =head1 SYNOPSIS
655
656         use PublicInbox::Git;
657         chomp(my $git_dir = `git rev-parse --git-dir`);
658         $git_dir or die "GIT_DIR= must be specified\n";
659         my $git = PublicInbox::Git->new($git_dir);
660
661 =head1 DESCRIPTION
662
663 Unstable API outside of the L</new> method.
664 It requires L<git(1)> to be installed.
665
666 =head1 METHODS
667
668 =cut
669
670 =head2 new
671
672         my $git = PublicInbox::Git->new($git_dir);
673
674 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
675 This is the only public API method we support.  Everything else
676 in this module is subject to change.
677
678 =head1 SEE ALSO
679
680 L<Git>, L<PublicInbox::Import>
681
682 =head1 CONTACT
683
684 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
685
686 The mail archives are hosted at L<https://public-inbox.org/meta/>
687
688 =head1 COPYRIGHT
689
690 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
691
692 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
693
694 =cut