File Coverage

blib/lib/EasyDNS/DDNS/State.pm
Criterion Covered Total %
statement 44 47 93.6
branch 10 20 50.0
condition 3 6 50.0
subroutine 9 10 90.0
pod 0 4 0.0
total 66 87 75.8


line stmt bran cond sub pod time code
1             package EasyDNS::DDNS::State;
2              
3 3     3   176544 use strict;
  3         5  
  3         103  
4 3     3   11 use warnings;
  3         7  
  3         179  
5              
6 3     3   16 use File::Basename ();
  3         4  
  3         64  
7 3     3   10 use File::Path qw(make_path);
  3         6  
  3         184  
8 3     3   1021 use File::Temp qw(tempfile);
  3         14509  
  3         144  
9              
10 3     3   365 use EasyDNS::DDNS::Util ();
  3         5  
  3         1242  
11              
12             sub new {
13 3     3 0 152531 my ($class, %args) = @_;
14              
15 3   50     11 my $path = $args{path} // '';
16             my $self = bless {
17             path => $path,
18 3   100     30 verbose => $args{verbose} // 0,
19             }, $class;
20              
21 3         12 return $self;
22             }
23              
24             sub getPath {
25 0     0 0 0 my ($self) = @_;
26 0   0     0 return $self->{path} // '';
27             }
28              
29             sub getLastIp {
30 5     5 0 16 my ($self) = @_;
31 5         16 my $path = $self->{path};
32              
33 5 50       12 return '' if !$path;
34 5 100       127 return '' if !-f $path;
35              
36 3 50       78 open my $fh, '<', $path or return '';
37 3         54 my $line = <$fh>;
38 3         22 close $fh;
39              
40 3         8 $line = EasyDNS::DDNS::Util::trim($line);
41 3         38 return $line;
42             }
43              
44             sub setLastIp {
45 3     3 0 10 my ($self, $ip) = @_;
46 3         8 my $path = $self->{path};
47              
48 3 50       11 die "State path not set\n" if !$path;
49              
50 3         10 $ip = EasyDNS::DDNS::Util::trim($ip);
51 3 50       16 die "Refusing to store empty IP\n" if $ip eq '';
52              
53 3         199 my $dir = File::Basename::dirname($path);
54 3 50       69 if (!-d $dir) {
55 0 0       0 make_path($dir) or die "Failed to create state dir '$dir': $!\n";
56             }
57              
58             # Atomic write: write to temp file in same directory, then rename.
59 3         19 my ($fh, $tmp) = tempfile('last_ip.XXXXXX', DIR => $dir, UNLINK => 0);
60 3 50       1382 print {$fh} $ip, "\n" or die "Failed writing temp state file: $!\n";
  3         67  
61 3 50       154 close $fh or die "Failed closing temp state file: $!\n";
62              
63 3 50       408 rename($tmp, $path) or die "Failed renaming '$tmp' -> '$path': $!\n";
64              
65 3         35 return 1;
66             }
67              
68             1;
69              
70             __END__