From: Robert 'phaylon' Sedlacek Date: Fri, 27 Jul 2012 20:02:38 +0000 (+0000) Subject: host file reading X-Git-Tag: v0.001_001~19 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=9eb914a2b3ac8c9cf8806897ba5506e127124602;p=scpubgit%2FSystem-Introspector.git host file reading --- diff --git a/lib/System/Introspector/Config.pm b/lib/System/Introspector/Config.pm index 98697ab..ff71115 100644 --- a/lib/System/Introspector/Config.pm +++ b/lib/System/Introspector/Config.pm @@ -1,6 +1,7 @@ package System::Introspector::Config; use Moo; use Config::General; +use File::Basename; has config => (is => 'lazy'); @@ -15,14 +16,32 @@ sub _build_config { sub sudo_user { $_[0]->config->{sudo_user} } -sub groups { keys %{ $_[0]->config->{group} || {} } } +sub groups { sort keys %{ $_[0]->config->{group} || {} } } sub has_group { exists $_[0]->config->{group}{ $_[1] } } +my $_load_host_file = sub { + my ($self, $path) = @_; + my $full_path = join '/', dirname($self->config_file), $path; + open my $fh, '<:utf8', $full_path + or die "Unable to read host_file '$full_path': $!\n"; + my @hosts = <$fh>; + chomp @hosts; + return grep { m{\S} and not m{^\s*#} } @hosts; +}; + sub hosts { my ($self) = @_; my $host_spec = $self->config->{host}; - return ref($host_spec) ? @$host_spec : $host_spec; + my $host_file = $self->config->{host_file}; + return( + ref($host_spec) + ? @$host_spec + : defined($host_spec) ? $host_spec : (), + defined($host_file) + ? $self->$_load_host_file($host_file) + : (), + ); } sub user { $_[0]->config->{user} } diff --git a/t/config.t b/t/config.t new file mode 100644 index 0000000..d88a1b5 --- /dev/null +++ b/t/config.t @@ -0,0 +1,31 @@ +use strictures 1; +use Test::More; +use FindBin; + +use System::Introspector::Config; + +my $config = System::Introspector::Config->new( + config_file => "$FindBin::Bin/data/test.conf", +); + +is $config->sudo_user, 'root', 'sudo user'; +is_deeply [$config->groups], [qw( stable unstable )], 'groups'; +ok $config->has_group('stable'), 'has group'; +ok !$config->has_group('none'), 'does not have group'; +is_deeply [$config->hosts], [qw( foo bar baz qux quux quuux )], 'hosts'; +is $config->user, 'introspect', 'user'; + +is_deeply $config->config_for_group('stable'), { + introspect => { + Foo => {}, + Bar => { sudo => 1 }, + }, +}, 'multiple elements with one sudo'; + +is_deeply $config->config_for_group('unstable'), { + introspect => { + Qux => { sudo => 1 }, + }, +}, 'single element with group-wide sudo'; + +done_testing; diff --git a/t/data/from-hosts.txt b/t/data/from-hosts.txt new file mode 100644 index 0000000..16bd88e --- /dev/null +++ b/t/data/from-hosts.txt @@ -0,0 +1,6 @@ +baz +qux +quux + +# comment +quuux diff --git a/t/data/test.conf b/t/data/test.conf new file mode 100644 index 0000000..9d8fc80 --- /dev/null +++ b/t/data/test.conf @@ -0,0 +1,20 @@ +host foo +host bar + +host_file from-hosts.txt + +user introspect +sudo_user root + + + + + sudo 1 + + + + + sudo 1 + + +