root/trunk/extlib/IPC/Cmd.pm

Revision 4158, 16.8 kB (checked in by fumiakiy, 7 months ago)

Importing greyhound to public repository.

Line 
1package IPC::Cmd;
2
3use Params::Check               qw[check];
4use Module::Load::Conditional   qw[can_load];
5use Locale::Maketext::Simple    Style => 'gettext';
6
7use ExtUtils::MakeMaker();
8use File::Spec ();
9use Config;
10
11use strict;
12
13require Carp;
14$Carp::CarpLevel = 1;
15
16BEGIN {
17    use Exporter    ();
18    use vars        qw[ @ISA $VERSION @EXPORT_OK $VERBOSE
19                        $USE_IPC_RUN $USE_IPC_OPEN3
20                    ];
21
22    $VERSION        = '0.24';
23    $VERBOSE        = 0;
24    $USE_IPC_RUN    = 1;
25    $USE_IPC_OPEN3  = 1;
26
27    @ISA            = qw[Exporter];
28    @EXPORT_OK      = qw[can_run run];
29}
30
31### check if we can run some command ###
32sub can_run {
33    my $command = shift;
34
35    if( File::Spec->file_name_is_absolute($command) ) {
36        return MM->maybe_command($command);
37   
38    } else {   
39        for my $dir (split /$Config{path_sep}/, $ENV{PATH}) {
40            my $abs = File::Spec->catfile($dir, $command);
41            return $abs if $abs = MM->maybe_command($abs);
42        }
43    }
44}
45
46
47### Execute a command: $cmd may be a scalar or an arrayref of cmd and args
48### $bufout is a scalar ref to store outputs, $verbose can override conf
49sub run {
50    my %hash = @_;
51
52    my $x = '';
53    my $tmpl = {
54        verbose => { default    => $VERBOSE },
55        command => { required   => 1,
56                     allow      => sub {my $cmd = pop();
57                                        !(ref $cmd) or ref $cmd eq 'ARRAY' }
58                   },
59        buffer  => { default => \$x },             
60    };
61
62    my $args = check( $tmpl, \%hash, $VERBOSE )
63                or ( warn(loc(q[Could not validate input!])), return );
64
65    ### Kludge! This enables autoflushing for each perl process we launched.
66    ### XXX probably not really needed, and seems to throw quite a few
67    ### 'make test' etc off to have PERL5OPT set
68    #local $ENV{PERL5OPT} = ($ENV{PERL5OPT} || '') .
69    #                            ' -MIPC::Cmd::System=autoflush=1';
70
71    my $verbose     = $args->{verbose};
72    my $is_win98    = ($^O eq 'MSWin32' and !Win32::IsWinNT());
73
74    my $err;                # error flag
75    my $have_buffer;        # to indicate we executed via IPC::Run
76                            # or IPC::Open3 only then it makes sence
77                            # to return the buffers
78
79    my (@buffer,@buferr,@bufout);
80
81    ### STDOUT message handler
82    my $_out_handler = sub {
83    #sub _out_handler {
84        my $buf = shift;
85        return unless defined $buf;
86
87        print STDOUT $buf if $verbose;
88        push @buffer, $buf;
89        push @bufout, $buf;
90    };
91
92    ### STDERR message handler
93    my $_err_handler = sub {
94    #sub _err_handler {
95        my $buf = shift;
96        return unless defined $buf;
97
98        print STDERR $buf if $verbose;
99        push @buffer, $buf;
100        push @buferr, $buf;
101    };
102
103    my $cmd = $args->{command};
104    my @cmd = ref ($cmd) ? grep(length, @{$cmd}) : $cmd;
105
106    print loc(qq|Running [%1]...\n|,"@cmd") if $verbose;
107
108    ### First, we prefer Barrie Slaymaker's wonderful IPC::Run module.
109    if (!$is_win98 and $USE_IPC_RUN and 
110        can_load(
111            modules => { 'IPC::Run' => '0.55' },
112            verbose => $verbose && ($^O eq 'MSWin32') ) 
113    ) {
114        STDOUT->autoflush(1); STDERR->autoflush(1);
115
116        $have_buffer++;
117
118        ### a command like:
119        # [
120        #     '/usr/bin/gzip',
121        #     '-cdf',
122        #     '/Users/kane/sources/p4/other/archive-extract/t/src/x.tgz',
123        #     '|',
124        #     '/usr/bin/tar',
125        #     '-tf -'
126        # ]
127        ### needs to become:
128        # [
129        #     ['/usr/bin/gzip', '-cdf',
130        #       '/Users/kane/sources/p4/other/archive-extract/t/src/x.tgz']
131        #     '|',
132        #     ['/usr/bin/tar', '-tf -']
133        # ]
134
135        my @command; my $special_chars;
136        if( ref $cmd ) {
137            my $aref = [];
138            for my $item (@cmd) {
139                if( $item =~ /[<>|&]/ ) {
140                    push @command, $aref, $item;
141                    $aref = [];                 
142                    $special_chars++;
143                } else {
144                    push @$aref, $item;
145                }
146            }           
147            push @command, $aref;
148        } else {
149            @command = map { if( /[<>|&]/ ) {
150                                $special_chars++; $_;
151                             } else {                           
152                                [ split / +/ ]
153                             }
154                        } split( /\s*([<>|&])\s*/, $cmd );
155        }
156       
157        ### due to the double '>' construct, stdout buffers are now ending
158        ### up in the stderr buffer. this is a bug in IPC::Run.
159        ### Mailed barries about this early june, no solution yet :(
160        ### update (23-6-04): so this thing with the double > makes
161        ### this command not even fill any buffer:
162        ###     perl -lewarn$$
163        ### so it looks like when there are no 'special' chars in the
164        ### command, like '|' and friends, best not use the '>' construct.
165        if( $special_chars ) {             
166            IPC::Run::run(@command, \*STDIN, '>', $_out_handler, 
167                                             '>', $_err_handler) or $err++;
168        } else {
169            IPC::Run::run(@command, \*STDIN, $_out_handler, 
170                                         $_err_handler) or $err++;
171        }
172 
173 
174    ### Next, IPC::Open3 is know to fail on Win32, but works on Un*x.
175    } elsif (   $^O !~ /^(?:MSWin32|cygwin)$/
176                and $USE_IPC_OPEN3
177                and can_load(
178                    modules => { map{$_ => '0.0'} 
179                                qw|IPC::Open3 IO::Select Symbol| },
180                    verbose => $verbose
181    ) ) {
182        my $rv;
183        ($rv,$err) = _open3_run(\@cmd, $_out_handler, $_err_handler);
184        $have_buffer++;
185
186
187    ### Abandon all hope; falls back to simple system() on verbose calls.
188    } elsif ($verbose) {
189        ### quote for if we have pipes or anything else in there
190        system("@cmd");
191        $err = $? ? $? : 0;
192
193    ### Non-verbose system() needs to have STDOUT and STDERR muted.
194    } else {
195        local *SAVEOUT; local *SAVEERR;
196
197        open(SAVEOUT, ">&STDOUT")
198            or warn(loc("couldn't dup STDOUT: %1",$!)),      return;
199        open(STDOUT, ">".File::Spec->devnull)
200            or warn "couldn't reopen STDOUT: $!",   return;
201
202        open(SAVEERR, ">&STDERR")
203            or warn(loc("couldn't dup STDERR: %1",$!)),      return;
204        open(STDERR, ">".File::Spec->devnull)
205            or warn(loc("couldn't reopen STDERR: %1",$!)),   return;
206
207        ### quote for if we have pipes or anything else in there
208        system("@cmd");
209
210        open(STDOUT, ">&SAVEOUT")
211            or warn(loc("couldn't restore STDOUT: %1",$!)), return;
212        open(STDERR, ">&SAVEERR")
213            or warn(loc("couldn't restore STDERR: %1",$!)), return;
214    }
215
216    ### unless $err has been set from _open3_run, set it to $? ###
217    $err ||= $?;
218
219    if ( scalar @buffer ) {
220        my $capture = $args->{buffer};
221        $$capture = join '', @buffer;
222    }
223   
224    return wantarray
225                ? $have_buffer
226                    ? (!$err, $?, \@buffer, \@bufout, \@buferr)
227                    : (!$err, $? )
228                : !$err
229}
230
231
232### IPC::Run::run emulator, using IPC::Open3.
233sub _open3_run {
234    my ($cmdref, $_out_handler, $_err_handler, $verbose) = @_;
235   
236    ### in case there are pipes in there;
237    ### IPC::Open3 will call exec and exec will do the right thing ###
238    my $cmd = join " ", @$cmdref;
239
240    ### Following code are adapted from Friar 'abstracts' in the
241    ### Perl Monastery (http://www.perlmonks.org/index.pl?node_id=151886).
242
243    my ($infh, $outfh, $errfh); # open3 handles
244
245    my $pid = eval {
246        IPC::Open3::open3(
247            $infh   = Symbol::gensym(),
248            $outfh  = Symbol::gensym(),
249            $errfh  = Symbol::gensym(),
250            $cmd,
251        )
252    };
253
254
255    return (undef, $@) if $@;
256
257    my $sel = IO::Select->new; # create a select object
258    $sel->add($outfh, $errfh); # and add the fhs
259
260    STDOUT->autoflush(1); STDERR->autoflush(1);
261    $outfh->autoflush(1) if UNIVERSAL::can($outfh, 'autoflush');
262    $errfh->autoflush(1) if UNIVERSAL::can($errfh, 'autoflush');
263
264    while (my @ready = $sel->can_read) {
265        foreach my $fh (@ready) { # loop through buffered handles
266            # read up to 4096 bytes from this fh.
267            my $len = sysread $fh, my($buf), 4096;
268
269            if (not defined $len){
270                # There was an error reading
271                warn loc("Error from child: %1",$!);
272                return(undef, $!);
273            }
274            elsif ($len == 0){
275                $sel->remove($fh); # finished reading
276                next;
277            }
278            elsif ($fh == $outfh) {
279                $_out_handler->($buf);
280            } elsif ($fh == $errfh) {
281                $_err_handler->($buf);
282            } else {
283                warn loc("%1 error", 'IO::Select');
284                return(undef, $!);
285            }
286        }
287    }
288
289    waitpid $pid, 0; # wait for it to die
290    return 1;
291}
292
2931;
294
295__END__
296
297=pod
298
299=head1 NAME
300
301IPC::Cmd - finding and running system commands made easy
302
303=head1 SYNOPSIS
304
305    use IPC::Cmd qw[can_run run];
306
307    my $full_path = can_run('wget') or warn 'wget is not installed!';
308
309
310    ### commands can be arrayrefs or strings ###
311    my $cmd = "$full_path -b theregister.co.uk";
312    my $cmd = [$full_path, '-b', 'theregister.co.uk'];
313
314    ### in scalar context ###
315    my $buffer;
316    if( scalar run( command => $cmd,
317                    verbose => 0,
318                    buffer  => \$buffer )
319    ) {
320        print "fetched webpage successfully\n";
321    }
322
323
324    ### in list context ###
325    my( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
326            run( command => $cmd, verbose => 0 );
327
328    if( $success ) {
329        print "this is what the command printed:\n";
330        print join "", @$full_buf;
331    }
332
333
334    ### don't have IPC::Cmd be verbose, ie don't print to stdout or
335    ### stderr when running commands -- default is '0'
336    $IPC::Cmd::VERBOSE = 0;
337
338=head1 DESCRIPTION
339
340IPC::Cmd allows you to run commands, interactively if desired,
341platform independent but have them still work.
342
343The C<can_run> function can tell you if a certain binary is installed
344and if so where, whereas the C<run> function can actually execute any
345of the commands you give it and give you a clear return value, as well
346as adhere to your verbosity settings.
347
348=head1 FUNCTIONS
349
350=head2 can_run
351
352C<can_run> takes but a single argument: the name of a binary you wish
353to locate. C<can_run> works much like the unix binary C<which> or the bash
354command C<type>, which scans through your path, looking for the requested
355binary .
356
357Unlike C<which> and C<type>, this function is platform independent and
358will also work on, for example, Win32.
359
360It will return the full path to the binary you asked for if it was
361found, or C<undef> if it was not.
362
363=head2 run
364
365C<run> takes 3 arguments:
366
367=over 4
368
369=item command
370
371This is the command to execute. It may be either a string or an array
372reference.
373This is a required argument.
374
375See L<CAVEATS> for remarks on how commands are parsed and their
376limitations.
377
378=item verbose
379
380This controls whether all output of a command should also be printed
381to STDOUT/STDERR or should only be trapped in buffers (NOTE: buffers
382require C<IPC::Run> to be installed or your system able to work with
383C<IPC::Open3>).
384
385It will default to the global setting of C<$IPC::Cmd::VERBOSE>,
386which by default is 0.
387
388=item buffer
389
390This will hold all the output of a command. It needs to be a reference
391to a scalar.
392Note that this will hold both the STDOUT and STDERR messages, and you
393have no way of telling which is which.
394If you require this distinction, run the C<run> command in list context
395and inspect the individual buffers.
396
397Of course, this requires that the underlying call supports buffers. See
398the note on buffers right above.
399
400=back
401
402C<run> will return a simple C<true> or C<false> when called in scalar
403context.
404In list context, you will be returned a list of the following items:
405
406=over 4
407
408=item success
409
410A simple boolean indicating if the command executed without errors or
411not.
412
413=item errorcode
414
415If the first element of the return value (success) was 0, then some
416error occurred. This second element is the error code the command
417you requested exited with, if available.
418
419=item full_buffer
420
421This is an arrayreference containing all the output the command
422generated.
423Note that buffers are only available if you have C<IPC::Run> installed,
424or if your system is able to work with C<IPC::Open3> -- See below).
425This element will be C<undef> if this is not the case.
426
427=item out_buffer
428
429This is an arrayreference containing all the output sent to STDOUT the
430command generated.
431Note that buffers are only available if you have C<IPC::Run> installed,
432or if your system is able to work with C<IPC::Open3> -- See below).
433This element will be C<undef> if this is not the case.
434
435=item error_buffer
436
437This is an arrayreference containing all the output sent to STDERR the
438command generated.
439Note that buffers are only available if you have C<IPC::Run> installed,
440or if your system is able to work with C<IPC::Open3> -- See below).
441This element will be C<undef> if this is not the case.
442
443=back
444
445C<run> will try to execute your command using the following logic:
446
447=over 4
448
449=item *
450
451If you are not on windows 98 and have C<IPC::Run> installed, use that
452to execute the command. You will have the full output available in
453buffers, interactive commands are sure to work  and you are guaranteed
454to have your verbosity settings honored cleanly.
455
456=item *
457
458Otherwise, if you are not on MSWin32 or Cygwin, try to execute the
459command by using C<IPC::Open3>. Buffers will be available, interactive
460commands will still execute cleanly, and also your  verbosity settings
461will be adhered to nicely;
462
463=item *
464
465Otherwise, if you have the verbose argument set to true, we fall back
466to a simple system() call. We cannot capture any buffers, but
467interactive commands will still work.
468
469=item *
470
471Otherwise we will try and temporarily redirect STDERR and STDOUT, do a
472system() call with your command and then re-open STDERR and STDOUT.
473This is the method of last resort and will still allow you to execute
474your commands cleanly. However, no buffers will be available.
475
476=head1 Global Variables
477
478The behaviour of IPC::Cmd can be altered by changing the following
479global variables:
480
481=head2 $IPC::Cmd::VERBOSE
482
483This controls whether IPC::Cmd will print any output from the
484commands to the screen or not. The default is 0;
485
486=head2 $IPC::Cmd::USE_IPC_RUN
487
488This variable controls whether IPC::Cmd will try to use L<IPC::Run>
489when available and suitable. Defaults to true.
490
491=head2 $IPC::Cmd::USE_IPC_OPEN3
492
493This variable controls whether IPC::Cmd will try to use L<IPC::Open3>
494when available and suitable. Defaults to true.
495
496=head2 Caveats
497
498=over 4
499
500=item Whitespace
501
502When you provide a string as this argument, the string will be
503split on whitespace to determine the individual elements of your
504command. Although this will usually just Do What You Mean, it may
505break if you have files or commands with whitespace in them.
506
507If you do not wish this to happen, you should provide an array
508reference, where all parts of your command are already separated out.
509Note however, if there's extra or spurious whitespace in these parts,
510the parser or underlying code may not interpret it correctly, and
511cause an error.
512
513Example:
514The following code
515   
516    gzip -cdf foo.tar.gz | tar -xf -
517   
518should either be passed as
519
520    "gzip -cdf foo.tar.gz | tar -xf -"
521
522or as
523
524    ['gzip', '-cdf', 'foo.tar.gz', '|', 'tar', '-xf', '-']
525   
526But take care not to pass it as, for example
527   
528    ['gzip -cdf foo.tar.gz', '|', 'tar -xf -']           
529
530Since this will lead to issues as described above.
531
532=item IO Redirect
533
534Currently it is too complicated to parse your command for IO
535Redirections. For capturing STDOUT or STDERR there is a work around
536however, since you can just inspect your buffers for the contents.
537
538=item IPC::Run buffer capture bug
539
540Due to a bug in C<IPC::Run> versions upto and including the latest one
541at the time of writing (0.78), C<run()> calls executed via C<IPC::Run>
542will not be able to differentiate between C<STDOUT> and C<STDERR>
543output when C<special characters> are present in the command (like
544<,>,| and &); All output will be caught in the C<STDERR> buffer.
545
546Note that this is only a problem if you use the long output of C<run()>
547and not if you provide the C<buffer> option to the command.
548
549If this limitation is not acceptable to you, consider setting the
550global variable C<$IPC::Cmd::USE_IPC_RUN> to false.
551
552
553=back
554
555=head1 See Also
556
557C<IPC::Run>, C<IPC::Open3>
558
559=head1 AUTHOR
560
561This module by
562Jos Boumans E<lt>kane@cpan.orgE<gt>.
563
564=head1 COPYRIGHT
565
566This module is
567copyright (c) 2002,2003,2004 Jos Boumans E<lt>kane@cpan.orgE<gt>.
568All rights reserved.
569
570This library is free software;
571you may redistribute and/or modify it under the same
572terms as Perl itself.
Note: See TracBrowser for help on using the browser.