File Coverage

blib/lib/Backticks.pm
Criterion Covered Total %
statement 142 152 93.4
branch 61 84 72.6
condition 6 11 54.5
subroutine 36 37 97.3
pod 19 19 100.0
total 264 303 87.1


line stmt bran cond sub pod time code
1             package Backticks;
2              
3 1     1   30028 use 5.006;
  1         5  
  1         47  
4 1     1   5 use strict;
  1         2  
  1         36  
5 1     1   5 use warnings;
  1         11  
  1         29  
6              
7 1     1   966 use Filter::Simple;
  1         77340  
  1         8  
8 1     1   1593 use File::Temp qw(tempfile);
  1         16976  
  1         85  
9 1     1   10 use Carp qw(croak);
  1         2  
  1         53  
10 1     1   6 use Scalar::Util qw(blessed);
  1         2  
  1         50  
11 1     1   937 use Class::ISA;
  1         3198  
  1         28  
12 1     1   939 use IPC::Open3;
  1         3237  
  1         75  
13 1     1   10 use overload '""' => \&stdout; # Object stringifies to command's stdout
  1         2  
  1         12  
14              
15             # Always report errors from a context outside of this package
16             $Carp::Internal{ (__PACKAGE__) }++;
17              
18             =head1 NAME
19              
20             Backticks - Use `backticks` like objects!
21              
22             =cut
23              
24             our $VERSION = '1.0.9';
25              
26             =head1 SYNOPSIS
27              
28             This module turns backticks into full objects which you can
29             query in interesting ways.
30              
31             use Backticks;
32              
33             my $results = `ls -a /`; # Assign a Backticks object to $results
34              
35             print $results->stdout; # Get the command's STDOUT
36             print $results->stderr; # Get the command's STDERR
37             print $results->merged; # Get STDOUT and STDERR together
38             print $results->success; # Will be true when command exited clean
39             print $results; # Get the command's STDOUT... the object
40             # stringifies to the command's output
41             # so you can use it most places you
42             # use normal backticks
43              
44             You can have failed commands automatically die your perl script
45            
46             $Backticks::autodie = 1;
47             `perl -e 'print STDERR "OUCH!\n"; exit 1'`;
48              
49             Which dies with the following message:
50              
51             Error executing `perl -e 'warn "OUCH!\n"; exit 1'`:
52             Failed with non-zero exit code 1
53             Error output:
54             OUCH!
55            
56             You can automatically chomp output:
57              
58             $Backticks::chomped = 1;
59             my $chomped = `perl -e "print qq{Hello\n}"`;
60              
61             You can even access parameters instantly in object mode by calling methods
62             immediately after the backticks!
63            
64             say `echo foo`->stdout; # Shows 'foo'
65             say `perl -e "warn 'Hello!'"`->stderr; # Shows 'Hello!'
66             say `perl -e "exit 1"`->exitcode; # Shows '1'
67            
68             You can also use a perl object-oriented interface instead of using the
69             `backticks` to create objects, the following command is the same as the first
70             one above:
71              
72             my $results = Backticks->run("ls -la /");
73            
74             Alternately, you can create a command and run it later:
75            
76             my $command = Backticks->new("ls -la /");
77             # ... do some stuff
78             $command->run();
79            
80             Creating commands as an object affords you the opportunity to override
81             Backticks package settings, by passing them as hash-style params:
82              
83             $Backticks::chomped = 0;
84             my $chomped_out = Backticks->run(
85             'echo "Hello there!"',
86             'chomped' => 1,
87             );
88              
89             =head1 PACKAGE VARIABLES
90              
91             =head2 $Backticks::autodie
92              
93             If set to 1, then any command which does not have a true success() will cause
94             the Perl process to die. Defaults to 0.
95              
96             This setting was the original onus for this module. By setting autodie you can
97             change a script which as a bunch of unchecked system calls in backticks to
98             having the results all checked using only two lines of code.
99              
100             =head2 $Backticks::chomped
101              
102             If set to 1, then STDOUT and STDERR will remove a trailing newline from the
103             captured contents, if present. Defaults to 0.
104              
105             It's very rare when you get output from a command and you don't want its
106             output chomped, or at least it's rare when chomping will cause a problem.
107              
108             =head2 $Backticks::debug
109              
110             If set to 1, then additional debugging information will be output to STDERR.
111             Defaults to 0.
112              
113             If you are running deployment scripts in which the output of every command
114             needs to be logged, this can be a handy way of showing everything about each
115             command which was run.
116              
117             =cut
118              
119             # Default values for all object fields
120             my %field_defaults = (
121             'command' => '',
122             'error' => '',
123             'stdout' => '',
124             'stderr' => '',
125             'merged' => '',
126             'returncode' => 0,
127             'debug' => 0,
128             'autodie' => 0,
129             'chomped' => 0,
130             );
131              
132             # These object fields are settable
133             my %field_is_settable = map { $_ => 1 } qw(command debug autodie chomped);
134              
135             # These settable object fields cause the object to be reset when they're set
136             my %field_causes_reset = map { $_ => 1 } qw(command);
137              
138             # These object fields are removed when the ->reset method is called
139             my %field_does_reset = map { $_ => 1 } qw(error stdout stderr returncode);
140              
141             # These object fields default to package variables of the same name
142             my %field_has_package_var = map { $_ => 1 } qw(debug autodie chomped);
143              
144             # Implement the source filter in Filter::Simple
145             FILTER_ONLY quotelike => sub {
146             s{^`(.*?)`$}
147             {
148             my $cmd = $1;
149             $cmd =~ s|\\|\\\\|gs;
150             $cmd =~ s|"|\\"|gs;
151             "Backticks->run(\"$cmd\")";
152             }egsx;
153             },
154             all => sub {
155             # The variable $Backticks::filter_debug indicates that we
156             # should print the input source lines as the appear after processing
157             $Backticks::filter_debug
158             && warn join '', map {"Backticks: $_\n"} split /\n/, $_;
159             };
160              
161             # Determine if we're being called as a valid class or instance method
162             # Return a 1 if we're a class method, a 0 if we're an instance method,
163             # or if neither then croak complaining that it's a problem
164             sub _class_method {
165 184     184   465 my $source = $_[0];
166 184 100 33     837 if ( blessed $source ) {
    50          
167 174 50       1700 return 0 if $source->isa('Backticks');
168             }
169             elsif ( defined $source && not ref $source ) {
170             # Since we're checking through Class::ISA, this should work for
171             # subclasses of this module (if we ever have any)
172 10         665 return 1
173 10 50       65 if scalar( grep { $_ eq 'Backticks' }
174             Class::ISA::self_and_super_path($source) );
175             }
176 0         0 croak "Must be called as a class or instance method";
177             }
178              
179             # Get the instance object (if called as an instance method) or the last run's
180             # object (if called as a class method)
181             sub _self {
182 174 100   174   1268 if ( _class_method(@_) ) {
183 1 50       12 defined($Backticks::last_run)
184             || croak "No previous Backticks command was run";
185 1         7 return $Backticks::last_run;
186             }
187 173         768 return $_[0];
188             }
189              
190             # Generic accessor to get the field for the current object (if called
191             # as an instance method) or the last run's object (if called as a class
192             # method)
193             sub _get {
194              
195             # Resolve the object being operated upon (class or instance)
196 115     115   210 my $self = _self( shift @_ );
197 115         429 my $field = shift @_; # The field being operated upon for this object
198            
199 115 50       662 exists( $field_defaults{$field} ) || croak "Unrecognized field '$field'";
200              
201             # Firstly, try to get the value from the object
202 115 100       1302 return $self->{$field} if defined( $self->{$field} );
203            
204             # If not found in the object, then get the value from the package var
205 32 100       308 if ( $field_has_package_var{$field} ) {
206 1     1   689 my $pkg_var = eval { no strict 'refs'; ${ 'Backticks::' . $field } };
  1         3  
  1         1899  
  19         145  
  19         19  
  19         152  
207 19 100       116 return $pkg_var if defined( $pkg_var );
208             }
209              
210             # Otherwise return the default value for the field
211 31         283 return $field_defaults{$field};
212             }
213              
214             sub _set {
215             # Resolve the object being operated upon (class or instance)
216 6     6   19 my $self = _self( shift @_ );
217 6         26 my $field = shift @_; # The field being operated upon for this object
218            
219 6 50       24 exists( $field_defaults{$field} ) || croak "Unrecognized field '$field'";
220              
221 6 50       18 if ( scalar @_ ) {
222 6 50       22 croak "Field '$field' cannot be set."
223             unless $field_is_settable{$field};
224 6         78 $self->{$field} = shift @_;
225 6 100       45 $self->reset if $field_causes_reset{$field};
226             }
227             }
228              
229             =head1 CLASS METHODS
230              
231             =head2 Backticks->new( 'command', [ %params ] )
232              
233             Creates a new Backticks object but does not run it yet. %params may contain
234             boolean values for this instance's 'debug', 'autodie' and 'chomped' settings.
235              
236             =cut
237              
238             sub new {
239            
240 5 50   5 1 15 _class_method(@_) || croak "Must be called as a class method!";
241 5         25 my $self = bless {}, shift @_;
242            
243             # Set the command
244 5         35 $self->_set( 'command', shift @_ );
245              
246             # Set all of the fields passed into ->new
247 5         15 my %params = @_;
248 5         31 $self->_set( $_, $params{$_} ) foreach keys %params;
249            
250 5         13 return $self;
251             }
252              
253             =head2 Backticks->run( 'command', [ %params ] )
254              
255             Behaves exactly like Backticks->new(...), but after the object is created it
256             immediately runs the command before returning the object.
257              
258             =head2 `command`
259              
260             This is a source filter alias for:
261              
262             Backticks->run( 'command' )
263              
264             It will create a new Backticks object, run the command, and return the object
265             complete with results. Since Backticks objects stringify to the STDOUT of the
266             command which was run, the default behavior is very similar to Perl's normal
267             backticks.
268              
269             =head1 OBJECT METHODS
270              
271             =head2 $obj->run()
272              
273             Runs (or if the command has already been run, re-runs) the $obj's command,
274             and returns the object. Note this is the only object method that can't be
275             called in class context (Backticks->run) to have it work on the last executed
276             command as described in the "Accessing the Last Run" secion below. If you
277             need to re-run the last command, use Backticks->rerun instead.
278              
279             =cut
280              
281             sub run {
282              
283             # Get a new object if called as a class method or the
284             # referenced object if called as an instance method
285 5 100   5 1 12627 my $self = _class_method(@_) ? new(@_) : $_[0];
286              
287 5         15 $self->reset;
288              
289 5         21 $self->_debug_warn( "Executing command `" . $self->command . "`:" );
290              
291             # Run in an eval to catch any perl errors
292 5         11 eval {
293              
294 5         25 local $/ = "\n";
295            
296             # Open the command via open3, specifying IN/OUT/ERR streams
297 5   50     23 my $pid = open3( \*P_STDIN, \*P_STDOUT, \*P_STDERR, $self->command )
298             || die $!;
299            
300 4         90680 close P_STDIN; # Close the command's STDIN
301 4         192 while (1) {
302 5 100       26560 if ( not eof P_STDOUT ) {
303 3         70 $self->{'stdout'} .= my $out = ;
304 3         33 $self->{'merged'} .= $out;
305             }
306 5 100       2001672 if ( not eof P_STDERR ) {
307 4         222 $self->{'stderr'} .= my $err = ;
308 4         408 $self->{'merged'} .= $err;
309             }
310 5 100 66     2012059 last if eof(P_STDOUT) && eof(P_STDERR);
311             }
312            
313 4 50       367 waitpid( $pid, 0 ) || die $!;
314              
315 4 100       81 if ($?) { $self->{'returncode'} = $? }
  3         113  
316              
317             };
318              
319 5 100       55940 if ($@) {
    50          
    50          
    100          
320             # If $@ was set then perl had a problem running the command
321 1         31 $self->_add_error($@);
322             }
323             elsif ( $self->returncode == -1 ) {
324             # If we got a return code of -1 then we weren't able to run the
325             # command (the most common cause of this is the command didn't exist
326             # or we didn't have permissions to run it)
327 0         0 $self->_add_error("Failed to execute: $!");
328             }
329             elsif ( $self->signal ) {
330             # If we have a non-zero signal then the command went askew
331 0         0 my $err = "Died with signal " . $self->signal;
332 0 0       0 if ( $self->coredump ) { $err .= " with coredump"; }
  0         0  
333 0         0 $self->_add_error($err);
334             }
335             elsif ( $self->exitcode ) {
336             # If we have a non-zero exit code then the command went askew
337 3         18 $self->_add_error(
338             "Failed with non-zero exit code " . $self->exitcode );
339             }
340              
341             # Perform a chomp if requested
342 5 100       39 if ( $self->chomped ) {
343             # Defined checks are here so we don't auto-vivify the fields...
344             # We don't actually use chomp here because on Win32, chomp doesn't
345             # nix the carriage return.
346 1 50       30 defined( $self->{'stdout'} ) && $self->{'stdout'} =~ s/\r?\n$//;
347 1 50       11 defined( $self->{'stderr'} ) && $self->{'stderr'} =~ s/\r?\n$//;
348 1 50       15 defined( $self->{'merged'} ) && $self->{'merged'} =~ s/\r?\n$//;
349             }
350              
351             # Print debugging information
352 5         42 $self->_debug_warn( $self->as_table );
353              
354             # If we are expected to die unless we have a success, then do so...
355 5 100 66     35 if ( $self->autodie && not $self->success ) { croak $self->error_verbose }
  1         16  
356              
357             # Make it so we can get at the last command run through class methods
358 4         9 $Backticks::last_run = $self;
359              
360 4         86 return $self;
361             }
362              
363             =head2 $obj->rerun()
364              
365             Re-runs $obj's command, and returns the object.
366              
367             =cut
368              
369 0     0 1 0 sub rerun { _self(@_)->run }
370              
371             =head2 $obj->reset()
372              
373             Resets the object back to a state as if the command had never been run
374              
375             =cut
376              
377             sub reset {
378 10     10 1 56 my $self = _self(@_);
379 10         31 delete $self->{$_} foreach grep { $field_does_reset{$_} } keys %$self;
  11         48  
380             }
381              
382             =head2 $obj->as_table()
383              
384             Returns a summary text table about the command.
385              
386             =cut
387              
388             sub as_table {
389 5     5 1 13 my $self = _self(@_);
390 5         21 my $out = '';
391 5         31 _tbl( \$out, 'Command', $self->command);
392 5 100       19 $self->error && _tbl( \$out, 'Error', $self->error );
393 5 100       20 $self->stdout && _tbl( \$out, 'STDOUT', $self->stdout );
394 5 100       37 $self->stderr && _tbl( \$out, 'STDERR', $self->stderr );
395 5 100       23 $self->merged && _tbl( \$out, 'Merged', $self->merged );
396 5 100       18 if ( $self->returncode ) {
397 3         11 _tbl( \$out, 'Return Code', $self->returncode );
398 3         17 _tbl( \$out, 'Exit Code', $self->exitcode );
399 3         10 _tbl( \$out, 'Signal', $self->signal );
400 3         9 _tbl( \$out, 'Coredump', $self->coredump );
401             }
402 5         41 return $out;
403             }
404              
405             # Adds rows to the provided string ref for as_table above
406             sub _tbl {
407 30     30   43 my $out = shift; # String reference to add the row to
408 30         80 my $name = shift; # Name of the field being displayed
409 30         41 my $val = shift; # Value of the field being displayed
410            
411             # Show undefined values as the string "undef"
412 30 50       56 if ( not defined $val ) { $val = 'undef'; }
  0         0  
413            
414             # Indent multi-line values
415 30         96 $val = join( "\n" . ( ' ' x 14 ), split "\n", $val );
416            
417             # Append the row
418 30         139 $$out .= sprintf "%-11s : %s\n", $name, $val;
419             }
420              
421             =head2 $obj->command()
422              
423             Returns a string containing the command that this object is/was configured to
424             run.
425              
426             =head2 $obj->stdout(), $obj->stderr(), $obj->merged()
427              
428             Returns a string containing the contents of STDOUT or STDERR of the command
429             which was run. If chomped is true, then this value will lack the trailing
430             newline if one happened in the captured output. Merged is the combined output
431             of STDOUT and STDERR.
432              
433             =head2 $obj->returncode(), $obj->exitcode(), $obj->coredump(), $obj->signal()
434              
435             Returns an integer, indicating a $?-based value at the time the command was
436             run:
437              
438             =over 4
439              
440             =item returncode = $?
441              
442             =item exitcode = $? >> 8
443              
444             =item coredump = $? & 128
445              
446             =item signal = $? & 127
447              
448             =back
449              
450             =head2 $obj->error(), $obj->error_verbose()
451              
452             Returns a string containing a description of any errors encountered while
453             running the command. In the case of error_verbose, it will also contain the
454             command which was run and STDERR's output.
455              
456             =cut
457              
458 16     16 1 39 sub command { _get( shift(@_), 'command' ) }
459 14     14 1 171 sub error { _get( shift(@_), 'error' ) }
460 33     33 1 101 sub returncode { _get( shift(@_), 'returncode' ) }
461 11     11 1 2157 sub stdout { _get( shift(@_), 'stdout' ) }
462 11     11 1 27 sub stderr { _get( shift(@_), 'stderr' ) }
463 10     10 1 28 sub merged { _get( shift(@_), 'merged' ) }
464 3     3 1 13 sub coredump { _self(@_)->returncode & 128 }
465 11     11 1 25 sub exitcode { _self(@_)->returncode >> 8 }
466 7     7 1 20 sub signal { _self(@_)->returncode & 127 }
467              
468             sub error_verbose {
469 1     1 1 6 my $self = shift;
470 1 50       9 return '' unless $self->error;
471 1         17 my $err = "Error executing `" . $self->command . "`:\n" . $self->error;
472 1 50       8 if ( $self->stderr ne '' ) { $err .= "\nError output:\n" . $self->stderr }
  1         79  
473 1         1679 return $err;
474             }
475              
476             =head2 $obj->success()
477              
478             Returns a 1 or 0, indicating whether or not the command run had an error or
479             return code.
480              
481             =cut
482              
483             sub success {
484 3     3 1 26 my $self = _self(@_);
485 3 50       9 return ( $self->error eq '' ) ? 1 : 0;
486             }
487              
488             =head2 $obj->autodie(), $obj->chomped(), $obj->debug()
489              
490             Returns a 1 or 0, if the corresponding $Backticks::xxx variable has been
491             overridden within this object (as passed in as parameters during ->new()).
492             Otherwise it will return the value of the corresponding $Backticks::xxx field
493             as default.
494              
495             =cut
496              
497 5     5 1 11 sub autodie { _get( shift(@_), 'autodie' ) }
498 5     5 1 24 sub chomped { _get( shift(@_), 'chomped' ) }
499 10     10 1 24 sub debug { _get( shift(@_), 'debug' ) }
500              
501             # Append to this instance or the last run instance's error field
502             sub _add_error {
503 4     4   22 my $self = _self( shift @_ );
504 4 50       25 if ( $self->{'error'} ) { $self->{'error'} .= "\n"; }
  0         0  
505 4         42 $self->{'error'} .= join "\n", @_;
506 4         53 chomp $self->{'error'};
507             }
508              
509             # Print debugging output to STDERR if debugging is enabled
510             sub _debug_warn {
511 10 50   10   30 _self( shift @_ )->debug || return;
512 0           warn "$_\n" foreach split /\n/, @_;
513             }
514              
515             =head1 ACCESSING THE LAST RUN
516              
517             Any of the instance $obj->method's above can also be called as
518             Backticks->method and will apply to the last command run through the Backticks
519             module. So:
520              
521             `run a command`;
522             print Backticks->stderr; # Will show the STDERR for `run a command`!
523             print Backticks->success; # Will show success for it...
524            
525             $foo = Backticks->run('another command');
526             print Backticks->stdout; # Output for the above line
527              
528             If you want to access the last run object more explicitly, you can find it at:
529            
530             $Backticks::last_run
531            
532             =head1 NOTES
533              
534             =over 4
535              
536             =item No redirection
537              
538             Since we're not using the shell to open subprocesses (behind the scenes we're
539             using L) you can't redirect input or output. But that shouldn't be a
540             problem, since getting the redirected output is likely why you're using this
541             module in the first place. ;)
542            
543             =item STDERR is captured by default
544              
545             Since we're capturing STDERR from commands which are run, the default behavior
546             is different from Perl's normal backticks, which will print the subprocess's
547             STDERR output to the perl process's STDERR. In other words, command error
548             streams normally trickle up into Perl's error stream, but won't under this
549             module. You can always just print it yourself:
550              
551             warn `command`->stderr;
552              
553             =item Source filtering
554              
555             The overriding of `backticks` is provided by Filter::Simple. Source filtering
556             can be weird sometimes... if you want to use this module in a purely
557             traditional Perl OO style, simply turn off the source filtering as soon as you
558             load the module:
559              
560             use Backticks;
561             no Backticks;
562              
563             This way the class is loaded, but `backticks` are Perl-native. You can still
564             use Backticks->run() or Backticks->new() to create objects even after the
565             "no Backticks" statement.
566              
567             =item Using Perl's backticks with Backticks
568              
569             If you want to use Perl's normal backticks functionality in conjunction with
570             this module's `backticks`, simply use qx{...} instead:
571              
572             use Backticks;
573             `command`; # Uses the Backticks module, returns an object
574             qx{command}; # Bypasses Backticks module, returns a string
575              
576             =item Module variable scope
577              
578             The module's variables are shared everywhere it's used within a perl runtime.
579             If you want to make sure that the setting of a Backticks variable is limited to
580             the scope you're in, you should use 'local':
581              
582             local $Backticks::chomped = 1;
583            
584             This will return $Backticks::chomped to whatever its prior state was once it
585             leaves the block.
586            
587             =back
588              
589             =head1 AUTHOR
590              
591             Anthony Kilna, C<< >> - L
592              
593             =head1 BUGS
594              
595             Please report any bugs or feature requests to
596             C,
597             or through the web interface at
598             L. I will be
599             notified, and then you'll automatically be notified of progress on your
600             bug as I make changes.
601              
602             =head1 SUPPORT
603              
604             You can find documentation for this module with the perldoc command.
605              
606             perldoc Backticks
607              
608             You can also look for information at:
609              
610             =over 4
611              
612             =item * RT: CPAN's request tracker (report bugs here)
613              
614             L
615              
616             =item * AnnoCPAN: Annotated CPAN documentation
617              
618             L
619              
620             =item * CPAN Ratings
621              
622             L
623              
624             =item * Search CPAN
625              
626             L
627              
628             =back
629              
630             =head1 LICENSE AND COPYRIGHT
631              
632             Copyright 2012 Kilna Companies.
633              
634             This program is free software; you can redistribute it and/or modify it
635             under the terms of either: the GNU General Public License as published
636             by the Free Software Foundation; or the Artistic License.
637              
638             See http://dev.perl.org/licenses/ for more information.
639              
640             =cut
641              
642             1; # End of Backticks