]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
7eaaeb8bc181531914e83d7ef111c2f83e2de247
[public-inbox.git] / lib / PublicInbox / Git.pm
1 # Copyright (C) 2014-2020 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 warnings;
12 use POSIX qw(dup2);
13 use IO::Handle; # ->autoflush
14 use File::Glob qw(bsd_glob GLOB_NOSORT);
15 use PublicInbox::Spawn qw(popen_rd);
16 use PublicInbox::Tmpfile;
17 use base qw(Exporter);
18 our @EXPORT_OK = qw(git_unquote git_quote);
19
20 use constant MAX_INFLIGHT =>
21         ($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF())
22         /
23         65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
24
25 my %GIT_ESC = (
26         a => "\a",
27         b => "\b",
28         f => "\f",
29         n => "\n",
30         r => "\r",
31         t => "\t",
32         v => "\013",
33         '"' => '"',
34         '\\' => '\\',
35 );
36 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
37
38
39 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
40 sub git_unquote ($) {
41         return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
42         $_[0] = $1;
43         $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
44         $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
45         $_[0];
46 }
47
48 sub git_quote ($) {
49         if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
50                       '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
51                 return qq{"$_[0]"};
52         }
53         $_[0];
54 }
55
56 sub new {
57         my ($class, $git_dir) = @_;
58         my @st;
59         $st[7] = $st[10] = 0;
60         # may contain {-tmp} field for File::Temp::Dir
61         bless { git_dir => $git_dir, st => \@st, -git_path => {} }, $class
62 }
63
64 sub git_path ($$) {
65         my ($self, $path) = @_;
66         $self->{-git_path}->{$path} ||= do {
67                 local $/ = "\n";
68                 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
69
70                 # git prior to 2.5.0 did not understand --git-path
71                 if ($str eq "--git-path\n$path") {
72                         $str = "$self->{git_dir}/$path";
73                 }
74                 $str;
75         };
76 }
77
78 sub alternates_changed {
79         my ($self) = @_;
80         my $alt = git_path($self, 'objects/info/alternates');
81         my @st = stat($alt) or return 0;
82         my $old_st = $self->{st};
83         # 10 - ctime, 7 - size
84         return 0 if ($st[10] == $old_st->[10] && $st[7] == $old_st->[7]);
85         $self->{st} = \@st;
86 }
87
88 sub last_check_err {
89         my ($self) = @_;
90         my $fh = $self->{err_c} or return;
91         sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
92         defined(sysread($fh, my $buf, -s $fh)) or
93                         fail($self, "sysread failed: $!");
94         $buf;
95 }
96
97 sub _bidi_pipe {
98         my ($self, $batch, $in, $out, $pid, $err) = @_;
99         if ($self->{$pid}) {
100                 if (defined $err) { # "err_c"
101                         my $fh = $self->{$err};
102                         sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
103                         truncate($fh, 0) or fail($self, "truncate failed: $!");
104                 }
105                 return;
106         }
107         my ($out_r, $out_w);
108         pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
109         my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
110                         qw(-c core.abbrev=40 cat-file), $batch);
111         my $redir = { 0 => $out_r };
112         if ($err) {
113                 my $id = "git.$self->{git_dir}$batch.err";
114                 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
115                 $self->{$err} = $fh;
116                 $redir->{2} = $fh;
117         }
118         my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
119         $self->{$pid} = $p;
120         $out_w->autoflush(1);
121         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
122                 fcntl($out_w, 1031, 4096);
123                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
124         }
125         $self->{$out} = $out_w;
126         $self->{$in} = $in_r;
127 }
128
129 sub read_cat_in_full ($$$) {
130         my ($self, $in, $left) = @_;
131         my $offset = 0;
132         my $buf = '';
133         while ($left > 0) {
134                 my $r = read($in, $buf, $left, $offset);
135                 defined($r) or fail($self, "read failed: $!");
136                 $r == 0 and fail($self, 'exited unexpectedly');
137                 $left -= $r;
138                 $offset += $r;
139         }
140         my $r = read($in, my $lf, 1);
141         defined($r) or fail($self, "read failed: $!");
142         fail($self, 'newline missing after blob') if ($r != 1 || $lf ne "\n");
143         \$buf;
144 }
145
146 sub _cat_async_step ($$$) {
147         my ($self, $inflight, $in) = @_;
148         my $pair = shift @$inflight or die 'BUG: inflight empty';
149         my ($cb, $arg) = @$pair;
150         local $/ = "\n";
151         my $head = $in->getline;
152         $head =~ / missing$/ and return
153                 eval { $cb->(undef, undef, undef, undef, $arg) };
154
155         $head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/ or
156                 fail($self, "Unexpected result from async git cat-file: $head");
157         my ($oid_hex, $type, $size) = ($1, $2, $3 + 0);
158         my $bref = read_cat_in_full($self, $in, $size);
159         eval { $cb->($bref, $oid_hex, $type, $size, $arg) };
160 }
161
162 sub cat_async_wait ($) {
163         my ($self) = @_;
164         my $inflight = delete $self->{inflight} or return;
165         my $in = $self->{in};
166         while (scalar(@$inflight)) {
167                 _cat_async_step($self, $inflight, $in);
168         }
169 }
170
171 sub cat_file {
172         my ($self, $obj, $ref) = @_;
173         my ($retried, $in, $head);
174         cat_async_wait($self);
175 again:
176         batch_prepare($self);
177         $self->{out}->print($obj, "\n") or fail($self, "write error: $!");
178
179         $in = $self->{in};
180         local $/ = "\n";
181         $head = $in->getline;
182         if ($head =~ / missing$/) {
183                 if (!$retried && alternates_changed($self)) {
184                         $retried = 1;
185                         cleanup($self);
186                         goto again;
187                 }
188                 return;
189         }
190         $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
191                 fail($self, "Unexpected result from git cat-file: $head");
192
193         my $size = $1;
194         $$ref = $size if $ref;
195         read_cat_in_full($self, $in, $size);
196 }
197
198 sub batch_prepare ($) { _bidi_pipe($_[0], qw(--batch in out pid)) }
199
200 sub check {
201         my ($self, $obj) = @_;
202         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
203         $self->{out_c}->print($obj, "\n") or fail($self, "write error: $!");
204         local $/ = "\n";
205         chomp(my $line = $self->{in_c}->getline);
206         my ($hex, $type, $size) = split(' ', $line);
207
208         # Future versions of git.git may show 'ambiguous', but for now,
209         # we must handle 'dangling' below (and maybe some other oddball
210         # stuff):
211         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
212         return if $type eq 'missing' || $type eq 'ambiguous';
213
214         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
215                 $size = $type + length("\n");
216                 my $r = read($self->{in_c}, my $buf, $size);
217                 defined($r) or fail($self, "read failed: $!");
218                 return;
219         }
220
221         ($hex, $type, $size);
222 }
223
224 sub _destroy {
225         my ($self, $in, $out, $pid, $err) = @_;
226         my $p = delete $self->{$pid} or return;
227         delete @$self{($in, $out)};
228         delete $self->{$err} if $err; # `err_c'
229
230         # PublicInbox::DS may not be loaded
231         eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
232         waitpid($p, 0) if $@; # wait synchronously if not in event loop
233 }
234
235 sub cat_async_abort ($) {
236         my ($self) = @_;
237         my $inflight = delete $self->{inflight} or die 'BUG: not in async';
238         cleanup($self);
239 }
240
241 sub fail {
242         my ($self, $msg) = @_;
243         $self->{inflight} ? cat_async_abort($self) : cleanup($self);
244         die $msg;
245 }
246
247 sub popen {
248         my ($self, @cmd) = @_;
249         @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
250         popen_rd(\@cmd);
251 }
252
253 sub qx {
254         my ($self, @cmd) = @_;
255         my $fh = $self->popen(@cmd);
256         local $/ = "\n";
257         return <$fh> if wantarray;
258         local $/;
259         <$fh>
260 }
261
262 # returns true if there are pending "git cat-file" processes
263 sub cleanup {
264         my ($self) = @_;
265         _destroy($self, qw(in out pid));
266         _destroy($self, qw(in_c out_c pid_c err_c));
267         !!($self->{pid} || $self->{pid_c});
268 }
269
270 # assuming a well-maintained repo, this should be a somewhat
271 # accurate estimation of its size
272 # TODO: show this in the WWW UI as a hint to potential cloners
273 sub packed_bytes {
274         my ($self) = @_;
275         my $n = 0;
276         my $pack_dir = git_path($self, 'objects/pack');
277         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
278                 $n += -s $p;
279         }
280         $n
281 }
282
283 sub DESTROY { cleanup(@_) }
284
285 sub local_nick ($) {
286         my ($self) = @_;
287         my $ret = '???';
288         # don't show full FS path, basename should be OK:
289         if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
290                 $ret = "/path/to/$1";
291         }
292         wantarray ? ($ret) : $ret;
293 }
294
295 sub host_prefix_url ($$) {
296         my ($env, $url) = @_;
297         return $url if index($url, '//') >= 0;
298         my $scheme = $env->{'psgi.url_scheme'};
299         my $host_port = $env->{HTTP_HOST} //
300                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
301         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
302 }
303
304 sub pub_urls {
305         my ($self, $env) = @_;
306         if (my $urls = $self->{cgit_url}) {
307                 return map { host_prefix_url($env, $_) } @$urls;
308         }
309         local_nick($self);
310 }
311
312 sub cat_async_begin {
313         my ($self) = @_;
314         cleanup($self) if alternates_changed($self);
315         batch_prepare($self);
316         die 'BUG: already in async' if $self->{inflight};
317         $self->{inflight} = [];
318 }
319
320 sub cat_async ($$$;$) {
321         my ($self, $oid, $cb, $arg) = @_;
322         my $inflight = $self->{inflight} or die 'BUG: not in async';
323         if (scalar(@$inflight) >= MAX_INFLIGHT) {
324                 _cat_async_step($self, $inflight, $self->{in});
325         }
326
327         $self->{out}->print($oid, "\n") or fail($self, "write error: $!");
328         push(@$inflight, [ $cb, $arg ]);
329 }
330
331 sub extract_cmt_time {
332         my ($bref, undef, undef, undef, $modified) = @_;
333
334         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
335                 my $cmt_time = $1 + 0;
336                 $$modified = $cmt_time if $cmt_time > $$modified;
337         }
338 }
339
340 # returns the modified time of a git repo, same as the "modified" field
341 # of a grokmirror manifest
342 sub modified ($) {
343         my ($self) = @_;
344         my $modified = 0;
345         my $fh = popen($self, qw(rev-parse --branches));
346         cat_async_begin($self);
347         local $/ = "\n";
348         while (my $oid = <$fh>) {
349                 chomp $oid;
350                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
351         }
352         cat_async_wait($self);
353         $modified || time;
354 }
355
356 1;
357 __END__
358 =pod
359
360 =head1 NAME
361
362 PublicInbox::Git - git wrapper
363
364 =head1 VERSION
365
366 version 1.0
367
368 =head1 SYNOPSIS
369
370         use PublicInbox::Git;
371         chomp(my $git_dir = `git rev-parse --git-dir`);
372         $git_dir or die "GIT_DIR= must be specified\n";
373         my $git = PublicInbox::Git->new($git_dir);
374
375 =head1 DESCRIPTION
376
377 Unstable API outside of the L</new> method.
378 It requires L<git(1)> to be installed.
379
380 =head1 METHODS
381
382 =cut
383
384 =head2 new
385
386         my $git = PublicInbox::Git->new($git_dir);
387
388 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
389 This is the only public API method we support.  Everything else
390 in this module is subject to change.
391
392 =head1 SEE ALSO
393
394 L<Git>, L<PublicInbox::Import>
395
396 =head1 CONTACT
397
398 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
399
400 The mail archives are hosted at L<https://public-inbox.org/meta/>
401
402 =head1 COPYRIGHT
403
404 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
405
406 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
407
408 =cut