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;
9 our @EXPORT_OK = qw/try_cat/;
10 require PublicInbox::Inbox;
11 use File::Path::Expand qw/expand_filename/;
13 # returns key-value pairs of config directives in a hash
14 # if keys may be multi-value, the value is an array ref containing all values
16 my ($class, $file) = @_;
17 $file = default_file() unless defined($file);
18 $file = ref $file ? $file : git_config_dump($file);
19 my $self = bless $file, $class;
22 $self->{-by_addr} ||= {};
23 $self->{-by_name} ||= {};
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 $self->{-by_name}->{$name} = _fill($self, "publicinbox.$name");
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 $pid = open(my $fh, '-|', @cmd);
81 defined $pid or die "$cmd failed: $!";
84 foreach my $line (<$fh>) {
86 my ($k, $v) = split(/=/, $line, 2);
90 if (ref($cur) eq "ARRAY") {
93 $rv{$k} = [ $cur, $v ];
99 close $fh or die "failed to close ($cmd) pipe: $!";
100 $? and warn "$$ $cmd exited with: ($pid) $?";
107 if (open(my $fh, '<', $path)) {
115 my ($self, $pfx) = @_;
118 foreach my $k (qw(mainrepo address filter url)) {
119 my $v = $self->{"$pfx.$k"};
120 $rv->{$k} = $v if defined $v;
123 $inbox =~ s/\Apublicinbox\.//;
124 $rv->{name} = $inbox;
125 my $v = $rv->{address} ||= 'public-inbox@example.com';
126 $rv->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
127 $rv = PublicInbox::Inbox->new($rv);
128 if (ref($v) eq 'ARRAY') {
129 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
131 $self->{-by_addr}->{lc($v)} = $rv;