use reusable I/O utils and better error handling
[scpubgit/System-Introspector.git] / lib / System / Introspector / Hosts.pm
1 package System::Introspector::Hosts;
2 use Moo;
3
4 use System::Introspector::Util qw(
5     handle_from_file
6     transform_exceptions
7 );
8
9 has hosts_file => (
10     is      => 'ro',
11     default => sub { '/etc/hosts' },
12 );
13
14 sub gather {
15     my ($self) = @_;
16     return transform_exceptions {
17         my $fh = $self->_open_hosts_file;
18         my @hosts;
19         while (defined( my $line = <$fh> )) {
20             chomp $line;
21             next if $line =~ m{^\s*$}
22                  or $line =~ m{^\s*#};
23             push @hosts, [split m{\s+}, $line];
24         }
25         return { hosts => \@hosts };
26     };
27 }
28
29 sub _open_hosts_file {
30     my ($self) = @_;
31     return handle_from_file $self->hosts_file;
32 }
33
34 1;
35
36 __END__
37
38 =head1 NAME
39
40 System::Introspector::Hosts - Gather known hosts
41
42 =head1 DESCRIPTION
43
44 Reads a C<hosts> file to produce a list of known hosts
45
46 =head1 ATTRIBUTES
47
48 =head2 hosts_file
49
50 The path to the C<hosts> file that should be read. Defaults to C</etc/hosts>.
51
52 =head1 SEE ALSO
53
54 =over
55
56 =item L<System::Introspector>
57
58 =back
59
60 =cut
61