blib/lib/MYDan/Collector/Stat/Backup.pm untested

filter: Statementstmt 0.0% 0 / 56 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 105 CC 12 SCAR 47.1
CC
12
Cov
0%
co
156.0
BEGIN
2.0
BEGIN
2.0
CRAP 110.7
1 package MYDan::Collector::Stat::Backup;
2  
3 use strict;
4 use warnings;
5 use Carp;
6 use POSIX;
7  
8 use MYDan::Collector::Util;
9  
10 our $path;
11 my ( $max, $xxx ) = ( 32, sprintf '0' x 32 );
12  
13 sub co
14 {
15 my ( $this, @backup, @stat, %backup ) = @_;
16  
17 push @stat, [ 'BACKUP', 'md5' ];
18  
19 return \@stat unless $path && -d $path;
20  
21 map{ $backup{$1} = $2 if $_ =~ /^\{BACKUP\}\{([\w\/*.:_-]+)\}\{(\d+)\}/ }@backup;
22  
23 for my $backup ( keys %backup )
24 {
25 my @file = grep{ -f $_ && $_ =~ /^[\w\/*.:_-]+$/ }
26 $backup =~ /\*/ ? glob $backup: $backup;
27  
28 my ( $i, $keep )= ( 1, $backup{$backup} );
29  
30 for my $file ( @file )
31 {
32 last if $i++ > $max;
33  
34 my $md5 = MYDan::Collector::Util::qx( "md5sum '$file'" );
35 next unless $md5 =~ /^(\w{32})\s+$file$/;
36 $md5 = $1;
37
38 my $dst = $file; $dst =~ s/\//=/g;
39  
40 if( ! $keep || -f "$path/$dst=$md5" )
41 {
42 push @stat, [ $file, $md5 ];
43 next;
44 }
45  
46  
47 if( MYDan::Collector::Util::system "cp '$file' '$path/$dst=$xxx'" )
48 {
49 warn "backup copy fail: $?\n";
50 next;
51 }
52  
53 my $d = MYDan::Collector::Util::qx( "md5sum '$path/$dst=$xxx'" );
54 next unless $d =~ /^(\w{32})\s+$path\/$dst=$xxx$/;
55 $d = $1;
56 if( MYDan::Collector::Util::system "mv '$path/$dst=$xxx' '$path/$dst=$d'" )
57 {
58 warn "backup mv fail: $?\n";
59 next;
60 }
61  
62 my %data = map{ $_ => ( stat $_ )[9] }
63 grep{ -f $_ && $_ =~ /^$path\/$dst=\w{32}$/ }glob "$path/$dst*";
64  
65 my @data = sort{ $data{$b} <=> $data{$a} } keys %data;
66 unlink splice @data, $keep if @data > $keep;
67  
68 push @stat, [ $file, $d ] if -f "$path/$dst=$d";
69 }
70 }
71  
72 return \@stat;
73 }
74  
75 1;