lib/IPC/Capture.pm

filter: Statementstmt 57.4% 177 / 308 Branchbran 27.7% 20 / 72 Conditioncond 21.0% 8 / 38 MC/DCmcdc 0.0% 0 / 21 Subroutinesub 67.5% 25 / 37 Podpod 100% 21 / 21 totaltotal 50.5% 251 / 497 CC 55 SCAR 23.0
CC
55
Cov
49%
can_run_qx_path_glob
30.1
probe_system_ipc_cmd
30.0
run_qx_all_separated_old
20.0
CRAP 9.9
↑ Summary
1 package IPC::Capture;
2 1 ▶use base qw( Class::Base );
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 =head1 NAME
5  
6 IPC::Capture - portably run external apps and capture the output
7  
8 =head1 SYNOPSIS
9  
10 use IPC::Capture;
11 my $ich = IPC::Capture->new();
12 $ich->set_filter('stdout_only');
13  
14 my $output = $ich->run( $this_cmd );
15 if ( $output ) ) {
16 # work with $output...
17 }
18  
19 unless( $ich->can_run( $another_cmd ) {
20 die "Will not be able to run the external command: $another_cmd\n";
21 }
22  
23 $ich->set_filter('stderr_only');
24 my $errors = $ich->run( $another_cmd );
25  
26 # stdout and stderr together:
27 $ich->set_filter('all_output');
28 my $all = $ich->run( $another_cmd );
29  
30  
31  
32 =head1 DESCRIPTION
33  
34 IPC::Capture is a module for running external applications
35 in a portable fashion when you're primarily interested in capturing
36 the returned output.
37  
38 Essentially this is an attempt at creating a portable way of doing
39 "backticks" with io-redirection. In fact, if it looks like it will work,
40 this module will internally just try to run the command via a sub-shell
41 invoked by qx; otherwise, it will try some other approaches which may work
42 (going through other modules such as L<IPC::Cmd>, L<IPC::Run>, and/or
43 L<IPC::Open3>).
44  
45 The different ways of running external commands are called "ways" here
46 (because words like "methods" already have too many other associations).
47 At present, there are only two "ways" defined in this module: "qx" and
48 "ipc_cmd". We probe the system trying each of the known ways (in the
49 order defined in the "ways" attribute), and use the first one that looks
50 like it will work.
51  
52 =head2 METHODS
53  
54 =over
55  
56 =cut
57  
58 1 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
59 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
60 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
61 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
62 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
63 1 ▶use Hash::Util qw( lock_keys unlock_keys );
Subroutine BEGIN: called CC=1 SCAR=0.0
64 1 ▶use File::Spec qw( devnull );
Subroutine BEGIN: called CC=1 SCAR=0.0
65 1 ▶use File::Temp qw( tempfile tempdir );
Subroutine BEGIN: called CC=1 SCAR=0.0
66 # Note: IPC::Cmd is used below dynamically (if qx fails)
67 1 ▶use List::MoreUtils qw( zip );
Subroutine BEGIN: called CC=1 SCAR=0.0
68  
69 1 our $VERSION = '0.06';
70 1 my $DEBUG = 0; # TODO change to 0 before shipping
71  
72 # needed for accessor generation
73 1 our $AUTOLOAD;
74 1 my %ATTRIBUTES = ();
75  
76 =item new
77  
78 Creates a new IPC::Capture object.
79  
80 Takes a hashref as an argument, with named fields identical
81 to the names of the object attributes (which also may be set
82 later via the accessor methods). These attributes are:
83  
84 =over
85  
86 =item filter
87  
88 The "filter" is a code that specifies what command output
89 streams we're interested in capturing. Allowed values:
90  
91 =over
92  
93 =item stdout_only
94  
95 Discards stderr and returns only stdout. Like the Bourne shell
96 redirect: '2>/dev/null'
97  
98 =item stderr_only
99  
100 Discards stdout and returns only stderr. Like the Bourne shell
101 redirect: '2>&1 1>/dev/null'
102  
103 =item all_output
104  
105 Intermixes lines of stdout and stderr in chronological order.
106 Like the Bourne shell redirect: '2>&1'
107  
108 =item all_separated
109  
110 The return will be an array reference with two elements: stdout and stderr.
111 (But under some circumstances, it may not be possible to seperate
112 the two, and all output will be returned intermixed, as the first
113 item, and the second will be undef.)
114  
115 =back
116  
117 =item autochomp
118  
119 Set to a true value, causes all returned values to be
120 automatically chomped. Defaults to false.
121  
122 =item known_ways
123  
124 List of known ways of invoking external commands, in the default
125 order in which they'll be tried (as of this writing: ['ex', 'ipc_cmd'].
126  
127 =item ways
128  
129 List of ways of invoking external commands, in the order the user
130 would like to try them. Defaults to L</known_ways>.
131  
132 =item way
133  
134 The chosen "way" that will be used for invoking external commands.
135  
136 =item stdout_probe_messages
137  
138 List of messages which are sent to STDOUT by the probe sub-script.
139 An array reference.
140  
141 =item stderr_probe_messages
142  
143 List of messages which are sent to STDERR by the probe sub-script.
144 An array reference.
145  
146 =back
147  
148 Takes an optional hashref as an argument, with named fields
149 identical to the names of the object attributes.
150  
151 =cut
152  
153 # Note: "new" is inherited from Class::Base and
154 # calls the following "init" routine automatically.
155  
156 =item init
157  
158 Method that initializes object attributes and then locks them
159 down to prevent accidental creation of new ones.
160  
161 Any class that inherits from this one should have an B<init> of
162 it's own that calls this B<init>. Otherwise, it's an internally
163 used routine that is not of much interest to client coders.
164  
165 =cut
166  
167 3 ▶sub init {
Subroutine init: called CC=9 SCAR=23.1
Pod documented
168 3 my $self = shift;
169 3 my $args = shift;
170 3 unlock_keys( %{ $self } );
171  
172 3 my @attributes = qw(
173 filter
174  
175 autochomp
176  
177 known_ways
178 ways
179 way
180  
181 known_filters
182  
183 stdout_probe_messages
184 stderr_probe_messages
185  
186 success
187 );
188  
189 3 foreach my $field (@attributes) {
190 27 $ATTRIBUTES{ $field } = 1;
191 27 $self->{ $field } = $args->{ $field };
192 }
193  
194 3 $self->{ success } = 1; ### TODO stub.
195  
196 3 $self->{ known_ways } = ['qx', 'ipc_cmd'];
197 3 ▶ $self->{ ways } ||= $self->{ known_ways };
Condition33%1/3
$self->{"ways"} ||= $self->{"known_ways"}
l!l&&r!l&&!r
030
MC/DC0%0/2
$self->{"ways"} ||= $self->{"known_ways"}
$self->{"ways"} $self->{"known_ways"}
Truth table33%1/3
A ||= B
A= $self->{"ways"}B= $self->{"known_ways"}
ABresult
1X1
011
000
198  
199 $self->{ known_filters } =
200 [
201 3 'stdout_only',
202 'stderr_only',
203 'all_output',
204 'all_separated',
205 ];
206  
207 $self->{ stdout_probe_messages } ||=
208 3 ▶ [ 'abc', 'ijk', 'xyz' ];
Condition50%1/2
$self->{"stdout_probe_messages"} ||= ["abc", "ijk", "xyz"]
l!l
03
MC/DC0%0/1
$self->{"stdout_probe_messages"} ||= ["abc", "ijk", "xyz"]
$self->{"stdout_probe_messages"}
Truth table50%1/2
A
A= $self->{"stdout_probe_messages"}
Aresult
11
00
209  
210 $self->{ stderr_probe_messages } ||=
211 3 ▶ [ '123', '567', '890' ];
Condition50%1/2
$self->{"stderr_probe_messages"} ||= [123, 567, 890]
l!l
03
MC/DC0%0/1
$self->{"stderr_probe_messages"} ||= [123, 567, 890]
$self->{"stderr_probe_messages"}
Truth table50%1/2
A
A= $self->{"stderr_probe_messages"}
Aresult
11
00
212  
213 3 my $way = $self->probe_system;
214 3 ▶ unless( $way ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($way) 0 3 3
215 0 $self->debug("IPC::Capture probe_system method has not found a way.");
216 }
217 3 ▶ $self->{ way } = $way || 'qx'; # TODO should there be a fallback default here?
Condition50%1/2
$way || 'qx'
l!l
30
MC/DC0%0/1
$way || 'qx'
$way
Truth table50%1/2
A
A= $way
Aresult
11
00
218  
219 3 ▶ $self->debugging( 1 ) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 3 3
220 3 ▶ $DEBUG = 1 if $self->debugging();
Branch: 1 branch
BranchTrueFalseTotal
if $self->debugging 0 3 3
221  
222 3 lock_keys( %{ $self } );
223 3 return $self;
224 }
225 # Note: logically, known_ways and known_filters
226 # could be class data: but I don't think I care.
227  
228 =item probe_system
229  
230 Internally used during the init phase of object creation.
231 Chooses a good "way" of running commands external to perl.
232  
233 =cut
234  
235 3 ▶sub probe_system {
Subroutine probe_system: called CC=4 SCAR=13.9
Pod documented
236 3 my $self = shift;
237 3 my $ways = $self->ways;
238  
239 ## Here we use File::Temp to write out a small perl script that sends
240 ## some known output to stdout and (optionally) to stderr
241 3 my $code = $self->define_yammer_script();
242  
243 # creating a temporary perl script file
244 # Note: we explicitly use tmpdir, or else it uses curdir which may not be writable(!)
245 3 my $tmpdir = File::Spec->tmpdir();
246 3 ▶ $File::Temp::KEEP_ALL = 1 if $DEBUG; # overrides "UNLINK" & leaves tempfile
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 3 3
247 3 my ($fh1, $scriptname) = tempfile('yap_XXXX',
248 SUFFIX => '.pl',
249 DIR => $tmpdir,
250 UNLINK => 1 );
251  
252 3 $self->debug( "scriptname: $scriptname\n" );
253 3 print {$fh1} $code;
254 3 close( $fh1 );
255  
256 # trying running the script a few different ways
257 3 my $chosen_way;
258 3 foreach my $way (@{ $ways } ) {
259 3 my $method = "probe_system_$way";
260 3 my $retval = $self->$method( $scriptname );
261 3 ▶ if ( defined( $retval ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $retval) 3 0 3
262 3 $chosen_way = $way;
263 3 last;
264 }
265 }
266  
267 # cleanup
268 3 unlink( $scriptname );
269  
270 3 return $chosen_way;
271 }
272  
273  
274 =item define_yammer_script
275  
276 This is an internally used routine, broken out as a method for
277 ease of testing.
278  
279 This generates some code for the 'yammer_script' which is used
280 used by L</probe_system> to check which ways work for running
281 external commands. The 'yammer_script' sends three lines of
282 output to stdout, and if provided with command-line arguments, it
283 will echo up to three of them to stderr. The stderr output is
284 interleaved with the output sent to stdout, starting with stdout
285 (so the pattern is: OeOeOe).
286  
287 This method uses the object data L</stdout_probe_messages> to get
288 an aref of messages to send to stdout; but this can be overridden
289 by passing it an aref of alternate messages.
290  
291 So, just to make it clear: the STDOUT strings are defined when
292 this method is called, but the STDERR strings are defined only
293 when the yammer script it generates is run.
294  
295 =cut
296  
297 3 ▶sub define_yammer_script {
Subroutine define_yammer_script: called CC=2 SCAR=7.1
Pod documented
298 3 my $self = shift;
299 3 ▶ my $messages = shift || $self->stdout_probe_messages;
Condition33%1/3
shift() || $self->stdout_probe_messages
l!l&&r!l&&!r
030
MC/DC0%0/2
shift() || $self->stdout_probe_messages
shift() $self->stdout_probe_messages
Truth table33%1/3
A || B
A= shift()B= $self->stdout_probe_messages
ABresult
1X1
011
000
300 3 my ($x, $y, $z) = @{ $messages };
301 3 my $code =
302 '$|=1;' . "\n" .
303 'print "' . $x . '\n"; ' . "\n" .
304 'print STDERR "$ARGV[0]\n" if defined($ARGV[0]); ' . "\n" .
305 'print "' . $y . '\n"; ' . "\n" .
306 'print STDERR "$ARGV[1]\n" if defined($ARGV[1]); ' . "\n" .
307 'print "' . $z . '\n"; ' . "\n" .
308 'print STDERR "$ARGV[2]\n" if defined($ARGV[2]); ' . "\n" ;
309 3 return $code;
310 }
311  
312  
313 =item probe_system_qx
314  
315 Method used internally by the internal method "probe_system".
316 Takes one argument: the script name, which it will try to run
317 via qx.
318  
319 =cut
320  
321 3 ▶sub probe_system_qx {
Subroutine probe_system_qx: called CC=5 SCAR=16.6
Pod documented
322 3 my $self = shift;
323 3 my $scriptname = shift;
324 3 ▶ my $stderr_probe_messages = shift || $self->stderr_probe_messages;
Condition33%1/3
shift() || $self->stderr_probe_messages
l!l&&r!l&&!r
030
MC/DC0%0/2
shift() || $self->stderr_probe_messages
shift() $self->stderr_probe_messages
Truth table33%1/3
A || B
A= shift()B= $self->stderr_probe_messages
ABresult
1X1
011
000
325  
326 3 my $perl = $^X; # have perl tell us where it is (might not be in path)
327 3 my $stderr_args = join ' ', @{ $stderr_probe_messages };
328 3 my $cmd = "$perl $scriptname $stderr_args";
329  
330 3 my $stdout_probe_messages = $self->stdout_probe_messages;
331  
332 3 my ($capture_stdout, $capture_stderr, $capture_all);
333 3 $capture_stdout = $self->run_qx_stdout_only( $cmd );
334 3 chomp($capture_stdout);
335 3 $capture_stderr = $self->run_qx_stderr_only( $cmd );
336 3 chomp($capture_stderr);
337 3 $capture_all = $self->run_qx_all_output( $cmd );
338 3 chomp($capture_all);
339  
340 3 my $expected_stdout = join "\n", @{ $stdout_probe_messages };
341 3 my $expected_stderr = join "\n", @{ $stderr_probe_messages };
342 3 my $expected_all = join "\n", zip @{ $stdout_probe_messages }, @{ $stderr_probe_messages };
343  
344 3 ▶ if ( ( $capture_stdout eq $expected_stdout ) &&
Branch: 1 branch
BranchTrueFalseTotal
if ($capture_stdout eq $expected_stdout and $capture_stderr eq $expected_stderr and $capture_all eq $expected_all) { } 3 0 3
Condition33%2/6
$capture_stdout eq $expected_stdout and $capture_stderr eq $expected_stderr and $capture_all eq $expected_all
!ll&&!rl&&r
003
$capture_stdout eq $expected_stdout and $capture_stderr eq $expected_stderr
!ll&&!rl&&r
003
MC/DC0%0/3
$capture_stdout eq $expected_stdout and $capture_stderr eq $expected_stderr and $capture_all eq $expected_all
$capture_stdout eq $expected_stdout $capture_stderr eq $expected_stderr $capture_all eq $expected_all
Truth table25%1/4
A and B and C
A= $capture_stdout eq $expected_stdoutB= $capture_stderr eq $expected_stderrC= $capture_all eq $expected_all
ABCresult
0XX0
10X0
1100
1111
345 ( $capture_stderr eq $expected_stderr ) &&
346 ( $capture_all eq $expected_all ) ) {
347 3 return 1;
348 } else {
349 0 return;
350 }
351 }
352  
353  
354 =item probe_system_ipc_cmd
355  
356 Method used internally by the internal method "probe_system".
357 Takes one argument: the script name, which it will try to run
358 via IPC::Cmd.
359  
360 =cut
361  
362 0 ▶sub probe_system_ipc_cmd {
Subroutine probe_system_ipc_cmd: not called CC=5 SCAR=34.0
Pod documented
363 0 my $self = shift;
364 0 my $scriptname = shift;
365 0 ▶ my $stderr_probe_messages = shift || [ '123', '567', '890' ];
Condition0%0/2
shift() || ['123', '567', '890']
l!l
00
MC/DC0%0/1
shift() || ['123', '567', '890']
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
366  
367 0 my $perl = $^X; # have perl tell us where it is (might not be in path)
368 0 my $stderr_args = join ' ', @{ $stderr_probe_messages };
369 0 my $cmd = "$perl $scriptname $stderr_args";
370  
371 0 my $stdout_probe_messages = $self->stdout_probe_messages;
372  
373 0 my ($capture_stdout, $capture_stderr, $capture_all);
374 0 $capture_stdout = $self->run_ipc_cmd_stdout_only( $cmd );
375 0 chomp($capture_stdout);
376 0 $capture_stderr = $self->run_ipc_cmd_stderr_only( $cmd );
377 0 chomp($capture_stderr);
378 0 $capture_all = $self->run_ipc_cmd_all_output( $cmd );
379 0 chomp($capture_all);
380  
381 0 my $expected_stdout = join "\n", @{ $stdout_probe_messages };
382 0 my $expected_stderr = join "\n", @{ $stderr_probe_messages };
383 0 my $expected_all = join "\n", zip @{ $stdout_probe_messages }, @{ $stderr_probe_messages };
384  
385 0 ▶ if ( ( $capture_stdout eq $expected_stdout ) &&
Branch: 1 branch
BranchTrueFalseTotal
if ($capture_stdout eq $expected_stdout and $capture_stderr eq $expected_stderr and $capture_all eq $expected_all) { } 0 0 0
Condition0%0/6
$capture_stdout eq $expected_stdout and $capture_stderr eq $expected_stderr and $capture_all eq $expected_all
!ll&&!rl&&r
000
$capture_stdout eq $expected_stdout and $capture_stderr eq $expected_stderr
!ll&&!rl&&r
000
MC/DC0%0/3
$capture_stdout eq $expected_stdout and $capture_stderr eq $expected_stderr and $capture_all eq $expected_all
$capture_stdout eq $expected_stdout $capture_stderr eq $expected_stderr $capture_all eq $expected_all
Truth table0%0/4
A and B and C
A= $capture_stdout eq $expected_stdoutB= $capture_stderr eq $expected_stderrC= $capture_all eq $expected_all
ABCresult
0XX0
10X0
1100
1111
386 ( $capture_stderr eq $expected_stderr ) &&
387 ( $capture_all eq $expected_all ) ) {
388 0 return 1;
389 } else {
390 0 return;
391 }
392 }
393  
394 =item can_run
395  
396 Given the name of an external command, will check to see if we
397 can run it.
398  
399 Note: just because the program has the name you're looking for,
400 there's no guarantee that it's the right program.
401  
402 =cut
403  
404 0 ▶sub can_run {
Subroutine can_run: not called CC=1 SCAR=6.9
Pod documented
405 0 my $self = shift;
406 0 my $cmd = shift;
407 0 my $way = $self->way;
408 0 my $method = "can_run_$way";
409 0 my $status = $self->$method( $cmd );
410 0 return $status;
411 }
412  
413 =item can_run_qx
414  
415 This is a method used internally by L</can_run>, it tries to
416 determine if the given program can be run via the shell
417 (i.e. the "qx" way), and returns the full path to the program
418 if it's found, otherwise, undef.
419  
420 =cut
421  
422 # Trying a few different ways, only one of which need work...
423 0 ▶sub can_run_qx {
Subroutine can_run_qx: not called CC=3 SCAR=24.8
Pod documented
424 0 my $self = shift;
425 0 my $program = shift;
426 0 my $found;
427  
428 0 ▶ if( $found = $self->can_run_qx_which( $program ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($found = $self->can_run_qx_which($program)) { } 0 0 0
elsif ($found = $self->can_run_qx_path_glob($program)) { } 0 0 0
429 0 return $found;
430 } elsif( $found = $self->can_run_qx_path_glob( $program ) ) {
431 0 return $found;
432 }
433  
434 0 return; # undef, nothing found
435 }
436  
437  
438 =item can_run_qx_which
439  
440 This is a method used internally by L</can_run_qx>.
441 It uses the old old unix utility "which" to look for
442 the given program.
443  
444 =cut
445  
446 0 ▶sub can_run_qx_which {
Subroutine can_run_qx_which: not called CC=4 SCAR=26.8
Pod documented
447 0 my $self = shift;
448 0 my $program = shift;
449 0 my $subname = ( caller(0) )[3];
450  
451 0 my $which = 'which';
452 0 my $found;
453 0 eval {
454 1 ▶ no warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
455 0 $found = qx{ $which $program };
456 0 chomp( $found );
457 };
458 0 ▶ if ($@) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 0 0 0
elsif (defined $found and $found =~ / \b $program $ /msx) { } 0 0 0
459 0 $self->debug("$subname: Running '$which' errored out: $@\n");
460 0 return;
461 ▶ } elsif ( defined( $found ) && ($found =~ m{ \b $program $ }xms) ) {
Condition0%0/3
defined $found and $found =~ / \b $program $ /msx
!ll&&!rl&&r
000
MC/DC0%0/2
defined $found and $found =~ / \b $program $ /msx
defined $found $found =~ / \b $program $ /msx
Truth table0%0/3
A and B
A= defined $foundB= $found =~ / \b $program $ /msx
ABresult
0X0
100
111
462 0 return $found;
463 } else {
464 0 return;
465 }
466 }
467  
468  
469 =item can_run_qx_path_glob
470  
471 This is a method used internally by L</can_run_qx>.
472 It looks for the given program by checking looking for
473 an executible file of that name somewhere in the path.
474  
475 =cut
476  
477 0 ▶sub can_run_qx_path_glob {
Subroutine can_run_qx_path_glob: not called CC=6 SCAR=34.1
Pod documented
478 0 my $self = shift;
479 0 my $program = shift;
480 0 my $found;
481 # Just look in each directory in the PATH for an
482 # executable file with the right name,
483 0 my @PATH = File::Spec->path();
484 0 foreach my $loc (@PATH) {
485 0 chdir( $loc );
486 # This is better for debugging (for obscure reasons):
487 # my @names = glob '*';
488 # foreach my $name (@names) {
489 # But this is more memory efficient...
490 0 ▶ while ( my $name = glob '*' ) {
Subroutine BEGIN: called CC=1 SCAR=1.2
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $name = glob("*"))) 0 0 0
491 0 ▶ if (( $name eq $program ) && ( -f "$loc/$name" ) && ( -x "$loc/$name" )) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq $program and -f "$loc/$name" and -x "$loc/$name") 0 0 0
Condition0%0/6
$name eq $program and -f "$loc/$name" and -x "$loc/$name"
!ll&&!rl&&r
000
$name eq $program and -f "$loc/$name"
!ll&&!rl&&r
000
MC/DC0%0/3
$name eq $program and -f "$loc/$name" and -x "$loc/$name"
$name eq $program -f "$loc/$name" -x "$loc/$name"
Truth table0%0/4
A and B and C
A= $name eq $programB= -f "$loc/$name"C= -x "$loc/$name"
ABCresult
0XX0
10X0
1100
1111
492 0 $found = File::Spec->catfile($loc, $name);
493 0 return $found;
494 }
495 }
496 }
497 0 return;
498 }
499  
500 =item can_run_ipc_cmd
501  
502 Given the name of a program, checks to see if it can run it.
503 Returns the full path to the binary if it is found.
504  
505 Note: this is a simple wrapper around IPC::Cmd::can_run.
506  
507 =cut
508  
509 0 ▶sub can_run_ipc_cmd {
Subroutine can_run_ipc_cmd: not called CC=1 SCAR=6.9
Pod documented
510 0 my $self = shift;
511 0 my $program = shift;
512 0 require IPC::Cmd;
513 0 my $path = IPC::Cmd::can_run( $program );
514 0 return $path;
515 }
516  
517 =item run
518  
519 Takes one argument: an external command string.
520  
521 Returns the output from the external command (as controlled by
522 the L</filter> setting in the object). The output
523 will almost always be in the form of a multi-line string,
524 except in one case:
525  
526 If filter is set to "all_separated", then this will return a
527 reference to an array of two elements, the first containing
528 stdout, the second stderr.
529  
530 =cut
531  
532 8 ▶sub run {
Subroutine run: called CC=1 SCAR=0.0
Pod documented
533 8 my $self = shift;
534 8 my $cmd = shift;
535 8 my $output;
536 8 my $way = $self->way;
537 8 my $od = $self->filter;
538 8 my $method = 'run_' . $way. '_' . $od ; # run_<way>_<od>
539 8 $output = $self->$method( $cmd );
540 8 return $output;
541 }
542  
543 =back
544  
545 =head2 "run_<way>_<od>"
546  
547 These methods are for internal use by the "run" method.
548  
549 =head2 "run_qx_*" methods
550  
551 These are methods that take the given command and simply try to
552 run them via whatever shell is available to the qx{} operator.
553  
554 The L</filter> setting is converted to equivalent
555 Bourne shell redirect.
556  
557 =over
558  
559 =item run_qx_all_output
560  
561 =cut
562  
563 5 ▶sub run_qx_all_output {
Subroutine run_qx_all_output: called CC=2 SCAR=7.0
Pod documented
564 5 my $self = shift;
565 5 my $cmd = shift;
566 5 my $output;
567 5 my $sod = '2>&1';
568 5 $output = qx{$cmd $sod};
569 5 ▶ chomp( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 5 5
570 5 return $output;
571 }
572  
573 =item run_qx_stdout_only
574  
575 =cut
576  
577 5 ▶sub run_qx_stdout_only {
Subroutine run_qx_stdout_only: called CC=2 SCAR=7.0
Pod documented
578 5 my $self = shift;
579 5 my $cmd = shift;
580 5 my $output;
581 5 my $devnull = File::Spec->devnull;
582 5 my $sod = "2>$devnull";
583 5 $output = qx{$cmd $sod};
584 5 ▶ chomp( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 5 5
585 5 return $output;
586 }
587  
588 =item run_qx_stderr_only
589  
590 =cut
591  
592 5 ▶sub run_qx_stderr_only {
Subroutine run_qx_stderr_only: called CC=2 SCAR=7.0
Pod documented
593 5 my $self = shift;
594 5 my $cmd = shift;
595 5 my $output;
596 5 my $devnull = File::Spec->devnull;
597 5 my $sod = "2>&1 1>$devnull";
598 5 $output = qx{$cmd $sod};
599 5 ▶ chomp( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 5 5
600 5 return $output;
601 }
602  
603 =item run_qx_all_separated_old
604  
605 (An earlier attempt that seemed "more correct"
606 to me, but doesn't work on MSwin32.)
607  
608 =cut
609  
610 # uses redirection to a temp file to get stderr isolated from stdout
611 0 ▶sub run_qx_all_separated_old {
Subroutine run_qx_all_separated_old: not called CC=4 SCAR=30.0
Pod documented
612 0 my $self = shift;
613 0 my $cmd = shift;
614 0 my ($output, $stdout, $stderr);
615 0 my $tmpdir = File::Spec->tmpdir();
616  
617 0 ▶ $File::Temp::KEEP_ALL = 1 if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 0 0
618  
619 0 my ($fh, $filename) = tempfile('buf_XXXX',
620 SUFFIX => '.dat',
621 DIR => $tmpdir,
622 UNLINK => 1);
623  
624  
625 0 my $sod = "2>$filename";
626 0 $stdout = qx{$cmd $sod};
627  
628 0 ▶ while( my $line = <$fh> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 0 0 0
629 0 $stderr .= $line;
630 }
631  
632 0 $output = [ $stdout, $stderr ];
633 0 ▶ $self->chomp_aref( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 0 0
634 0 return $output;
635 }
636  
637  
638 =item run_qx_all_separated
639  
640  
641 =cut
642  
643 # And alternate form of L</run_qx_all_separated> to work
644 # around an mswin32 issue.
645  
646 2 ▶sub run_qx_all_separated {
Subroutine run_qx_all_separated: called CC=5 SCAR=16.2
Pod documented
647 2 my $self = shift;
648 2 my $cmd = shift;
649 2 my ($output, $stdout, $stderr);
650 2 my $tmpdir = File::Spec->tmpdir();
651  
652 # $File::Temp::KEEP_ALL = 1 if $DEBUG;
653  
654 2 my ($fh, $filename) = tempfile('buf_XXXX',
655 SUFFIX => '.dat',
656 DIR => $tmpdir,
657 UNLINK => 0);
658  
659 2 close($fh);
660  
661 2 my $sod = "2>$filename";
662 2 $stdout = qx{$cmd $sod};
663  
664 2 ▶ open $fh, '<', $filename or croak "Could not re-open $filename for read: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<", $filename or croak("Could not re-open $filename for read: $!") 2 0 2
665  
666 2 ▶ while( my $line = <$fh> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 12 2 14
667 12 $stderr .= $line;
668 }
669 2 close($fh);
670  
671 2 ▶ unlink( $filename ) unless $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
unless $DEBUG 2 0 2
672  
673 2 $output = [ $stdout, $stderr ];
674 2 ▶ $self->chomp_aref( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 2 2
675 2 return $output;
676 }
677  
678  
679  
680 =back
681  
682 =head2 "run_ipc_cmd_*" methods
683  
684 These are methods that take the given command and try to
685 run them via the L<IPC::Cmd> module, (which in turn will try
686 to use L<IPC::Run> or L<Run::Open3>).
687  
688 The L</filter> setting determines what kind of
689 IPC::Cmd call to use, and which of it's output channels will
690 be returned.
691  
692 =over
693  
694 =item run_ipc_cmd_stdout_only
695  
696 Used internally by L</run> when the L</filter> is set
697 to 'stdout_only' (and the L</way> is 'ipc_cmd').
698  
699 =cut
700  
701 0 ▶sub run_ipc_cmd_stdout_only {
Subroutine run_ipc_cmd_stdout_only: not called CC=3 SCAR=24.8
Pod documented
702 0 my $self = shift;
703 0 my $cmd = shift;
704 0 my $output;
705 my $all_buf;
706 0 require IPC::Cmd;
707 0 my( $success, $error_code, $all_sep_buf, $stdout_buf, $stderr_buf ) =
708 IPC::Cmd::run( command => $cmd, verbose => 0, buffer=> \$all_buf );
709 0 $output = $stdout_buf->[0];
710  
711 0 ▶ if( not( $success ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($success) 0 0 0
712 0 warn "IPC::Cmd run of $cmd failed.";
713 }
714 0 ▶ chomp( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 0 0
715 0 return $output;
716 }
717  
718  
719 =item run_ipc_cmd_stderr_only
720  
721 Used internally by L</run> when the L</filter> is set
722 to 'stderr_only' (and the L</way> is 'ipc_cmd'):
723  
724 =cut
725  
726 0 ▶sub run_ipc_cmd_stderr_only {
Subroutine run_ipc_cmd_stderr_only: not called CC=3 SCAR=24.8
Pod documented
727 0 my $self = shift;
728 0 my $cmd = shift;
729 0 my $output;
730 my $all_buf;
731 0 require IPC::Cmd;
732 0 my( $success, $error_code, $all_sep_buf, $stdout_buf, $stderr_buf ) =
733 IPC::Cmd::run( command => $cmd, verbose => 0, buffer=> \$all_buf );
734 0 $output = $stderr_buf->[0];
735  
736 0 ▶ if( not( $success ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($success) 0 0 0
737 0 warn "IPC::Cmd run of $cmd has failed";
738 }
739 0 ▶ chomp( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 0 0
740 0 return $output;
741 }
742  
743  
744 =item run_ipc_cmd_all_output
745  
746 Used internally by L</run> when the L</filter> is set
747 to 'all_output' (and the L</way> is 'ipc_cmd'):
748  
749 =cut
750  
751 0 ▶sub run_ipc_cmd_all_output {
Subroutine run_ipc_cmd_all_output: not called CC=3 SCAR=24.8
Pod documented
752 0 my $self = shift;
753 0 my $cmd = shift;
754 0 my $output;
755 my $all_buf;
756 0 require IPC::Cmd;
757 0 ▶ if( IPC::Cmd::run( command => $cmd, verbose => 0, buffer=> \$all_buf ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (IPC::Cmd::run('command', $cmd, 'verbose', 0, 'buffer', \$all_buf)) { } 0 0 0
758 0 $output = $all_buf;
759 } else {
760 0 warn "IPC::Cmd run of $cmd failed.";
761 }
762 0 ▶ chomp( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 0 0
763 0 return $output;
764 }
765  
766 =item run_ipc_cmd_all_separated
767  
768 Used internally by L</run> when the L</filter> is set
769 to 'all_separated' (and the L</way> is 'ipc_cmd'):
770  
771 =cut
772  
773 0 ▶sub run_ipc_cmd_all_separated {
Subroutine run_ipc_cmd_all_separated: not called CC=3 SCAR=24.8
Pod documented
774 0 my $self = shift;
775 0 my $cmd = shift;
776 0 my ($output, $stdout, $stderr);
777 0 my $all_buf;
778 0 require IPC::Cmd;
779 0 my( $success, $error_code, $all_sep_buf, $stdout_buf, $stderr_buf ) =
780 IPC::Cmd::run( command => $cmd, verbose => 0, buffer=> \$all_buf );
781 0 $output = $all_sep_buf;
782  
783 0 ▶ if( not( $success ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($success) 0 0 0
784 0 warn "IPC::Cmd run of $cmd failed.";
785 }
786  
787 0 ▶ $self->chomp_aref( $output ) if $self->autochomp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->autochomp 0 0 0
788 0 return $output;
789 }
790  
791 =back
792  
793 =head1 utility methods
794  
795 =over
796  
797 =item chomp_aref
798  
799 Like "chomp", but presumes it's been given an array reference
800 of strings to work on.
801  
802 =cut
803  
804 0 ▶sub chomp_aref {
Subroutine chomp_aref: not called CC=3 SCAR=24.8
Pod documented
805 0 my $self = shift;
806 0 my $aref = shift;
807  
808 0 ▶ unless ( ref( $aref ) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $aref eq "ARRAY") 0 0 0
809 0 croak "chomp_aref only works on an array reference";
810 }
811 0 foreach ( @{ $aref } ){
812 0 chomp( $_ );
813 }
814 0 return $aref;
815 }
816  
817  
818  
819  
820 =back
821  
822 =head2 basic setters and getters
823  
824 The naming convention in use here is that setters begin with
825 "set_", but getters have *no* prefix: the most commonly used case
826 deserves the simplest syntax (and mutators are deprecated).
827  
828 These accessors exist for all of the object attributes (documented
829 above) irrespective of whether they're expected to be externally useful.
830  
831 =head2 automatic generation of accessors
832  
833 =over
834  
835 =item AUTOLOAD
836  
837 =cut
838  
839 10 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=5 SCAR=16.2
840 10 ▶ return if $AUTOLOAD =~ /DESTROY$/; # skip calls to DESTROY ()
Branch: 1 branch
BranchTrueFalseTotal
if $IPC::Capture::AUTOLOAD =~ /DESTROY$/ 3 7 10
841  
842 7 my ($name) = $AUTOLOAD =~ /([^:]+)$/; # extract method name
843 7 (my $field = $name) =~ s/^set_//;
844  
845 # check that this is a valid accessor call
846 croak("Unknown method '$AUTOLOAD' called")
847 7 ▶ unless defined( $ATTRIBUTES{ $field } );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ATTRIBUTES{$field} 0 7 7
848  
849 1 ▶ { no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
850  
851 # create the setter and getter and install them in the symbol table
852  
853 7 ▶ if ( $name =~ /^set_/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($name =~ /^set_/) { } 1 6 7
elsif ($name =~ /^get_/) { } 0 6 6
854  
855 8 ▶ *$name = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
856 8 my $self = shift;
857 8 $self->{ $field } = shift;
858 8 return $self->{ $field };
859 1 };
860  
861 1 goto &$name; # jump to the new method.
862 } elsif ( $name =~ /^get_/ ) {
863 0 carp("Apparent attempt at using a getter with unneeded 'get_' prefix.");
864 }
865  
866 45 ▶ *$name = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
867 45 my $self = shift;
868 45 return $self->{ $field };
869 6 };
870  
871 6 goto &$name; # jump to the new method.
872 }
873 }
874  
875  
876 1 1;
877  
878 =back
879  
880 =head1 How It Works
881  
882 Where possible, IPC::Capture will simply work by running the
883 given command in a sub-shell, invoked with a qx.
884  
885 During the init phase, it tries to determine if a qx works as
886 expected (using Bourne-shell style redirects) by the expedient of
887 writing a temporary perl script that generates a known output,
888 and then just trying to run the script. (This step will be
889 skipped if the object is told which style of i/o it should use
890 when instantiated.)
891  
892 It appears that qx with i/o re-direction is a relatively portable
893 idiom these days: it's supported by most forms of perl on
894 Windows, and I would be surprised if OSX does not support it
895 also.
896  
897 If a qx fails, then this system will try another way of doing
898 the job using the L<IPC::Cmd> module.
899  
900 If no way of running a simple command and capturing it's output
901 can be found, an error will be signalled during instantiation.
902  
903 L<IPC::Cmd> in turn uses L<IPC::Run> or L<IPC::Open3> (depending
904 on which is installed), which means that this module should have
905 a fair degree of cross-platform portability.
906  
907 =head2 further notes
908  
909 Depending on the type of output requested with the "filter",
910 this module will choose to do either a scalar or an array context call
911 to IPC::Cmd::run (insulating the user from one of IPC::Cmd's
912 oddities).
913  
914 =head1 MOTIVATION
915  
916 The original goal was to find something more portable than
917 shelling out via qx with Bourne shell redirection.
918  
919 I'd just written the L<Emacs::Run> module that shells out to
920 emacs, and I was looking for improvements. (Note: emacs is
921 a widely available program, with portability roughly on the
922 same scale as perl.)
923  
924 The L<IPC::Cmd> module looked like a promising simplification
925 over directly using L<IPC::Run> or L<IPC::Open3>, but it's
926 output capture features seemed clumsy.
927  
928 So: my first thought was to write a wrapper around the wrapper,
929 and as an added bonus, it would fall back on doing a simple qx
930 if L<IPC::Cmd> wasn't going to work.
931  
932 My initial tests of that code immediately revealed a problem
933 with L<IPC::Cmd>: it usually worked as expected, but sometimes
934 would behave strangely (e.g. returning only one line of output
935 instead of the expected six; or instead of interleaving stderr
936 with stdout, it might return all stderr lines first).
937 My suspicion was that this was due to running on a perl with
938 threads enabled, but in any case, it didn't inspire confidence
939 with the idea that L<IPC::Cmd> was going to be more reliable than qx.
940  
941 At which point, it occured to me that I could rewrite the
942 module to work the other way around: just use qx, but fall
943 back on L<IPC::Cmd>. And indeed, it wasn't that difficult to
944 write probe routines to find out if qx works reliably.
945  
946 All of this work seemed a little besides the point when I realized
947 that nearly every Windows installation of perl can deal with Bourne
948 shell redirects -- but still this module may very well improve
949 portability to some of the more unusual platforms such as VMS or
950 the older Macs.
951  
952 And at the very least, if I use this module religiously, I can
953 stop worrying about mistyping '2>&1'.
954  
955  
956 =head1 TODO
957  
958 o More filters -- "output_to_file", etc.
959 Add a general purpose, user-defineable one?
960  
961 o IPC::Cmd seems to have reliability problems (possibly, with
962 multi-threaded perls?), the precise output it returns can vary
963 from run to run. Possibly: implement a voting algorithm, return
964 the output most commonly recieved.
965  
966 o Better test coverage: autochomp; probe_system*;
967  
968 o 02-can_run.t tests multiple internal routines, only one flavor of
969 which need work for the overall behavior to work. Possibly should
970 ship only with tests that verify the interface methods...
971  
972 o IPC::Capture lacks "success", as of 0.05. This means the SYNOPSIS
973 is complete nonsense for versions 0.04 and earlier. For now,
974 not mentioning "success", but think about implementing it.
975  
976 =head1 SEE ALSO
977  
978 L<IPC::Cmd>
979 L<IPC::Run>
980 L<IPC::Open3>
981  
982 Shell redirection apparently works on Windows:
983 http://www.perlmonks.org/?node_id=679842
984  
985  
986 =head1 AUTHOR
987  
988 Joseph Brenner, E<lt>doom@kzsu.stanford.eduE<gt>,
989 07 Apr 2008
990  
991 =head1 COPYRIGHT AND LICENSE
992  
993 Copyright (C) 2008 by Joseph Brenner
994  
995 This library is free software; you can redistribute it and/or modify
996 it under the same terms as Perl itself, either Perl version 5.8.2 or,
997 at your option, any later version of Perl 5 you may have available.
998  
999 =head1 BUGS AND LIMITATIONS
1000  
1001 There are possible security gotchas with using this module,
1002 because it hands strings off to the shell to execute. Any
1003 commands built-up from user input should be scrubbed carefully
1004 before being run with this module. Using taint is strongly
1005 recommended: see L<perlsec>.
1006  
1007 =cut
↑ Summary