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>
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;
14 use PublicInbox::Spawn qw(spawn popen_rd);
15 use base qw(Exporter);
16 our @EXPORT_OK = qw(git_unquote git_quote);
29 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
32 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
34 return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
36 $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
37 $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
42 if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
43 '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
50 my ($class, $git_dir) = @_;
53 # may contain {-tmp} field for File::Temp::Dir
54 bless { git_dir => $git_dir, st => \@st, -git_path => {} }, $class
58 my ($self, $path) = @_;
59 $self->{-git_path}->{$path} ||= do {
61 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
63 # git prior to 2.5.0 did not understand --git-path
64 if ($str eq "--git-path\n$path") {
65 $str = "$self->{git_dir}/$path";
71 sub alternates_changed {
73 my $alt = git_path($self, 'objects/info/alternates');
74 my @st = stat($alt) or return 0;
75 my $old_st = $self->{st};
76 # 10 - ctime, 7 - size
77 return 0 if ($st[10] == $old_st->[10] && $st[7] == $old_st->[7]);
83 my $fh = $self->{err_c} or return;
84 sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
85 defined(sysread($fh, my $buf, -s $fh)) or
86 fail($self, "sysread failed: $!");
91 my ($self, $batch, $in, $out, $pid, $err) = @_;
93 if (defined $err) { # "err_c"
94 my $fh = $self->{$err};
95 sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
96 truncate($fh, 0) or fail($self, "truncate failed: $!");
100 my ($in_r, $in_w, $out_r, $out_w);
102 pipe($in_r, $in_w) or fail($self, "pipe failed: $!");
103 pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
104 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
105 fcntl($out_w, 1031, 4096);
106 fcntl($in_w, 1031, 4096) if $batch eq '--batch-check';
109 my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
110 qw(-c core.abbrev=40 cat-file), $batch);
111 my $redir = { 0 => fileno($out_r), 1 => fileno($in_w) };
113 open(my $fh, '+>', undef) or fail($self, "open.err failed: $!");
115 $redir->{2} = fileno($fh);
117 my $p = spawn(\@cmd, undef, $redir);
118 defined $p or fail($self, "spawn failed: $!");
120 $out_w->autoflush(1);
121 $self->{$out} = $out_w;
122 $self->{$in} = $in_r;
126 my ($self, $obj, $ref) = @_;
127 my ($retried, $in, $head);
130 batch_prepare($self);
131 $self->{out}->print($obj, "\n") or fail($self, "write error: $!");
135 $head = $in->getline;
136 if ($head =~ / missing$/) {
137 if (!$retried && alternates_changed($self)) {
144 $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
145 fail($self, "Unexpected result from git cat-file: $head");
150 $$ref = $size if $ref;
155 my $r = read($in, $buf, $left, $offset);
156 defined($r) or fail($self, "read failed: $!");
157 $r == 0 and fail($self, 'exited unexpectedly');
163 my $r = read($in, my $lf, 1);
164 defined($r) or fail($self, "read failed: $!");
165 fail($self, 'newline missing after blob') if ($r != 1 || $lf ne "\n");
170 sub batch_prepare ($) { _bidi_pipe($_[0], qw(--batch in out pid)) }
173 my ($self, $obj) = @_;
174 _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
175 $self->{out_c}->print($obj, "\n") or fail($self, "write error: $!");
177 chomp(my $line = $self->{in_c}->getline);
178 my ($hex, $type, $size) = split(' ', $line);
180 # Future versions of git.git may show 'ambiguous', but for now,
181 # we must handle 'dangling' below (and maybe some other oddball
183 # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
184 return if $type eq 'missing' || $type eq 'ambiguous';
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: $!");
193 ($hex, $type, $size);
197 my ($self, $in, $out, $pid, $err) = @_;
198 my $p = delete $self->{$pid} or return;
199 delete @$self{($in, $out)};
200 delete $self->{$err} if $err; # `err_c'
205 my ($self, $msg) = @_;
211 my ($self, @cmd) = @_;
212 @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
217 my ($self, @cmd) = @_;
218 my $fh = $self->popen(@cmd);
219 defined $fh or return;
221 return <$fh> if wantarray;
226 # returns true if there are pending "git cat-file" processes
229 _destroy($self, qw(in out pid));
230 _destroy($self, qw(in_c out_c pid_c err_c));
231 !!($self->{pid} || $self->{pid_c});
234 # assuming a well-maintained repo, this should be a somewhat
235 # accurate estimation of its size
236 # TODO: show this in the WWW UI as a hint to potential cloners
240 my $pack_dir = git_path($self, 'objects/pack');
241 foreach my $p (glob("$pack_dir/*.pack")) {
247 sub DESTROY { cleanup(@_) }
252 # don't show full FS path, basename should be OK:
253 if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
254 $ret = "/path/to/$1";
256 wantarray ? ($ret) : $ret;
259 # show the blob URL for cgit/gitweb/whatever
261 my ($self, $oid) = @_;
262 # blob_url_format = "https://example.com/foo.git/blob/%s"
263 if (my $bfu = $self->{blob_url_format}) {
264 return map { sprintf($_, $oid) } @$bfu if wantarray;
265 return sprintf($bfu->[0], $oid);
270 sub host_prefix_url ($$) {
271 my ($env, $url) = @_;
272 return $url if index($url, '//') >= 0;
273 my $scheme = $env->{'psgi.url_scheme'};
274 my $host_port = $env->{HTTP_HOST} ||
275 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
276 "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
280 my ($self, $env) = @_;
281 if (my $urls = $self->{cgit_url}) {
282 return map { host_prefix_url($env, $_) } @$urls;
287 sub commit_title ($$) {
288 my ($self, $oid) = @_; # PublicInbox::Git, $sha1hex
289 my $buf = cat_file($self, $oid) or return;
291 ($$buf =~ /\r?\n\r?\n([^\r\n]+)\r?\n?/)[0]
294 # returns the modified time of a git repo, same as the "modified" field
295 # of a grokmirror manifest
299 my $fh = popen($self, qw(rev-parse --branches));
300 defined $fh or return $modified;
302 foreach my $oid (<$fh>) {
304 my $buf = cat_file($self, $oid) or next;
305 $$buf =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm or next;
306 my $cmt_time = $1 + 0;
307 $modified = $cmt_time if $cmt_time > $modified;
318 PublicInbox::Git - git wrapper
326 use PublicInbox::Git;
327 chomp(my $git_dir = `git rev-parse --git-dir`);
328 $git_dir or die "GIT_DIR= must be specified\n";
329 my $git = PublicInbox::Git->new($git_dir);
333 Unstable API outside of the L</new> method.
334 It requires L<git(1)> to be installed.
342 my $git = PublicInbox::Git->new($git_dir);
344 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
345 This is the only public API method we support. Everything else
346 in this module is subject to change.
350 L<Git>, L<PublicInbox::Import>
354 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
356 The mail archives are hosted at L<https://public-inbox.org/meta/>
360 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
362 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>