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 $self->{-by_name}->{$name} = _fill($self, "publicinbox.$name");
63 my ($self, $inbox, $key) = @_;
65 $self->{"publicinbox.$inbox.$key"};
68 sub config_dir { $ENV{PI_DIR} || expand_filename('~/.public-inbox') }
71 my $f = $ENV{PI_CONFIG};
72 return $f if defined $f;
73 config_dir() . '/config';
79 my @cmd = (qw/git config/, "--file=$file", '-l');
80 my $cmd = join(' ', @cmd);
81 my $fh = popen_rd(\@cmd);
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: $?";
106 if (open(my $fh, '<', $path)) {
114 my ($self, $pfx) = @_;
117 foreach my $k (qw(mainrepo address filter url)) {
118 my $v = $self->{"$pfx.$k"};
119 $rv->{$k} = $v if defined $v;
122 $inbox =~ s/\Apublicinbox\.//;
123 $rv->{name} = $inbox;
124 my $v = $rv->{address} ||= 'public-inbox@example.com';
125 $rv->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
126 $rv = PublicInbox::Inbox->new($rv);
127 if (ref($v) eq 'ARRAY') {
128 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
130 $self->{-by_addr}->{lc($v)} = $rv;