Commit | Line | Data |
60e1cc39 |
1 | package System::Introspector::Config; |
2 | use Moo; |
3 | use Config::General; |
9eb914a2 |
4 | use File::Basename; |
60e1cc39 |
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 | |
a5e1e1c6 |
17 | sub sudo_user { $_[0]->config->{sudo_user} } |
18 | |
9eb914a2 |
19 | sub groups { sort keys %{ $_[0]->config->{group} || {} } } |
60e1cc39 |
20 | |
21 | sub has_group { exists $_[0]->config->{group}{ $_[1] } } |
22 | |
9eb914a2 |
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 | |
b079a95d |
33 | sub 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 | |
47 | sub user { $_[0]->config->{user} } |
48 | |
a5e1e1c6 |
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 | } |
60e1cc39 |
76 | |
77 | 1; |
f24afb0e |
78 | |
79 | =head1 NAME |
80 | |
81 | System::Introspector::Config - Configuration file access |
82 | |
83 | =head1 SEE ALSO |
84 | |
85 | =over |
86 | |
87 | =item L<System::Introspector> |
88 | |
89 | =back |
90 | |
91 | =head1 COPYRIGHT |
92 | |
93 | Copyright (c) 2012 the L<System::Introspector> |
94 | L<AUTHOR|System::Introspector/AUTHOR>, |
95 | L<CONTRIBUTORS|System::Introspector/CONTRIBUTORS> and |
96 | L<SPONSORS|System::Introspector/SPONSORS>. |
97 | |
98 | =head1 LICENSE |
99 | |
100 | This library is free software and may be distributed under the same terms |
101 | as perl itself. |
102 | |
103 | =cut |