host file reading
[scpubgit/System-Introspector.git] / lib / System / Introspector / Config.pm
CommitLineData
60e1cc39 1package System::Introspector::Config;
2use Moo;
3use Config::General;
9eb914a2 4use File::Basename;
60e1cc39 5
6has config => (is => 'lazy');
7
8has config_file => (is => 'ro', required => 1);
9
10sub _build_config {
11 my ($self) = @_;
12 my $reader = Config::General->new($self->config_file);
13 my %config = $reader->getall;
14 return \%config;
15}
16
a5e1e1c6 17sub sudo_user { $_[0]->config->{sudo_user} }
18
9eb914a2 19sub groups { sort keys %{ $_[0]->config->{group} || {} } }
60e1cc39 20
21sub has_group { exists $_[0]->config->{group}{ $_[1] } }
22
9eb914a2 23my $_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
b079a95d 33sub hosts {
34 my ($self) = @_;
35 my $host_spec = $self->config->{host};
9eb914a2 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 );
b079a95d 45}
46
47sub user { $_[0]->config->{user} }
48
a5e1e1c6 49my $_get_inherited = sub {
50 my $data = shift;
51 $data ||= {};
52 return
53 map { ($_ => $data->{$_}) }
54 grep { exists $data->{$_} }
55 qw( sudo );
56};
57
58sub 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}
60e1cc39 76
771;