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