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