fixed exception namespace
[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 do {
18     package System::Introspector::_Exception;
19     use Moo;
20     has message => (is => 'ro');
21 };
22
23 sub fail { die System::Introspector::_Exception->new(message => shift) }
24 sub is_report_exception { ref(shift) eq 'System::Introspector::_Exception' }
25
26 sub files_from_dir {
27     my ($dir) = @_;
28     my $dh;
29     opendir $dh, $dir
30         or fail "Unable to read directory $dir: $!";
31     my @files;
32     while (defined( my $item = readdir $dh )) {
33         next if -d "$dir/$item";
34         push @files, $item;
35     }
36     return @files;
37 }
38
39 sub transform_exceptions (&) {
40     my ($code) = @_;
41     my $result = eval { $code->() };
42     if (my $error = $@) {
43         return { error => $error->message }
44             if is_report_exception $error;
45         die $@;
46     }
47     return $result;
48 }
49
50 sub output_from_command {
51     my ($command, $in) = @_;
52     $in = ''
53         unless defined $in;
54     my ($out, $err) = ('', '');
55     my $ok = run($command, \$in, \$out, \$err);
56     return $out, $err, $ok
57         if wantarray;
58     $command = join ' ', @$command
59         if ref $command;
60     fail "Error running command ($command): $err"
61         unless $ok;
62     return $out;
63 }
64
65 sub lines_from_command {
66     my ($command) = @_;
67     my $output = output_from_command $command;
68     chomp $output;
69     return split m{\n}, $output;
70 }
71
72 sub handle_from_command {
73     my ($command) = @_;
74     open my $pipe, '-|', $command
75         or fail "Unable to read from command '$command': $!";
76     return $pipe;
77 }
78
79 sub handle_from_file {
80     my ($file) = @_;
81     open my $fh, '<', $file
82         or fail "Unable to read $file: $!";
83     return $fh;
84 }
85
86 sub output_from_file {
87     my ($file) = @_;
88     my $fh = handle_from_file $file;
89     return <$fh>
90         if wantarray;
91     return do { local $/; <$fh> };
92 }
93
94 1;