SimpleBackuper/StorageSFTP.pm untested

filter: Statementstmt 0.0% 0 / 56 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 99 CC 4 SCAR 15.1
CC
4
Cov
0%
_do
12.0
_connect
6.0
new
2.0
CRAP 4.5
1 package App::SimpleBackuper::StorageSFTP;
2  
3 use strict;
4 use warnings;
5 use Try::Tiny;
6 use Net::SFTP::Foreign;
7 use Net::SFTP::Foreign::Constants qw(SSH2_FX_CONNECTION_LOST);
8  
9 sub new {
10 my($class, $options) = @_;
11 my(undef, $user, $host, $path) = $options =~ /^(([^@]+)@)?([^:]+):(.*)$/;
12
13 my $self = bless {user => $user, host => $host, path => $path} => $class;
14 $self->_connect();
15
16 return $self;
17 }
18  
19 sub _connect {
20 my($self) = @_;
21
22 $self->{sftp} = Net::SFTP::Foreign->new(host => $self->{host}, ($self->{user} ? (user => $self->{user}) : ()), timeout => 30);
23 $self->{sftp}->die_on_error("SFTP connect error");
24 $self->{sftp}->setcwd($self->{path}) or die "Can't setcwd to '$self->{path}': ".$self->{sftp}->error;
25 }
26  
27 sub _do {
28 my($self, $method, $params) = @_;
29 my $attempts_left = 3;
30 my @result;
31 while(1) {
32 @result = $self->{sftp}->$method(@$params);
33 last if @result and defined $result[0];
34 if($self->{sftp}->status == SSH2_FX_CONNECTION_LOST and $attempts_left--) {
35 print " (".$self->{sftp}->error.", reconnecting)";
36 sleep 30;
37 try {
38 $self->_connect()
39 } catch {
40 print " (attempt to reconnect failed: $_)";
41 };
42 } else {
43 $self->{sftp}->die_on_error("Can't $method (@$params) (status=".$self->{sftp}->status.")");
44 }
45 }
46 return \@result;
47 }
48  
49 sub put {
50 my($self, $name, $content_ref) = @_;
51 $self->_do(put_content => [ $$content_ref, $name ]);
52 return $self;
53 }
54  
55 sub get {
56 my($self, $name) = @_;
57 return $self->_do(get_content => [ $name ]);
58 }
59  
60 sub remove {
61 my($self, $name) = @_;
62 $self->_do(remove => [ $name ]);
63 return $self;
64 }
65  
66 sub listing {
67 my($self) = @_;
68 my $files = $self->_do(ls => [ '' ])->[0];
69 return { map {$_->{filename} => $_->{a}->size} grep {$_->{filename} ne '..' and $_->{filename} ne '.'} @$files };
70 }
71  
72 1;