Commit | Line | Data |
f79a227c |
1 | use strictures 1; |
2 | |
3 | package System::Introspector::Util; |
4 | use Exporter 'import'; |
db5ba31f |
5 | use IPC::Run qw( run ); |
f79a227c |
6 | |
7 | our @EXPORT_OK = qw( |
8 | handle_from_command |
db5ba31f |
9 | handle_from_file |
db5ba31f |
10 | output_from_command |
11 | output_from_file |
91c60940 |
12 | lines_from_command |
13 | files_from_dir |
f79a227c |
14 | transform_exceptions |
15 | ); |
16 | |
c23ab973 |
17 | do { |
18 | package System::Introspection::_Exception; |
19 | use Moo; |
20 | has message => (is => 'ro'); |
21 | }; |
22 | |
23 | sub fail { die System::Introspection::_Exception->new(message => shift) } |
24 | sub is_report_exception { ref(shift) eq 'System::Introspection::_Exception' } |
25 | |
db5ba31f |
26 | sub files_from_dir { |
27 | my ($dir) = @_; |
28 | my $dh; |
29 | opendir $dh, $dir |
c23ab973 |
30 | or fail "Unable to read directory $dir: $!"; |
db5ba31f |
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 | |
f79a227c |
39 | sub transform_exceptions (&) { |
40 | my ($code) = @_; |
f79a227c |
41 | my $result = eval { $code->() }; |
c23ab973 |
42 | if (my $error = $@) { |
43 | return { error => $error->message } |
44 | if is_report_exception $error; |
45 | die $@; |
46 | } |
f79a227c |
47 | return $result; |
48 | } |
49 | |
db5ba31f |
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; |
c23ab973 |
60 | fail "Error running command ($command): $err" |
db5ba31f |
61 | unless $ok; |
62 | return $out; |
63 | } |
64 | |
91c60940 |
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 | |
f79a227c |
72 | sub handle_from_command { |
73 | my ($command) = @_; |
74 | open my $pipe, '-|', $command |
c23ab973 |
75 | or fail "Unable to read from command '$command': $!"; |
f79a227c |
76 | return $pipe; |
77 | } |
78 | |
db5ba31f |
79 | sub handle_from_file { |
80 | my ($file) = @_; |
81 | open my $fh, '<', $file |
c23ab973 |
82 | or fail "Unable to read $file: $!"; |
db5ba31f |
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 | |
f79a227c |
94 | 1; |