r262@brr: dpavlin | 2007-11-25 14:33:40 +0100
[perl-cwmp.git] / lib / CWMP / Store / HASH.pm
1 package CWMP::Store::HASH;
2
3 use strict;
4 use warnings;
5
6 use Data::Dump qw/dump/;
7 use Hash::Merge qw/merge/;
8 use Carp qw/confess/;
9
10 =head1 NAME
11
12 CWMP::Store::HASH - base class for hash based storage engines
13
14 =head1 METHODS
15
16 =head2 open
17
18   $store->open({
19         path => 'var/',
20         debug => 1,
21         clean => 1,
22   });
23
24 =cut
25
26 my $path;
27
28 my $debug = 0;
29
30 sub open {
31         my $self = shift;
32
33         my $args = shift;
34
35         $debug = $args->{debug};
36         $path = $args->{path} || confess "no path?";
37
38         warn "open ",dump( $args ) if $debug;
39
40         $path = $self->full_path( $path );
41
42         if ( ! -e $path ) {
43                 mkdir $path || die "can't create $path: $!";
44                 warn "created $path directory\n" if $debug;
45         } elsif ( $args->{clean} ) {
46                 warn "removed old $path\n" if $debug;
47                 foreach my $uid ( $self->all_uids ) {
48                         my $file = $self->file( $uid );
49                         unlink $file || die "can't remove $file: $!";
50                 }
51         }
52
53
54 }
55
56 =head2 update_uid_state
57
58   $store->update_uid_state( $uid, $state );
59
60 =cut
61
62 sub update_uid_state {
63         my ( $self, $uid, $state ) = @_;
64
65         my $file = $self->file( $uid );
66
67         my $old_state = $self->get_state( $uid );
68
69         my $combined = merge( $state, $old_state );
70
71 #       warn "## ",dump( $old_state, $state, $combined );
72
73         $self->save_hash( $file, $combined ) || die "can't write $file: $!";
74
75 }
76
77 =head2 get_state
78
79   $store->get_state( $uid );
80
81 =cut
82
83 sub get_state {
84         my ( $self, $uid ) = @_;
85
86         my $file = $self->file( $uid );
87
88         if ( -e $file ) {
89                 return $self->load_hash( $file );
90         }
91
92         return;
93 }
94
95 =head2 all_uids
96
97   my @uids = $store->all_uids;
98
99 =cut
100
101 sub all_uids {
102         my $self = shift;
103
104         my $ext = $self->extension;
105         warn "## extension: $ext";
106
107         opendir(my $d, $path) || die "can't opendir $path: $!";
108         my @uids = grep { $_ =~ m/\Q$ext\E$/ && -f "$path/$_" } readdir($d);
109         closedir $d;
110
111         return map { my $l = $_; $l =~ s/\Q$ext\E$//; $l } @uids;
112 }
113
114 1;