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);
10 use File::Path::Expand qw/expand_filename/;
12 # returns key-value pairs of config directives in a hash
13 # if keys may be multi-value, the value is an array ref containing all values
15 my ($class, $file) = @_;
16 $file = default_file() unless defined($file);
17 $file = ref $file ? $file : git_config_dump($file);
18 my $self = bless $file, $class;
21 $self->{-by_addr} ||= {};
22 $self->{-by_name} ||= {};
23 $self->{-by_newsgroup} ||= {};
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;
55 my ($self, $name) = @_;
56 my $rv = $self->{-by_name}->{$name};
58 $rv = _fill($self, "publicinbox.$name") or return;
61 sub lookup_newsgroup {
64 my $rv = $self->{-by_newsgroup}->{$ng};
67 foreach my $k (keys %$self) {
68 $k =~ /\A(publicinbox\.[\w-]+)\.newsgroup\z/ or next;
72 $rv = _fill($self, $pfx);
80 my ($self, $inbox, $key) = @_;
82 $self->{"publicinbox.$inbox.$key"};
85 sub config_dir { $ENV{PI_DIR} || expand_filename('~/.public-inbox') }
88 my $f = $ENV{PI_CONFIG};
89 return $f if defined $f;
90 config_dir() . '/config';
96 my @cmd = (qw/git config/, "--file=$file", '-l');
97 my $cmd = join(' ', @cmd);
98 my $fh = popen_rd(\@cmd);
101 foreach my $line (<$fh>) {
103 my ($k, $v) = split(/=/, $line, 2);
107 if (ref($cur) eq "ARRAY") {
110 $rv{$k} = [ $cur, $v ];
116 close $fh or die "failed to close ($cmd) pipe: $?";
121 my ($self, $pfx) = @_;
124 foreach my $k (qw(mainrepo address filter url newsgroup)) {
125 my $v = $self->{"$pfx.$k"};
126 $rv->{$k} = $v if defined $v;
128 return unless $rv->{mainrepo};
130 $name =~ s/\Apublicinbox\.//;
132 my $v = $rv->{address} ||= 'public-inbox@example.com';
133 my $p = $rv->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
134 $rv->{domain} = ($p =~ /\@(\S+)\z/) ? $1 : 'localhost';
135 $rv = PublicInbox::Inbox->new($rv);
136 if (ref($v) eq 'ARRAY') {
137 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
139 $self->{-by_addr}->{lc($v)} = $rv;
141 if (my $ng = $rv->{newsgroup}) {
142 $self->{-by_newsgroup}->{$ng} = $rv;
144 $self->{-by_name}->{$name} = $rv;