aboutsummaryrefslogtreecommitdiff
path: root/lib/App/Beam/Command.pm
blob: ed6c686a4ea40b3b170507be312f8f9947b755e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package App::Beam::Command;

use strict;
use Carp;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(CHAN_STDOUT CHAN_STDERR);
our %EXPORT_TAGS = (
    channels => [ qw(CHAN_STDOUT CHAN_STDERR) ]
);

use IPC::Open3;
use Symbol 'gensym';

sub new {
    my $class = shift;
    return bless { argv => \@_ }, $class;
}

sub add {
    my $self = shift;
    push @{$self->{argv}}, @_;
}

use constant {
    CHAN_STDOUT => 0,
    CHAN_STDERR => 1
};

sub run {
    my $self = shift;
    my $out = gensym;
    my $err = gensym;

    return $self->{status} if exists($self->{status});
    
    my $pid = open3(\*STDIN, $out, $err, @{$self->{argv}});
    waitpid($pid, 0);
    $self->{status} = $?;
    local $/ = undef;
    $self->{channel}[CHAN_STDOUT] = <$out>;
    $self->{channel}[CHAN_STDERR] = <$err>;
    return $self->{status};
}

sub restart {
    my $self = shift;

    delete $self->{status};
    delete $self->{channel};
    return $self->run;
}

sub status {
    my $self = shift;
    return undef unless exists $self->{status};
    return $self->{status};
}

sub channel {
    my ($self, $chan) = @_;
    return undef if !exists($self->{channel}) || $chan > $#{$self->{channel}};
    open(my $fd, '<', \$self->{channel}[$chan]) or croak "can't dup: $!"; 
    return $fd;
}

sub argv {
    my ($self) = @_;
    return @{$self->{argv}};
}

sub command_line {
    my ($self) = @_;
    return join(' ', $self->argv);
}

sub command_name {
    my ($self) = @_;
    return $self->{argv}[0];
}

sub exit_code {
    my ($self) = @_;
    my $code = $self->status;
    return -1 if (!defined($code) || $code == -1 || ($code & 127));
    return $code >> 8;
}

1;

    

	


Return to:

Send suggestions and report system problems to the System administrator.