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