1 |
#!/usr/bin/perl |
2 |
|
3 |
use warnings; |
4 |
use strict; |
5 |
|
6 |
use LWP::UserAgent; |
7 |
use JSON; |
8 |
use Data::Dump qw/dump/; |
9 |
use File::Path qw/mkpath/; |
10 |
use File::Slurp qw//; |
11 |
|
12 |
# design-couch.pl |
13 |
# |
14 |
# 04/26/09 21:12:28 CEST Dobrica Pavlinusic <dpavlin@rot13.org> |
15 |
|
16 |
my ( $command, $database, $design ) = @ARGV; |
17 |
die "usage: $0 [push|pull] database design\n" unless $database && $design; |
18 |
|
19 |
my $ua = LWP::UserAgent->new; |
20 |
|
21 |
my $url = "http://llin.lan:5984/$database/_design/$design"; |
22 |
|
23 |
sub create_path { |
24 |
my $path = shift; |
25 |
if ( $path =~ m{/} ) { |
26 |
my $dir = $path; |
27 |
$dir =~ s{/[^/]+$}{}; |
28 |
mkpath $dir if ! -e $dir; |
29 |
#warn "# dir $dir"; |
30 |
} |
31 |
} |
32 |
sub write_file { |
33 |
my ( $path, $content ) = @_; |
34 |
$path =~ s{^/+}{}; |
35 |
create_path $path; |
36 |
File::Slurp::write_file $path, $content; |
37 |
print "$path ", -s $path, " bytes\n"; |
38 |
} |
39 |
|
40 |
sub write_attachment { |
41 |
my ( $path ) = @_; |
42 |
my $file = "_attachemnts/$path"; |
43 |
create_path $file; |
44 |
$ua->mirror( "$url/$path", $file ); |
45 |
print "detached $file ", -s $file, " bytes\n"; |
46 |
} |
47 |
|
48 |
sub unroll { |
49 |
my ( $tree, $path ) = @_; |
50 |
|
51 |
my $ref = ref $tree; |
52 |
if ( $ref eq 'HASH' ) { |
53 |
foreach my $child ( keys %$tree ) { |
54 |
if ( $child eq '_attachments' ) { |
55 |
write_attachment $_ foreach keys %{ $tree->{$child} }; |
56 |
} else { |
57 |
unroll( $tree->{$child}, $path ? "$path/$child" : $child ); |
58 |
} |
59 |
} |
60 |
} elsif ( $ref ) { |
61 |
warn "UNSUPPORTED $path $ref ", dump( $tree ); |
62 |
write_file "$path.json", to_json $tree; |
63 |
} elsif ( $ref eq '' ) { |
64 |
|
65 |
if ( $tree =~ m[^\s*(function(.*){.*}|/\*|//|var)]is ) { |
66 |
$path .= '.js'; |
67 |
} elsif ( $tree =~ m{<%=.*%>} ) { # couchapp template |
68 |
$path .= '.html'; |
69 |
} else { |
70 |
warn "# can't detect type of $path\n"; |
71 |
} |
72 |
|
73 |
write_file $path, $tree; |
74 |
} |
75 |
|
76 |
} |
77 |
|
78 |
if ( $command eq 'pull' ) { |
79 |
|
80 |
warn "# get $url\n"; |
81 |
my $response = $ua->get( $url ); |
82 |
|
83 |
die $response->status_line if $response->is_error; |
84 |
|
85 |
my $json = $response->decoded_content; |
86 |
write_file "../$database-$design.js", $json; |
87 |
|
88 |
unroll( from_json $json, '' ); |
89 |
|
90 |
} elsif ( $command eq 'push' ) { |
91 |
|
92 |
|
93 |
|
94 |
} else { |
95 |
die "$0: unknown command $command"; |
96 |
} |
97 |
|