File Coverage

blib/lib/Remember/Anything/AsPath.pm
Criterion Covered Total %
statement 45 45 100.0
branch 6 12 50.0
condition 9 11 81.8
subroutine 9 9 100.0
pod 2 3 66.6
total 71 80 88.7


line stmt bran cond sub pod time code
1             package Remember::Anything::AsPath;
2              
3 2     2   47225 use 5.010;
  2         6  
4              
5 2     2   9 use strict;
  2         3  
  2         37  
6 2     2   8 use warnings;
  2         3  
  2         45  
7 2     2   10 use Carp;
  2         3  
  2         89  
8 2     2   11 use Sereal::Encoder;
  2         7  
  2         755  
9              
10             our $VERSION = '0.06';
11              
12             sub new {
13 2     2 0 340 my ($class, %args) = @_;
14              
15 2   100     12 my $tree_depth = int(($args{tree_depth} // 2) + 1);
16 2 50       5 croak 'tree depth must be at least 1' if $tree_depth < 1;
17              
18 2   66     5 my $digest_sub = $args{digest_sub} // do {
19 1 50       2 eval { require Digest::SHA }
  1         7  
20             || croak "pass 'digest_sub' which returns path friendly chars as attribute "
21             . "or install 'Digest::SHA' module to use default digest function";
22 1         19 Digest::SHA->import('sha1_hex');
23 1         3 \&sha1_hex;
24             };
25              
26 2   100     22 my $part_length = int(length($digest_sub->(1)) / ($args{tree_depth} // 3) + 1);
27 2         18 my $encoder = Sereal::Encoder->new({ canonical => 1 });
28             $args{_path_parts_of} = sub {
29 6     6   183 unpack "(A$part_length)*", $digest_sub->( $encoder->encode(\@_) );
30 2         10 };
31              
32 2   50     6 $args{out_dir} ||= '.';
33 2         6 $args{out_dir} =~ s{[\/\\]$}{}; # remove trailing slash or backslash
34 2 50       159 eval { mkdir $args{out_dir} unless -d $args{out_dir} }
35 2 50       4 || croak 'could not create dir: "' . $args{out_dir} . '"';
36              
37 2         10 return bless \%args, $class;
38             }
39              
40             sub seen {
41 4     4 1 14 my $self = shift;
42 4   100     13 return (-f join '/', $self->{out_dir}, $self->{_path_parts_of}->(@_)) // 0;
43             }
44              
45             sub remember {
46 2     2 1 10 my $self = shift;
47              
48 2         5 my @path_parts = $self->{_path_parts_of}->(@_);
49              
50 2         10 my $full_path = join '/', $self->{out_dir}, @path_parts;
51 2 50       21 return if -f $full_path;
52              
53 2         4 my $cur_path = $self->{out_dir};
54 2         9 for my $path_part (@path_parts[0 .. $#path_parts - 1]) {
55 5         13 $cur_path .= "/$path_part";
56 5 50       6 eval { mkdir $cur_path unless -d $cur_path }
  5         157  
57             }
58              
59 2         86 open my $fh, '>', $full_path;
60 2         12 close $fh;
61              
62 2         9 return;
63             }
64              
65             1;
66              
67             __END__