]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Gcf2.pm
gcf2: libgit2-based git cat-file alternative
[public-inbox.git] / lib / PublicInbox / Gcf2.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # git-cat-file based on libgit2
5 package PublicInbox::Gcf2;
6 use strict;
7 use PublicInbox::Spawn qw(which popen_rd);
8 use Fcntl qw(LOCK_EX);
9 my (%CFG, $c_src, $lockfh);
10 BEGIN {
11         # PublicInbox::Spawn will set PERL_INLINE_DIRECTORY
12         # to ~/.cache/public-inbox/inline-c if it exists
13         my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //
14                 die 'PERL_INLINE_DIRECTORY not defined';
15         my $f = "$inline_dir/.public-inbox.lock";
16         open $lockfh, '>', $f or die "failed to open $f: $!\n";
17         my $pc = which($ENV{PKG_CONFIG} // 'pkg-config');
18         my ($dir) = (__FILE__ =~ m!\A(.+?)/[^/]+\z!);
19         my $rdr = {};
20         open $rdr->{2}, '>', '/dev/null' or die "open /dev/null: $!";
21         for my $x (qw(libgit2)) {
22                 my $l = popen_rd([$pc, '--libs', $x], undef, $rdr);
23                 $l = do { local $/; <$l> };
24                 next if $?;
25                 my $c = popen_rd([$pc, '--cflags', $x], undef, $rdr);
26                 $c = do { local $/; <$c> };
27                 next if $?;
28
29                 # note: we name C source files .h to prevent
30                 # ExtUtils::MakeMaker from automatically trying to
31                 # build them.
32                 my $f = "$dir/gcf2_$x.h";
33                 if (open(my $fh, '<', $f)) {
34                         chomp($l, $c);
35                         local $/;
36                         $c_src = <$fh>;
37                         $CFG{LIBS} = $l;
38                         $CFG{CCFLAGSEX} = $c;
39                         last;
40                 } else {
41                         die "E: $f: $!\n";
42                 }
43         }
44         die "E: libgit2 not installed\n" unless $c_src;
45
46         # CentOS 7.x ships Inline 0.53, 0.64+ has built-in locking
47         flock($lockfh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
48 }
49
50 # we use Capitalized and ALLCAPS for compatibility with old Inline::C
51 use Inline C => Config => %CFG, BOOT => 'git_libgit2_init();';
52 use Inline C => $c_src;
53 undef $c_src;
54 undef %CFG;
55 undef $lockfh;
56 1;