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 my $self = bless git_config_dump($file), $class;
19 $self->{-by_addr} = {};
20 $self->{-by_name} = {};
25 my ($self, $recipient) = @_;
26 my $addr = lc($recipient);
27 my $inbox = $self->{-by_addr}->{$addr};
28 return $inbox if $inbox;
32 foreach my $k (keys %$self) {
33 $k =~ /\A(publicinbox\.[\w-]+)\.address\z/ or next;
35 if (ref($v) eq "ARRAY") {
36 foreach my $alias (@$v) {
37 (lc($alias) eq $addr) or next;
42 (lc($v) eq $addr) or next;
47 defined $pfx or return;
52 my ($self, $name) = @_;
53 my $rv = $self->{-by_name}->{$name};
55 $self->{-by_name}->{$name} = _fill($self, "publicinbox.$name");
59 my ($self, $inbox, $key) = @_;
61 $self->{"publicinbox.$inbox.$key"};
64 sub config_dir { $ENV{PI_DIR} || expand_filename('~/.public-inbox') }
67 my $f = $ENV{PI_CONFIG};
68 return $f if defined $f;
69 config_dir() . '/config';
75 my @cmd = (qw/git config/, "--file=$file", '-l');
76 my $cmd = join(' ', @cmd);
77 my $pid = open(my $fh, '-|', @cmd);
78 defined $pid or die "$cmd failed: $!";
80 foreach my $line (<$fh>) {
82 my ($k, $v) = split(/=/, $line, 2);
86 if (ref($cur) eq "ARRAY") {
89 $rv{$k} = [ $cur, $v ];
95 close $fh or die "failed to close ($cmd) pipe: $!";
96 $? and warn "$$ $cmd exited with: ($pid) $?";
103 if (open(my $fh, '<', $path)) {
111 my ($self, $pfx) = @_;
114 foreach my $k (qw(mainrepo address filter url)) {
115 my $v = $self->{"$pfx.$k"};
116 $rv->{$k} = $v if defined $v;
119 $inbox =~ s/\Apublicinbox\.//;
120 $rv->{name} = $inbox;
121 my $v = $rv->{address} ||= 'public-inbox@example.com';
122 $rv->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
123 $rv = PublicInbox::Inbox->new($rv);
124 if (ref($v) eq 'ARRAY') {
125 $self->{-by_addr}->{lc($_)} = $rv foreach @$v;
127 $self->{-by_addr}->{lc($v)} = $rv;