Merge branch 'attr'
[cloudstore.git] / lib / CloudStore / JSON.pm
1 package CloudStore::JSON;
2 use warnings;
3 use strict;
4
5 use autodie;
6 use JSON::XS;
7 use File::Path qw();
8 use File::Slurp qw();
9
10 sub make_dir {
11         my ( $dir, $json ) = @_;
12         warn "### VFS make_dir $dir\n";
13         File::Path::make_path($dir);
14         $dir =~ s{/([^/]+)/?$}{/.$1};
15         File::Slurp::write_file $dir, $json if $json;
16 }
17
18 sub remove_dir {
19         warn "### VFS remove_dir $_[0]\n";
20         File::Path::remove_tree(@_);
21 }
22
23 sub remove_file {
24         warn "### VFS unlink $_[0]\n";
25         unlink $_[0];
26 }
27
28 sub write_file {
29         warn "### VFS ", -e $_[0] ? 'modify' : 'write', "_file $_[0]\n";
30         File::Slurp::write_file(@_);
31 }
32
33 sub read_file {
34         my $path = shift;
35         warn "### VFS read_file $path\n";
36         $path =~ s{/([^/]+)/?$}{/.$1} if -d $path;
37         File::Slurp::read_file($path);
38 }
39
40 sub rsync_transfer {
41         my ( $data ) = @_;
42         my $json = encode_json $data;
43
44         my $path = "users/$data->{login}/json/$data->{file}";
45
46         if ( $data->{itemize} =~ m/^[c>]([fd])/ ) { # received change/create
47                 my $type = $1;
48
49                 if ( $type eq 'f' ) {
50                         if ( $path =~ m{^(.+)/[^/]+$} ) { # have dir
51                                 make_dir $1, $json if ! -e $1;
52                         }
53                         write_file $path, $json;
54                 } elsif ( $type eq 'd' ) {
55                         make_dir $path, $json;
56                 } else {
57                         die "unknown type $type";
58                 }
59         } elsif ( $data->{itemize} =~ m/\*deleting/ ) {
60                 if ( -d $path ) {
61                         remove_dir $path;
62                 } elsif ( -f $path ) {
63                         remove_file $path;
64                 } else {
65                         warn "ignored delete $path";
66                 }
67         }
68         return $json;
69 }
70
71 sub file_data {
72         my $path = shift;
73         $path =~ s{/blob/}{/json/};
74         return decode_json read_file $path;
75 }
76
77 1;