3 package System::Introspector::Util;
5 use IPC::Run qw( run );
8 use Scalar::Util qw( blessed );
9 use Capture::Tiny qw( capture_stderr );
23 package System::Introspector::_Exception;
25 has message => (is => 'ro');
28 sub fail { die System::Introspector::_Exception->new(message => shift) }
29 sub is_report_exception { ref(shift) eq 'System::Introspector::_Exception' }
35 or fail "Unable to read directory $dir: $!";
37 while (defined( my $item = readdir $dh )) {
38 next if -d "$dir/$item";
44 sub transform_exceptions (&) {
46 my $result = eval { $code->() };
48 return { __error__ => $error->message }
49 if is_report_exception $error;
55 sub output_from_command {
56 my ($command, $in) = @_;
59 my ($out, $err) = ('', '');
60 my $ok = eval { run($command, \$in, \$out, \$err) or die $err};
62 return $out, $err, $ok
64 $command = join ' ', @$command
66 fail "Error running command ($command): $err"
71 sub lines_from_command {
73 my $output = output_from_command $command;
75 return split m{\n}, $output;
78 sub handle_from_command {
86 my ($err) = capture_stderr {
87 $child_pid = open2($out, File::Spec->devnull, $command);
90 waitpid $child_pid, 0;
92 my $content = join '', @lines;
94 $err = "Unknown error"
96 fail "Command error ($command): $err\n"
98 open $pipe, '<', \$content;
104 if blessed($err) and $err->isa('System::Introspector::_Exception');
105 fail "Error from command '$command': $err";
110 sub handle_from_file {
112 open my $fh, '<', $file
113 or fail "Unable to read $file: $!";
117 sub output_from_file {
119 my $fh = handle_from_file $file;
122 return do { local $/; <$fh> };