]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
git: git_unquote handles double-quote and backslash
[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);
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
30 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
31 sub git_unquote ($) {
32         return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
33         $_[0] = $1;
34         $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
35         $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
36         $_[0];
37 }
38
39 sub new {
40         my ($class, $git_dir) = @_;
41         my @st;
42         $st[7] = $st[10] = 0;
43         bless { git_dir => $git_dir, st => \@st }, $class
44 }
45
46 sub alternates_changed {
47         my ($self) = @_;
48         my $alt = "$self->{git_dir}/objects/info/alternates";
49         my @st = stat($alt) or return 0;
50         my $old_st = $self->{st};
51         # 10 - ctime, 7 - size
52         return 0 if ($st[10] == $old_st->[10] && $st[7] == $old_st->[7]);
53         $self->{st} = \@st;
54 }
55
56 sub _bidi_pipe {
57         my ($self, $batch, $in, $out, $pid) = @_;
58         return if $self->{$pid};
59         my ($in_r, $in_w, $out_r, $out_w);
60
61         pipe($in_r, $in_w) or fail($self, "pipe failed: $!");
62         pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
63         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
64                 fcntl($out_w, 1031, 4096);
65                 fcntl($in_w, 1031, 4096) if $batch eq '--batch-check';
66         }
67
68         my @cmd = ('git', "--git-dir=$self->{git_dir}", qw(cat-file), $batch);
69         my $redir = { 0 => fileno($out_r), 1 => fileno($in_w) };
70         my $p = spawn(\@cmd, undef, $redir);
71         defined $p or fail($self, "spawn failed: $!");
72         $self->{$pid} = $p;
73         $out_w->autoflush(1);
74         $self->{$out} = $out_w;
75         $self->{$in} = $in_r;
76 }
77
78 sub cat_file {
79         my ($self, $obj, $ref) = @_;
80         my ($retried, $in, $head);
81
82 again:
83         batch_prepare($self);
84         $self->{out}->print($obj, "\n") or fail($self, "write error: $!");
85
86         $in = $self->{in};
87         local $/ = "\n";
88         $head = $in->getline;
89         if ($head =~ / missing$/) {
90                 if (!$retried && alternates_changed($self)) {
91                         $retried = 1;
92                         cleanup($self);
93                         goto again;
94                 }
95                 return;
96         }
97         $head =~ /^[0-9a-f]{40} \S+ (\d+)$/ or
98                 fail($self, "Unexpected result from git cat-file: $head");
99
100         my $size = $1;
101         my $ref_type = $ref ? ref($ref) : '';
102
103         my $rv;
104         my $left = $size;
105         $$ref = $size if ($ref_type eq 'SCALAR');
106         my $cb_err;
107
108         if ($ref_type eq 'CODE') {
109                 $rv = eval { $ref->($in, \$left) };
110                 $cb_err = $@;
111                 # drain the rest
112                 my $max = 8192;
113                 while ($left > 0) {
114                         my $r = read($in, my $x, $left > $max ? $max : $left);
115                         defined($r) or fail($self, "read failed: $!");
116                         $r == 0 and fail($self, 'exited unexpectedly');
117                         $left -= $r;
118                 }
119         } else {
120                 my $offset = 0;
121                 my $buf = '';
122                 while ($left > 0) {
123                         my $r = read($in, $buf, $left, $offset);
124                         defined($r) or fail($self, "read failed: $!");
125                         $r == 0 and fail($self, 'exited unexpectedly');
126                         $left -= $r;
127                         $offset += $r;
128                 }
129                 $rv = \$buf;
130         }
131
132         my $r = read($in, my $buf, 1);
133         defined($r) or fail($self, "read failed: $!");
134         fail($self, 'newline missing after blob') if ($r != 1 || $buf ne "\n");
135         die $cb_err if $cb_err;
136
137         $rv;
138 }
139
140 sub batch_prepare ($) { _bidi_pipe($_[0], qw(--batch in out pid)) }
141
142 sub check {
143         my ($self, $obj) = @_;
144         $self->_bidi_pipe(qw(--batch-check in_c out_c pid_c));
145         $self->{out_c}->print($obj, "\n") or fail($self, "write error: $!");
146         local $/ = "\n";
147         chomp(my $line = $self->{in_c}->getline);
148         my ($hex, $type, $size) = split(' ', $line);
149         return if $type eq 'missing';
150         ($hex, $type, $size);
151 }
152
153 sub _destroy {
154         my ($self, $in, $out, $pid) = @_;
155         my $p = delete $self->{$pid} or return;
156         foreach my $f ($in, $out) {
157                 delete $self->{$f};
158         }
159         waitpid $p, 0;
160 }
161
162 sub fail {
163         my ($self, $msg) = @_;
164         cleanup($self);
165         die $msg;
166 }
167
168 sub popen {
169         my ($self, @cmd) = @_;
170         @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
171         popen_rd(\@cmd);
172 }
173
174 sub qx {
175         my ($self, @cmd) = @_;
176         my $fh = $self->popen(@cmd);
177         defined $fh or return;
178         local $/ = "\n";
179         return <$fh> if wantarray;
180         local $/;
181         <$fh>
182 }
183
184 sub cleanup {
185         my ($self) = @_;
186         _destroy($self, qw(in out pid));
187         _destroy($self, qw(in_c out_c pid_c));
188 }
189
190 # assuming a well-maintained repo, this should be a somewhat
191 # accurate estimation of its size
192 # TODO: show this in the WWW UI as a hint to potential cloners
193 sub packed_bytes {
194         my ($self) = @_;
195         my $n = 0;
196         foreach my $p (glob("$self->{git_dir}/objects/pack/*.pack")) {
197                 $n += -s $p;
198         }
199         $n
200 }
201
202 sub DESTROY { cleanup(@_) }
203
204 1;
205 __END__
206 =pod
207
208 =head1 NAME
209
210 PublicInbox::Git - git wrapper
211
212 =head1 VERSION
213
214 version 1.0
215
216 =head1 SYNOPSIS
217
218         use PublicInbox::Git;
219         chomp(my $git_dir = `git rev-parse --git-dir`);
220         $git_dir or die "GIT_DIR= must be specified\n";
221         my $git = PublicInbox::Git->new($git_dir);
222
223 =head1 DESCRIPTION
224
225 Unstable API outside of the L</new> method.
226 It requires L<git(1)> to be installed.
227
228 =head1 METHODS
229
230 =cut
231
232 =head2 new
233
234         my $git = PublicInbox::Git->new($git_dir);
235
236 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
237 This is the only public API method we support.  Everything else
238 in this module is subject to change.
239
240 =head1 SEE ALSO
241
242 L<Git>, L<PublicInbox::Import>
243
244 =head1 CONTACT
245
246 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
247
248 The mail archives are hosted at L<https://public-inbox.org/meta/>
249
250 =head1 COPYRIGHT
251
252 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
253
254 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
255
256 =cut