5a3c1ff24b3105dfbaf1a77ec1ed079de08d5034
[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_path {
11         warn "### VFS make_path $_[0]\n";
12         File::Path::make_path(@_);
13 }
14
15 sub remove_path {
16         warn "### VFS remove_path $_[0]\n";
17         File::Path::remove_tree(@_);
18 }
19
20 sub remove_file {
21         warn "### VFS unlink $_[0]\n";
22         unlink $_[0];
23 }
24
25 sub write_file {
26         warn "### VFS write_file $_[0]\n";
27         File::Slurp::write_file(@_);
28 }
29
30 sub modify_existing {
31         warn "### VFS modify_existing $_[0]\n";
32 }
33
34 sub rsync_transfer {
35         my ( $data ) = @_;
36         my $json = encode_json $data;
37
38         my $json_path = "users/$data->{login}/json/$data->{file}";
39
40         if ( $data->{itemize} =~ m/^[c>]([fd])/ ) { # received change/create
41                 my $type = $1;
42                 if ( -e $json_path ) {
43                         modify_existing $json_path;
44                         return $json;
45                 }
46
47                 if ( $type eq 'f' ) {
48                         if ( $json_path =~ m{^(.+)/[^/]+$} ) { # have dir
49                                 make_path $1 if ! -e $1;
50                         }
51                         write_file $json_path, $json;
52                 } elsif ( $type eq 'd' ) {
53                         make_path $json_path;
54                 }
55         } elsif ( $data->{itemize} =~ m/\*deleting/ ) {
56                 if ( -d $json_path ) {
57                         remove_path $json_path;
58                 } elsif ( -f $json_path ) {
59                         remove_file $json_path;
60                 }
61         }
62         return $json;
63 }
64
65
66 1;