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