lib/WWW/Shopify/Tools/Themer.pm untested

filter: Statementstmt 0.0% 0 / 319 Branchbran 0.0% 0 / 80 Conditioncond 0.0% 0 / 49 MC/DCmcdc 0.0% 0 / 26 Subroutinesub 0.0% 0 / 52 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 559 CC 41 SCAR 29.1
CC
41
Cov
0%
push
72.0
new
42.0
push_pages
42.0
CRAP 18.3
1 #!/usr/bin/perl
2  
3 use strict;
4 use warnings;
5  
6 use WWW::Shopify;
7 use WWW::Shopify::Private;
8  
9 package WWW::Shopify::Tools::Themer::Manifest;
10 use JSON;
11 use File::stat;
12 use File::Slurp;
13 use Scalar::Util qw(weaken);
14  
15 # When we save things down, we translate everything to absolute paths. W
16 sub new { return bless { }, $_[0]; }
17 sub load {
18 die unless -e $_[1];
19 my $json = decode_json(read_file($_[1]));
20 for (keys(%{$json->{files}})) {
21 $json->{files}->{$_}->{'local'} = DateTime->from_epoch(epoch => $json->{files}->{$_}->{'local'});
22 $json->{files}->{$_}->{'remote'} = DateTime->from_epoch(epoch => $json->{files}->{$_}->{'remote'});
23 $json->{files}->{$_}->{'system'} = DateTime->from_epoch(epoch => $json->{files}->{$_}->{'system'});
24 }
25 $_[0]->{files} = $json->{files};
26 $_[0]->{themes} = $json->{themes};
27 }
28 sub save {
29 my $json = {themes => [], files => {}};
30 for (keys(%{$_[0]->{files}})) {
31 $json->{files}->{$_} = {
32 'local' => $_[0]->{files}->{$_}->{'local'}->epoch,
33 'remote' => $_[0]->{files}->{$_}->{'remote'}->epoch,
34 'system' => $_[0]->{files}->{$_}->{'system'}->epoch
35 };
36 }
37 $json->{themes} = [map { {name => $_->{name}, id => $_->{id}, role => $_->{role}} } @{$_[0]->{themes}} ];
38 write_file($_[1], encode_json($json)) or die $!;
39 }
40  
41 sub local_path {
42 my ($self, $path) = @_;
43 my $directory = $self->directory;
44 return undef unless $path;
45 $path =~ s/^$directory//g;
46 return $path;
47 }
48  
49 sub absolute_path {
50 my ($self, $path) = @_;
51 my $directory = $self->directory;
52 $path = "$directory/$path" unless $path =~ m/^$directory/;
53 return $path;
54 }
55  
56 sub exists { return (exists $_[0]->{files}->{$_[0]->local_path($_[1])}); }
57 sub local { my $path = $_[0]->local_path($_[1]); $_[0]->{files}->{$path}->{'local'} = $_[2] if int(@_) == 3; return $_[0]->{files}->{$path}->{'local'}; }
58 sub remote { my $path = $_[0]->local_path($_[1]); $_[0]->{files}->{$path}->{'remote'} = $_[2] if int(@_) == 3; return $_[0]->{files}->{$path}->{'remote'}; }
59 sub system { my $path = $_[0]->local_path($_[1]); $_[0]->{files}->{$path}->{'system'} = $_[2] if int(@_) == 3; return $_[0]->{files}->{$path}->{'system'}; }
60 sub files { return keys(%{$_[0]->{files}}); }
61  
62 sub themer {
63 my ($self, $themer) = @_;
64 if (defined $themer) {
65 $_[0]->{themer} = $themer;
66 weaken($_[0]->{themer});
67 }
68 return $_[0]->{themer};
69 }
70  
71 sub directory { return $_[0]->themer->directory; }
72  
73 sub has_local_changes($$) {
74 my ($self, $path) = @_;
75 #return 0 if !$self->exists($path) || !(-e $path) || !$self->local($path);
76 return 1 if !$self->exists($path) || !(-e $path) || !$self->local($path);
77 return ($self->system($path) < DateTime->from_epoch(epoch => stat($self->absolute_path($path))->mtime));
78 }
79 sub has_remote_changes($$) {
80 my ($self, $path) = @_;
81 return undef unless $self->remote($path);
82 return 1 if !(-e $path) || !$self->local($path);
83 return ($self->local($path) < $self->remote($path));
84 }
85  
86 package WWW::Shopify::Tools::Themer;
87 use File::Basename;
88 use LWP::Simple;
89 use File::Path qw(make_path);
90 use File::Find;
91 use File::Slurp;
92 use File::stat;
93 use JSON;
94 use MIME::Base64;
95 use utf8;
96 #use threads;
97 #use threads::shared;
98  
99 our $VERSION = '0.11';
100  
101 =head1 WWW::Shopify::Tools::Themer
102  
103 The core class that deals with theme management, pushing and pulling to and from a shopify store.
104  
105 my $STC = new WWW::Shopify::Tools::Themer({url => $myurl, apikey => $myapikey, password => $mypassword, directory => $mypath});
106 OR
107 my $STC = new WWW::Shopify::Tools::Themer({url => $myurl, email => $myemail, password => $mypassword, directory => $mypath});
108  
109 Can use either a private API key, or a password.
110  
111 =cut
112  
113 sub new {
114 my ($package, $settings) = @_;
115 die new WWW::Shopify::Exception("Please pass in url, password, apikey xor email.") unless defined $settings->{url} && defined $settings->{password} && (defined $settings->{apikey} xor defined $settings->{email});
116 my $SA = new WWW::Shopify::Private($settings->{url}, $settings->{apikey}, $settings->{password});
117 $SA->login_admin($settings->{email}, $settings->{password}) if $settings->{email};
118 my $threads = (defined $settings->{threads}) ? $settings->{threads} : 4;
119 my $directory = $settings->{directory};
120 $directory = "." unless -e $directory && -d $directory;
121 my $self = bless { _SA => $SA, _directory => $directory, _threads => $threads }, $package;
122 my $manifest = new WWW::Shopify::Tools::Themer::Manifest;
123 $self->manifest($manifest);
124 my $manifest_path = $directory . "/.shopmanifest";
125
126 $manifest->load($manifest_path) if -e $manifest_path;
127 $manifest->themer($self);
128 return $self;
129 }
130  
131 use IO::Handle;
132 STDERR->autoflush(1);
133 STDOUT->autoflush(1);
134  
135 sub directory { return $_[0]->{_directory}; }
136 sub threads { return $_[0]->{_threads}; }
137 sub log { print STDOUT $_[1]; }
138 sub manifest { if (defined $_[1]) { $_[0]->{_manifest} = $_[1]; $_[1]->themer($_[0]); } return $_[0]->{_manifest}; }
139 sub sa { return $_[0]->{_SA}; }
140 sub shop_url { return $_[0]->sa->shop_url; }
141 sub shop_url_truncated { my $url = $_[0]->shop_url; $url =~ s/\.myshopify.com//; return $url; }
142  
143 sub save_manifest {
144 my ($self) = @_;
145 my $manifest = $self->manifest;
146 $manifest->save($self->directory . "/.shopmanifest");
147 }
148  
149 =head1 transfer_progress($self, $type, $theme, $files_transferred, $files_remaining, $file)
150  
151 Called during theme pushes. Lets you easily log what's happening. Normally, simply makes formatted output to log.
152  
153 =cut
154  
155 sub transfer_progress {
156 my ($self, $type, $theme, $files_transferred, $files_total, $file) = @_;
157 my $action;
158 $action = "Pushing" if $type eq "push";
159 $action = "Pulling" if $type eq "pull";
160 $action = "Deleting" if $type eq "delete";
161 $self->log("[" . sprintf("%03.2f", ($files_transferred/$files_total)*100.0) . "%]" . ($theme->{name} ? " (" . $theme->{name} . ")" : '') . " $action $file...\n");
162 }
163  
164 =head1 read_exception
165  
166 Spits out a nice exception message from all the underlying exception types that may be thrown.
167  
168 =cut
169  
170 sub read_exception {
171 my ($self, $exception) = @_;
172 if (ref($exception) && ref($exception->error) eq "HTTP::Response") {
173 if ($exception->error->code == 500) {
174 return $exception->error->decoded_content;
175 }
176 else {
177 my $json = decode_json($exception->error->content);
178 return $json->{errors}->{asset}->[0];
179 }
180 }
181 elsif (ref($exception)) {
182 return $exception->error;
183 }
184 else {
185 return "$exception";
186 }
187 }
188  
189 =head1 get_themes
190  
191 get_themes returns an array of all the themes present in the shop, with the active theme first.
192  
193 =cut
194  
195 sub get_themes {
196 my ($self) = @_;
197 my @themes = $self->sa()->get_all('Theme');
198 $self->manifest->{themes} = [map { { name => $_->name, id => $_->id, role => $_->role } } @themes];
199 return @{$self->manifest->{themes}};
200 }
201  
202 =head1 pull_all
203  
204 pull_all essentially pulls all themes from the remote site. Gets all themes using the API, and then calls pull on each of them. Also pulls on pages.
205  
206 $STC = new WWW::Shopify::Tools::Themer($settings);
207 $STC->pull_all([$folder]);
208  
209 =cut
210  
211 sub pull_all {
212 my ($self) = @_;
213 $self->pull(new WWW::Shopify::Model::Theme($_)) for ($self->get_themes);
214 $self->pull_pages;
215 }
216  
217 =head1 pull_pages
218  
219 Pulls all pages from a store and dumps them into the working/specified folder, in a directory named pages.
220  
221 $STC->pull_pages([$folder]);
222  
223 Files that are locally and remotely changed will be overwritten locally, so keep an eye out for this.
224 Files that are locally not, and remotely chagned will be overritten locally.
225 Files that are not present locally and remotely present will be pulled.
226  
227 =cut
228  
229 sub pull_pages {
230 my ($self) = @_;
231 my $folder = $self->directory;
232 my $manifest = $self->manifest;
233 make_path("$folder/pages");
234 foreach my $page ($self->sa->get_all("Page")) {
235 my $path = "$folder/pages/" . $page->handle . ".html";
236 $manifest->remote($path, $page->updated_at);
237 next if !$manifest->has_remote_changes($path);
238 $manifest->local($path, $page->updated_at);
239 write_file($path, { binmode => "utf8" }, $page->body_html) or die $!;
240 $manifest->system($path, DateTime->from_epoch(epoch => stat($path)->mtime));
241 }
242 $self->save_manifest;
243 }
244  
245 =head1 pull
246  
247 Pulls all assets from a particular theme and then dumps them into the working/specified folder, in a directory named for the particular theme.
248  
249 my @themes = $sa->get_all('ShopifyAPI::Model::Theme');
250 $STC->pull($themes[2], [$folder]);
251  
252 Files that are locally and remotely changed will be overwritten locally, so keep an eye out for this.
253 Files that are locally not, and remotely chagned will be overritten locally.
254 Files that are not present locally and remotely present will be pulled.
255  
256 =cut
257  
258 sub pull {
259 # Get all assets.
260 my ($self, $theme) = @_;
261 my $folder = $self->directory;
262 my $manifest = $self->manifest();
263 my $truncated = $self->shop_url_truncated;
264 my $n = "$folder/$truncated-" . $theme->{id};
265 make_path($n); write_file("$n/.info", encode_json({ id => $theme->{id} }));
266 my @assets = $self->sa()->get_all('Asset', {parent => $theme});
267 # We do a threaded pull, because we can.
268 my @asset_ids:shared = (0 .. int(@assets)-1);
269  
270 my %present = map { "$n/" . $_->key => 1 } @assets;
271 my @files = $self->manifest->files;
272 # Check to see if the file is deleted on the server side. If so, then delete it on our side.
273 for (grep { !exists $present{$_} && $_ =~ m/$n/ } @files) {
274 delete $self->manifest->{files}->{$_};
275 unlink($_);
276 }
277  
278 for (my $c = 0; $c < $self->threads(); ++$c) {
279 #threads->create(sub {
280 while (int(@asset_ids) > 0) {
281 #lock(@asset_ids);
282 my $asset = $assets[pop(@asset_ids)];
283 #unlock(@asset_ids);
284 my $path = "$n/" . $asset->key();
285 my $datetime = $asset->updated_at();
286 $manifest->remote($path, $datetime);
287 make_path(dirname($path));
288 next if !$manifest->has_remote_changes($path);
289 $self->transfer_progress("pull", $theme, int(@assets) - int(@asset_ids), int(@assets), $asset->key);
290 $manifest->local($path, $datetime);
291 if (defined $asset->public_url()) {
292 my $value = get($asset->public_url());
293 $value = '' unless $value;
294 write_file($path, {binmode => 'raw'}, $value) or die $!;
295 } else {
296 # Assets which don't have a public url, we have to get individually.
297 my $full_asset = $self->sa()->get('Asset', $asset->key(), {parent => $theme});
298 my $value = $full_asset->value();
299 $value = '' unless $value;
300 write_file($path, {binmode => 'utf8'}, $value);
301 }
302 $manifest->system($path, DateTime->from_epoch(epoch => stat($path)->mtime));
303 }
304 #});
305 }
306 $self->save_manifest;
307 }
308  
309 =head1 push_all
310  
311 Pushes all assets from all themes, if they need to be pushed, as well as pages.
312  
313 =cut
314  
315 sub push_all {
316 my ($self) = @_;
317 $self->push(new WWW::Shopify::Model::Theme($_)) for (@{$self->manifest->{themes}});
318 $self->push_pages;
319 }
320  
321 =head1 push_pages
322  
323 Pushes all pages that need to be pushed.
324  
325 $STC->push_pages([$folder]);
326  
327 Files that are locally changed, and remotely not, will be pushed.
328 Files that are locally changed, and remotely changed, will not be pushed.
329 Files that are locally unchanged will only be pushed if the file is missing on the server.
330  
331 =cut
332  
333 use List::Util qw(first);
334 sub push_pages {
335 my ($self) = @_;
336 my $folder = $self->directory;
337 my $manifest = $self->manifest;
338  
339 my @remote_pages = $self->sa->get_all("Page");
340 $manifest->remote("$folder/pages/" . $_->handle . ".html", $_->updated_at) for (@remote_pages);
341  
342 my @pages = ();
343 my %present = ();
344 find({no_chdir => 1, wanted => sub {
345 my ($path, $name) = ($_, basename($_));
346 return if ($name =~ m/^\./) || -d $path || $name !~ m/\.html$/;
347 $present{$path} = 1;
348 return if !$manifest->has_local_changes($path);
349 die new WWW::Shopify::Exception("Unable to push to repo; there are remote changes on $path.") if $manifest->has_remote_changes($path);
350 push(@pages, $path);
351 }}, "$folder/pages/");
352 for (grep { !exists $present{"$folder/pages/" . $_->handle . ".html"} } @remote_pages) {
353 $self->transfer_progress("delete", undef, 0, 1, $_->handle);
354 $self->sa->delete($_);
355 }
356 foreach my $i (0..$#pages) {
357 my $path = $pages[$i];
358 die new WWW::Shopify::Exception("Can't determine handle.") unless $path =~ m/\/?([\w\-]+)\.html$/;
359 my $handle = $1;
360 $self->transfer_progress("push", undef, $i, int(@pages), $handle);
361 my $remote_page = first { $_->handle eq $handle } @remote_pages;
362 if ($remote_page) {
363 $remote_page->body_html(scalar(read_file($path, binmode => "utf8")));
364 $remote_page = $self->sa->update($remote_page);
365 }
366 else {
367 $remote_page = $self->sa->create(new WWW::Shopify::Model::Page({
368 body_html => scalar(read_file($path, binmode => "utf8")),
369 handle => $handle,
370 title => join(" ", map { ucfirst($_) } split(/-/, $handle))
371 }));
372 }
373 $manifest->system($path, DateTime->from_epoch(epoch => stat($path)->mtime));
374 $manifest->local($path, $remote_page->updated_at);
375 $manifest->remote($path, $remote_page->updated_at);
376 }
377 $self->save_manifest;
378 }
379  
380 =head1 push
381  
382 Pushes all assets from a particular theme that need to be pushed.
383  
384 $STC->push($theme, [$folder]);
385  
386 Files that are locally changed, and remotely not, will be pushed.
387 Files that are locally changed, and remotely changed, will not be pushed.
388 Files that are locally unchanged will only be pushed if the file is missing on the server.
389  
390 =cut
391  
392 sub push {
393 my ($self, $theme) = @_;
394 my $folder = $self->directory;
395 my $manifest = $self->manifest();
396 my $truncated = $self->sa->shop_url;
397 $truncated =~ s/\.myshopify.com//;
398 my $n = "$folder/$truncated-" . $theme->{id};
399  
400 my @remote_assets = $self->sa()->get_all('Asset', {parent => $theme});
401 $manifest->remote("$n/" . $_->key(), $_->updated_at) for (@remote_assets);
402  
403 my %present = ();
404  
405 my @assets = ();
406 find({no_chdir => 1, wanted => sub {
407 my ($path, $name) = ($_, basename($_));
408 return if ($name =~ m/^\./);
409 return if (-d $path);
410 $present{$path} = 1;
411 return if !$manifest->has_local_changes($path);
412 die new WWW::Shopify::Exception("Unable to push to repo; there are remote changes on $path.") if $manifest->has_remote_changes($path);
413 push(@assets, $path);
414 }}, $n);
415 for (grep { !exists $present{"$n/" . $_->key()} } @remote_assets) {
416 $self->transfer_progress("delete", $theme, 0, 1, $_->key);
417 $self->sa->delete($_);
418 }
419  
420 my @asset_ids:shared = (0 .. int(@assets)-1);
421 for (my $c = 0; $c < $self->threads(); ++$c) {
422 #threads->create(sub {
423 while (int(@asset_ids) > 0) {
424 #lock(@asset_ids);
425 my $path = $assets[pop(@asset_ids)];
426 #unlock(@asset_ids);
427 die $path unless $path =~ m/$n\/(.*?\.(\w+))$/;
428 my $asset_key = $1;
429 my $asset_extension = $2;
430 my $asset = new WWW::Shopify::Model::Asset({key => $asset_key, associated_parent => $theme});
431 if ($asset_extension eq "liquid" || $asset_extension eq "json" || $asset_extension eq "js" || $asset_extension eq "css") {
432 $asset->value(scalar(read_file($path, binmode => ":utf8")));
433 }
434 else {
435 $asset->attachment(encode_base64(scalar(read_file($path, binmode => "raw"))));
436 }
437 $self->transfer_progress("push", $theme, int(@assets) - int(@asset_ids), int(@assets), $asset->key);
438 $asset = $manifest->exists($path) ? $self->sa->update($asset) : $self->sa->create($asset);
439 $manifest->system($path, DateTime->from_epoch(epoch => stat($path)->mtime));
440 $manifest->local($path, $asset->updated_at);
441 $manifest->remote($path, $asset->updated_at);
442 }
443 #}
444 }
445 $self->save_manifest;
446 }
447  
448 =head1 activate
449  
450 Sets the sepecified theme as the main shopify theme.
451  
452 =cut
453  
454 sub activate {
455 my ($self, $theme) = @_;
456 $theme->role('main');
457 $theme = $self->sa->update($theme);
458 my $manifest = first { $_->{role} eq "main" } @{$self->manifest->{themes}};
459 $manifest->{role} = "unpublished";
460 $manifest = first { $_->{id} == $theme->id } @{$self->manifest->{themes}};
461 $manifest->{role} = $theme->role;
462 $manifest->{name} = $theme->name;
463 }
464  
465 1;
466  
467 =head1 SEE ALSO
468  
469 L<WWW::Shopify>, L<WWW::Shopify::Private>, L<WWW::Shopify::Model::Theme>, L<WWW::Shopify::Model::Asset>
470  
471 =head1 AUTHOR
472  
473 Adam Harrison (adamdharrison@gmail.com)
474  
475 =head1 LICENSE
476  
477 Copyright (C) 2013 Adam Harrison
478  
479 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
480  
481 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
482  
483 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
484  
485 =cut