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