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