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} ||= {};
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;
58 $self->{-by_name}->{$name} = $rv;
62 my ($self, $inbox, $key) = @_;
64 $self->{"publicinbox.$inbox.$key"};
67 sub config_dir { $ENV{PI_DIR} || expand_filename('~/.public-inbox') }
70 my $f = $ENV{PI_CONFIG};
71 return $f if defined $f;
72 config_dir() . '/config';
78 my @cmd = (qw/git config/, "--file=$file", '-l');
79 my $cmd = join(' ', @cmd);
80 my $fh = popen_rd(\@cmd);
83 foreach my $line (<$fh>) {
85 my ($k, $v) = split(/=/, $line, 2);
89 if (ref($cur) eq "ARRAY") {
92 $rv{$k} = [ $cur, $v ];
98 close $fh or die "failed to close ($cmd) pipe: $?";
103 my ($self, $pfx) = @_;
106 foreach my $k (qw(mainrepo address filter url)) {
107 my $v = $self->{"$pfx.$k"};
108 $rv->{$k} = $v if defined $v;
110 return unless $rv->{mainrepo};
112 $inbox =~ s/\Apublicinbox\.//;
113 $rv->{name} = $inbox;
114 my $v = $rv->{address} ||= 'public-inbox@example.com';
115 $rv->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
116 $rv = PublicInbox::Inbox->new($rv);
117 if (ref($v) eq 'ARRAY') {
118 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
120 $self->{-by_addr}->{lc($v)} = $rv;