1 # Copyright (C) 2014-2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
4 # Used throughout the project for reading configuration
5 package PublicInbox::Config;
8 require PublicInbox::Inbox;
9 use PublicInbox::Spawn qw(popen_rd);
11 # returns key-value pairs of config directives in a hash
12 # if keys may be multi-value, the value is an array ref containing all values
14 my ($class, $file) = @_;
15 $file = default_file() unless defined($file);
16 $file = ref $file ? $file : git_config_dump($file);
17 my $self = bless $file, $class;
20 $self->{-by_addr} ||= {};
21 $self->{-by_name} ||= {};
22 $self->{-by_newsgroup} ||= {};
23 $self->{-limiters} ||= {};
28 my ($self, $recipient) = @_;
29 my $addr = lc($recipient);
30 my $inbox = $self->{-by_addr}->{$addr};
31 return $inbox if $inbox;
35 foreach my $k (keys %$self) {
36 $k =~ /\A(publicinbox\.[\w-]+)\.address\z/ or next;
38 if (ref($v) eq "ARRAY") {
39 foreach my $alias (@$v) {
40 (lc($alias) eq $addr) or next;
45 (lc($v) eq $addr) or next;
50 defined $pfx or return;
54 sub lookup_name ($$) {
55 my ($self, $name) = @_;
56 $self->{-by_name}->{$name} || _fill($self, "publicinbox.$name");
62 foreach my $k (keys %$self) {
63 $k =~ /\Apublicinbox\.([A-Z0-9a-z-]+)\.mainrepo\z/ or next;
66 my $ibx = lookup_name($self, $1) or next;
71 sub lookup_newsgroup {
74 my $rv = $self->{-by_newsgroup}->{$ng};
77 foreach my $k (keys %$self) {
78 $k =~ /\A(publicinbox\.[\w-]+)\.newsgroup\z/ or next;
82 $rv = _fill($self, $pfx);
90 my ($self, $name) = @_;
91 $self->{-limiters}->{$name} ||= do {
92 require PublicInbox::Qspawn;
93 my $key = "limiter.$name.max";
94 PublicInbox::Qspawn::Limiter->new($self->{$key});
99 my ($self, $inbox, $key) = @_;
101 $self->{"publicinbox.$inbox.$key"};
104 sub config_dir { $ENV{PI_DIR} || "$ENV{HOME}/.public-inbox" }
107 my $f = $ENV{PI_CONFIG};
108 return $f if defined $f;
109 config_dir() . '/config';
112 sub git_config_dump {
115 my @cmd = (qw/git config/, "--file=$file", '-l');
116 my $cmd = join(' ', @cmd);
117 my $fh = popen_rd(\@cmd) or die "popen_rd failed for $file: $!\n";
120 foreach my $line (<$fh>) {
122 my ($k, $v) = split(/=/, $line, 2);
126 if (ref($cur) eq "ARRAY") {
129 $rv{$k} = [ $cur, $v ];
135 close $fh or die "failed to close ($cmd) pipe: $?";
140 my ($self, $pfx) = @_;
143 foreach my $k (qw(mainrepo address filter url newsgroup
144 infourl watch watchheader httpbackendmax)) {
145 my $v = $self->{"$pfx.$k"};
146 $rv->{$k} = $v if defined $v;
148 return unless $rv->{mainrepo};
150 $name =~ s/\Apublicinbox\.//;
152 $rv->{-pi_config} = $self;
153 $rv = PublicInbox::Inbox->new($rv);
154 my $v = $rv->{address};
155 if (ref($v) eq 'ARRAY') {
156 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
158 $self->{-by_addr}->{lc($v)} = $rv;
160 if (my $ng = $rv->{newsgroup}) {
161 $self->{-by_newsgroup}->{$ng} = $rv;
163 $self->{-by_name}->{$name} = $rv;