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} ||= {};
27 my ($self, $recipient) = @_;
28 my $addr = lc($recipient);
29 my $inbox = $self->{-by_addr}->{$addr};
30 return $inbox if $inbox;
34 foreach my $k (keys %$self) {
35 $k =~ /\A(publicinbox\.[\w-]+)\.address\z/ or next;
37 if (ref($v) eq "ARRAY") {
38 foreach my $alias (@$v) {
39 (lc($alias) eq $addr) or next;
44 (lc($v) eq $addr) or next;
49 defined $pfx or return;
53 sub lookup_name ($$) {
54 my ($self, $name) = @_;
55 $self->{-by_name}->{$name} || _fill($self, "publicinbox.$name");
61 foreach my $k (keys %$self) {
62 $k =~ /\Apublicinbox\.([A-Z0-9a-z-]+)\.mainrepo\z/ or next;
65 my $ibx = lookup_name($self, $1) or next;
70 sub lookup_newsgroup {
73 my $rv = $self->{-by_newsgroup}->{$ng};
76 foreach my $k (keys %$self) {
77 $k =~ /\A(publicinbox\.[\w-]+)\.newsgroup\z/ or next;
81 $rv = _fill($self, $pfx);
89 my ($self, $inbox, $key) = @_;
91 $self->{"publicinbox.$inbox.$key"};
94 sub config_dir { $ENV{PI_DIR} || "$ENV{HOME}/.public-inbox" }
97 my $f = $ENV{PI_CONFIG};
98 return $f if defined $f;
99 config_dir() . '/config';
102 sub git_config_dump {
105 my @cmd = (qw/git config/, "--file=$file", '-l');
106 my $cmd = join(' ', @cmd);
107 my $fh = popen_rd(\@cmd) or die "popen_rd failed for $file: $!\n";
110 foreach my $line (<$fh>) {
112 my ($k, $v) = split(/=/, $line, 2);
116 if (ref($cur) eq "ARRAY") {
119 $rv{$k} = [ $cur, $v ];
125 close $fh or die "failed to close ($cmd) pipe: $?";
130 my ($self, $pfx) = @_;
133 foreach my $k (qw(mainrepo address filter url newsgroup
134 watch watchheader)) {
135 my $v = $self->{"$pfx.$k"};
136 $rv->{$k} = $v if defined $v;
138 return unless $rv->{mainrepo};
140 $name =~ s/\Apublicinbox\.//;
142 $rv = PublicInbox::Inbox->new($rv);
143 my $v = $rv->{address};
144 if (ref($v) eq 'ARRAY') {
145 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
147 $self->{-by_addr}->{lc($v)} = $rv;
149 if (my $ng = $rv->{newsgroup}) {
150 $self->{-by_newsgroup}->{$ng} = $rv;
152 $self->{-by_name}->{$name} = $rv;