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