3 package System::Introspector::Util;
5 use IPC::Run qw( run );
8 use Scalar::Util qw( blessed );
9 use Capture::Tiny qw( capture_stderr );
22 package System::Introspector::_Exception;
24 has message => (is => 'ro');
27 sub fail { die System::Introspector::_Exception->new(message => shift) }
28 sub is_report_exception { ref(shift) eq 'System::Introspector::_Exception' }
34 or fail "Unable to read directory $dir: $!";
36 while (defined( my $item = readdir $dh )) {
37 next if -d "$dir/$item";
43 sub transform_exceptions (&) {
45 my $result = eval { $code->() };
47 return { __error__ => $error->message }
48 if is_report_exception $error;
54 sub output_from_command {
55 my ($command, $in) = @_;
58 my ($out, $err) = ('', '');
59 my $ok = run($command, \$in, \$out, \$err);
60 return $out, $err, $ok
62 $command = join ' ', @$command
64 fail "Error running command ($command): $err"
69 sub lines_from_command {
71 my $output = output_from_command $command;
73 return split m{\n}, $output;
76 sub handle_from_command {
84 my ($err) = capture_stderr {
85 $child_pid = open2($out, File::Spec->devnull, $command);
88 waitpid $child_pid, 0;
90 my $content = join '', @lines;
92 $err = "Unknown error"
94 fail "Command error ($command): $err\n"
96 open $pipe, '<', \$content;
102 if blessed($err) and $err->isa('System::Introspector::_Exception');
103 fail "Error from command '$command': $err";
108 sub handle_from_file {
110 open my $fh, '<', $file
111 or fail "Unable to read $file: $!";
115 sub output_from_file {
117 my $fh = handle_from_file $file;
120 return do { local $/; <$fh> };