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 |
10 | files_from_dir |
11 | output_from_command |
12 | output_from_file |
f79a227c |
13 | transform_exceptions |
14 | ); |
15 | |
db5ba31f |
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 | |
f79a227c |
29 | sub transform_exceptions (&) { |
30 | my ($code) = @_; |
31 | local $@; |
32 | my $result = eval { $code->() }; |
33 | return { error => "$@" } |
34 | if $@; |
35 | return $result; |
36 | } |
37 | |
db5ba31f |
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 | |
f79a227c |
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 | |
db5ba31f |
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 | |
f79a227c |
75 | 1; |