ff711159d149ce621ddd75678183c6a0e9a68245
[scpubgit/System-Introspector.git] / lib / System / Introspector / Config.pm
1 package System::Introspector::Config;
2 use Moo;
3 use Config::General;
4 use File::Basename;
5
6 has config => (is => 'lazy');
7
8 has config_file => (is => 'ro', required => 1);
9
10 sub _build_config {
11     my ($self) = @_;
12     my $reader = Config::General->new($self->config_file);
13     my %config = $reader->getall;
14     return \%config;
15 }
16
17 sub sudo_user { $_[0]->config->{sudo_user} }
18
19 sub groups { sort keys %{ $_[0]->config->{group} || {} } }
20
21 sub has_group { exists $_[0]->config->{group}{ $_[1] } }
22
23 my $_load_host_file = sub {
24     my ($self, $path) = @_;
25     my $full_path = join '/', dirname($self->config_file), $path;
26     open my $fh, '<:utf8', $full_path
27         or die "Unable to read host_file '$full_path': $!\n";
28     my @hosts = <$fh>;
29     chomp @hosts;
30     return grep { m{\S} and not m{^\s*#} } @hosts;
31 };
32
33 sub hosts {
34     my ($self) = @_;
35     my $host_spec = $self->config->{host};
36     my $host_file = $self->config->{host_file};
37     return(
38         ref($host_spec)
39             ? @$host_spec
40             : defined($host_spec) ? $host_spec : (),
41         defined($host_file)
42             ? $self->$_load_host_file($host_file)
43             : (),
44     );
45 }
46
47 sub user { $_[0]->config->{user} }
48
49 my $_get_inherited = sub {
50     my $data = shift;
51     $data ||= {};
52     return
53         map  { ($_ => $data->{$_}) }
54         grep { exists $data->{$_} }
55         qw( sudo );
56 };
57
58 sub config_for_group {
59     my ($self, $name) = @_;
60     my %common;
61     my $config = $self->config;
62     %common = (%common, $config->$_get_inherited);
63     my $group = $config->{group}{ $name };
64     %common = (%common, $group->$_get_inherited);
65     return {
66         introspect => {
67             map {
68                 ($_ => {
69                     %common,
70                     %{ $group->{introspect}{ $_ } || {} },
71                 });
72             } keys %{ $group->{introspect} || {} },
73         },
74     };
75 }
76
77 1;