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