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