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