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 PublicInbox::Spawn qw(popen_rd);
12 use File::Path::Expand qw/expand_filename/;
14 # returns key-value pairs of config directives in a hash
15 # if keys may be multi-value, the value is an array ref containing all values
17 my ($class, $file) = @_;
18 $file = default_file() unless defined($file);
19 $file = ref $file ? $file : git_config_dump($file);
20 my $self = bless $file, $class;
23 $self->{-by_addr} ||= {};
24 $self->{-by_name} ||= {};
29 my ($self, $recipient) = @_;
30 my $addr = lc($recipient);
31 my $inbox = $self->{-by_addr}->{$addr};
32 return $inbox if $inbox;
36 foreach my $k (keys %$self) {
37 $k =~ /\A(publicinbox\.[\w-]+)\.address\z/ or next;
39 if (ref($v) eq "ARRAY") {
40 foreach my $alias (@$v) {
41 (lc($alias) eq $addr) or next;
46 (lc($v) eq $addr) or next;
51 defined $pfx or return;
56 my ($self, $name) = @_;
57 my $rv = $self->{-by_name}->{$name};
59 $rv = _fill($self, "publicinbox.$name") or return;
60 $self->{-by_name}->{$name} = $rv;
64 my ($self, $inbox, $key) = @_;
66 $self->{"publicinbox.$inbox.$key"};
69 sub config_dir { $ENV{PI_DIR} || expand_filename('~/.public-inbox') }
72 my $f = $ENV{PI_CONFIG};
73 return $f if defined $f;
74 config_dir() . '/config';
80 my @cmd = (qw/git config/, "--file=$file", '-l');
81 my $cmd = join(' ', @cmd);
82 my $fh = popen_rd(\@cmd);
85 foreach my $line (<$fh>) {
87 my ($k, $v) = split(/=/, $line, 2);
91 if (ref($cur) eq "ARRAY") {
94 $rv{$k} = [ $cur, $v ];
100 close $fh or die "failed to close ($cmd) pipe: $?";
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;
122 return unless $rv->{mainrepo};
124 $inbox =~ s/\Apublicinbox\.//;
125 $rv->{name} = $inbox;
126 my $v = $rv->{address} ||= 'public-inbox@example.com';
127 $rv->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
128 $rv = PublicInbox::Inbox->new($rv);
129 if (ref($v) eq 'ARRAY') {
130 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
132 $self->{-by_addr}->{lc($v)} = $rv;