more I/O utils
[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     files_from_dir
11     output_from_command
12     output_from_file
13     transform_exceptions
14 );
15
16 sub 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
29 sub transform_exceptions (&) {
30     my ($code) = @_;
31     local $@;
32     my $result = eval { $code->() };
33     return { error => "$@" }
34         if $@;
35     return $result;
36 }
37
38 sub 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
53 sub 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
60 sub handle_from_file {
61     my ($file) = @_;
62     open my $fh, '<', $file
63         or die "Unable to read $file: $!\n";
64     return $fh;
65 }
66
67 sub 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
75 1;