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