lib/WWW/Shopify/Liquid/Precompiler.pm untested

filter: Statementstmt 0.0% 0 / 80 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 150 CC 15 SCAR 32.8
CC
15
Cov
0%
should_compile
72.0
compile_directories
30.0
new
12.0
CRAP 26.6
1 =head1
2  
3 WWW::Shopify:::Liquid::Precompiler - Tool to automatically compile .liquid files, which have multiple extensions.
4  
5 =cut
6  
7 package WWW::Shopify::Liquid::Precompiler;
8 use File::Find;
9 use File::stat;
10 use File::Slurp;
11 use File::Basename;
12 use Encode;
13  
14 use strict;
15 use warnings;
16  
17 use WWW::Shopify::Liquid::Analyzer;
18  
19 sub new {
20 my $package = shift;
21 my ($self) = bless {
22 options => {},
23 analyzer => undef,
24 entities => {},
25 liquid => undef,
26 @_
27 }, $package;
28 $self->{liquid} = WWW::Shopify::Liquid->new if !$self->liquid;
29 $self->{analyzer} = WWW::Shopify::Liquid::Analyzer->new(liquid => $self->liquid) if !$self->analyzer;
30 return $self;
31 }
32 sub liquid { return $_[0]->{liquid}; }
33 sub analyzer { return $_[0]->{analyzer}; }
34
35 # Destination can be a folder, or a filename.
36 sub should_compile {
37 my ($self, $target, $destination) = @_;
38 return 0 if -d $target;
39 return 0 unless $target =~ m/^(.*?[^\/]+\.[^\/]+)\.liquid$/ && -e $target;
40 my $file;
41 if ($destination) {
42 $file = -d $destination ? $destination . "/" . basename($1) : $file;
43 } else {
44 $file = $1;
45 }
46 return $file if !-e $file;
47 my $mtime = stat($target)->mtime;
48 return $file if stat($file)->mtime < $mtime;
49 my $entity = $self->analyzer->add_refresh_path($target, values(%{$self->{entities}}));
50 $self->{entities}->{$entity->id} = $entity;
51 return $file if int(grep { $_->file && $mtime < stat($_->file)->mtime } (@{$entity->{full_dependencies}})) > 0;
52 return 0;
53 }
54  
55 sub options {
56 my ($self, $target) = @_;
57 return $_[0]->{options};
58 }
59  
60 sub compile {
61 my ($self, $file, $target) = @_;
62 my $text = $self->{liquid}->render_file($self->options($file), $file);
63 write_file($target, encode("UTF-8", $text));
64 return $target;
65 }
66  
67 sub compile_directories {
68 my ($self, @directories) = @_;
69 find({
70 wanted => sub {
71 my $file = $_;
72 if (my $target = $self->should_compile($file)) {
73 eval { $self->compile($file, $target); };
74 if (my $exp = $@) {
75 die new WWW::Shopify::Liquid::Exception("Can't target.") unless $file =~ m/^(.*?[^\/]+\.[^\/]+)\.liquid$/ && -e $file;
76 my $target = $1;
77 if (!-e $target) {
78 open(my $fh, ">>", $target) or die $!; close($fh);
79 } else {
80 utime(undef, undef, $target);
81 }
82 die $exp;
83 }
84 }
85 }, no_chdir => 1
86 }, @directories)
87 }
88  
89 sub watch_directories {
90 my ($self, @directories) = @_;
91 while (1) {
92 eval {
93 $self->compile_directories(@directories);
94 };
95 if (my $exp = $@) {
96 print STDERR "Error compiling: " . $exp->error . "\n";
97 }
98 sleep(1);
99 }
100 }
101  
102 1;