File Coverage

blib/lib/Shell/Carapace/SSH.pm
Criterion Covered Total %
statement 9 30 30.0
branch 0 8 0.0
condition n/a
subroutine 3 7 42.8
pod 0 2 0.0
total 12 47 25.5


line stmt bran cond sub pod time code
1             package Shell::Carapace::SSH;
2 1     1   1166 use Moo;
  1         2  
  1         7  
3              
4 1     1   280 use String::ShellQuote;
  1         2  
  1         139  
5 1     1   5 use Carp;
  1         1  
  1         468  
6              
7             has callback => (is => 'rw', required => 1);
8             has host => (is => 'rw', required => 1);
9             has ssh_options => (is => 'rw', default => sub { {} });
10             has ssh => (is => 'rw', lazy => 1, builder => 1);
11              
12             sub _build_ssh {
13 0     0     my $self = shift;
14 0           require Net::OpenSSH;
15 0 0         my %ssh_options = $self->ssh_options ? %{ $self->ssh_options } : ();
  0            
16 0           my $ssh = Net::OpenSSH->new($self->host, %ssh_options);
17 0 0         die $ssh->error if $ssh->error;
18 0           return $ssh;
19             }
20              
21             # force ssh builder to run so the connection occurs during object instantiation
22 0     0 0   sub BUILD { shift->ssh }
23              
24             sub run {
25 0     0 0   my ($self, @cmd) = @_;
26              
27 0           $self->callback->('command', $self->_stringify(@cmd), $self->host);
28              
29 0           my ($pty, $pid) = $self->ssh->open2pty(@cmd);
30              
31 0           while (my $line = <$pty>) {
32 0           $line =~ s/([\r\n])$//g;
33 0           $self->callback->('remote-output', $line, $self->host);
34             }
35              
36 0           waitpid($pid, 0);
37              
38 0 0         if ($? != 0) {
39 0           $self->callback->("error", $self->_stringify(@cmd), $self->host);
40 0           croak "cmd failed";
41             }
42             }
43              
44             sub _stringify {
45 0     0     my ($self, @cmd) = @_;
46 0 0         return $cmd[0] if @cmd == 1;
47 0           return join(" ", shell_quote @cmd);
48             }
49              
50             1;