user result now under 'users' key
[scpubgit/System-Introspector.git] / lib / System / Introspector / Util.pm
CommitLineData
f79a227c 1use strictures 1;
2
3package System::Introspector::Util;
4use Exporter 'import';
db5ba31f 5use IPC::Run qw( run );
f79a227c 6
7our @EXPORT_OK = qw(
8 handle_from_command
db5ba31f 9 handle_from_file
10 files_from_dir
11 output_from_command
12 output_from_file
f79a227c 13 transform_exceptions
14);
15
db5ba31f 16sub files_from_dir {
17 my ($dir) = @_;
18 my $dh;
19 opendir $dh, $dir
20 or die "Unable to read directory $dir: $!\n";
21 my @files;
22 while (defined( my $item = readdir $dh )) {
23 next if -d "$dir/$item";
24 push @files, $item;
25 }
26 return @files;
27}
28
f79a227c 29sub transform_exceptions (&) {
30 my ($code) = @_;
31 local $@;
32 my $result = eval { $code->() };
33 return { error => "$@" }
34 if $@;
35 return $result;
36}
37
db5ba31f 38sub output_from_command {
39 my ($command, $in) = @_;
40 $in = ''
41 unless defined $in;
42 my ($out, $err) = ('', '');
43 my $ok = run($command, \$in, \$out, \$err);
44 return $out, $err, $ok
45 if wantarray;
46 $command = join ' ', @$command
47 if ref $command;
48 die "Error running command ($command): $err\n"
49 unless $ok;
50 return $out;
51}
52
f79a227c 53sub handle_from_command {
54 my ($command) = @_;
55 open my $pipe, '-|', $command
56 or die "Unable to read from command '$command': $!\n";
57 return $pipe;
58}
59
db5ba31f 60sub handle_from_file {
61 my ($file) = @_;
62 open my $fh, '<', $file
63 or die "Unable to read $file: $!\n";
64 return $fh;
65}
66
67sub output_from_file {
68 my ($file) = @_;
69 my $fh = handle_from_file $file;
70 return <$fh>
71 if wantarray;
72 return do { local $/; <$fh> };
73}
74
f79a227c 751;