map groups by name instead of gid
[scpubgit/System-Introspector.git] / lib / System / Introspector / Groups.pm
index 8b93e32..db6e358 100644 (file)
@@ -1,30 +1,35 @@
 package System::Introspector::Groups;
 use Moo;
 
+use System::Introspector::Util qw(
+    handle_from_file
+    transform_exceptions
+);
+
 sub gather {
     my ($self) = @_;
-    my %group;
-    my $fh = $self->_open_group_file;
-    while (defined( my $line = <$fh> )) {
-        chomp $line;
-        my ($name, undef, $gid, $users) = split m{:}, $line;
-        $users = length($users)
-            ? [split m{,}, $users]
-            : [];
-        $group{ $gid } = {
-            name    => $name,
-            gid     => $gid,
-            users   => $users,
-        };
-    }
-    return \%group;
+    return transform_exceptions {
+        my %group;
+        my $fh = $self->_open_group_file;
+        while (defined( my $line = <$fh> )) {
+            chomp $line;
+            my ($name, undef, $gid, $users) = split m{:}, $line;
+            $users = length($users)
+                ? [split m{,}, $users]
+                : [];
+            $group{ $name } = {
+                name    => $name,
+                gid     => $gid,
+                users   => $users,
+            };
+        }
+        return { groups => \%group };
+    };
 }
 
 sub _open_group_file {
     my ($self) = @_;
-    open my $fh, '<', '/etc/group'
-        or die "Unable to read group file /etc/group: $!\n";
-    return $fh;
+    return handle_from_file '/etc/group';
 }
 
 1;