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;
54 my ($self, $name) = @_;
55 my $rv = $self->{-by_name}->{$name};
57 $rv = _fill($self, "publicinbox.$name") or return;
60 sub lookup_newsgroup {
63 my $rv = $self->{-by_newsgroup}->{$ng};
66 foreach my $k (keys %$self) {
67 $k =~ /\A(publicinbox\.[\w-]+)\.newsgroup\z/ or next;
71 $rv = _fill($self, $pfx);
79 my ($self, $inbox, $key) = @_;
81 $self->{"publicinbox.$inbox.$key"};
84 sub config_dir { $ENV{PI_DIR} || "$ENV{HOME}/.public-inbox" }
87 my $f = $ENV{PI_CONFIG};
88 return $f if defined $f;
89 config_dir() . '/config';
95 my @cmd = (qw/git config/, "--file=$file", '-l');
96 my $cmd = join(' ', @cmd);
97 my $fh = popen_rd(\@cmd) or die "popen_rd failed for $file: $!\n";
100 foreach my $line (<$fh>) {
102 my ($k, $v) = split(/=/, $line, 2);
106 if (ref($cur) eq "ARRAY") {
109 $rv{$k} = [ $cur, $v ];
115 close $fh or die "failed to close ($cmd) pipe: $?";
120 my ($self, $pfx) = @_;
123 foreach my $k (qw(mainrepo address filter url newsgroup
124 watch watchheader)) {
125 my $v = $self->{"$pfx.$k"};
126 $rv->{$k} = $v if defined $v;
128 return unless $rv->{mainrepo};
130 $name =~ s/\Apublicinbox\.//;
132 $rv = PublicInbox::Inbox->new($rv);
133 my $v = $rv->{address};
134 if (ref($v) eq 'ARRAY') {
135 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
137 $self->{-by_addr}->{lc($v)} = $rv;
139 if (my $ng = $rv->{newsgroup}) {
140 $self->{-by_newsgroup}->{$ng} = $rv;
142 $self->{-by_name}->{$name} = $rv;