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