Controller/AutoAssets/Handler/Directory.pm

filter: Statementstmt 81.4% 105 / 129 Branchbran 38.8% 14 / 36 Conditioncond 33.3% 3 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 89.6% 26 / 29 Podpod 0.0% 0 / 7 totaltotal 68.5% 148 / 216 CC 25 SCAR 26.0
CC
25
Cov
70%
html_head_tags
72.0
_subfile_mtime_verify
7.0
_resolve_subfile_content_type
6.0
CRAP 13.5
↑ Summary Plugin/AutoAssets.pm »
1 package Catalyst::Controller::AutoAssets::Handler::Directory;
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # VERSION
6  
7 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 with 'Catalyst::Controller::AutoAssets::Handler';
11  
12 1 ▶use Path::Class 0.32 qw( dir file );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use MIME::Types;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15  
16 1 ▶sub BUILD {
Subroutine BUILD: called CC=1 SCAR=0.0
17 1 my $self = shift;
18
19 # init dir_root:
20 1 $self->dir_root;
21 }
22  
23 3 ▶sub asset_request {
Subroutine asset_request: called CC=4 SCAR=14.8
Pod undocumented
24 3 my ( $self, $c, $sha1, @args ) = @_;
25
26 # Only subfiles are valid with Directory assets:
27 3 ▶ return $self->unknown_asset($c) unless (scalar @args > 0);
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @args > 0 0 3 3
28
29 3 my $path = join('/',@args);
30 3 $self->prepare_asset($path);
31  
32 return $self->unknown_asset($c) unless (
33 $sha1 eq $self->asset_name
34 3 ▶ && exists $self->subfile_meta->{$path}
Branch: 1 branch
BranchTrueFalseTotal
unless $sha1 eq $self->asset_name and exists $self->subfile_meta->{$path} 0 3 3
Condition33%1/3
$sha1 eq $self->asset_name and exists $self->subfile_meta->{$path}
!ll&&!rl&&r
003
MC/DC0%0/2
$sha1 eq $self->asset_name and exists $self->subfile_meta->{$path}
$sha1 eq $self->asset_name exists $self->subfile_meta->{$path}
Truth table33%1/3
A and B
A= $sha1 eq $self->asset_nameB= exists $self->subfile_meta->{$path}
ABresult
0X0
100
111
35 );
36  
37 3 my $meta = $self->subfile_meta->{$path};
38 3 return $self->_set_file_response($c,$meta->{file},$meta->{content_type});
39 }
40  
41 3 ▶sub _set_file_response {
Subroutine _set_file_response: called CC=1 SCAR=0.0
42 3 my ($self, $c, $file, $content_type) = @_;
43
44 3 $c->response->header(
45 'Content-Type' => $content_type,
46 'Cache-Control' => $self->cache_control_header
47 );
48  
49 3 my $f= $file->openr;
50 3 binmode $f;
51 3 return $c->response->body( $f );
52 }
53  
54  
55 0 ▶sub _resolve_subfile_content_type {
Subroutine _resolve_subfile_content_type: not called CC=2 SCAR=17.9
56 0 my $self = shift;
57 0 my $File = shift;
58 my $content_type = $self->subfile_meta->{$File}->{content_type}
59 0 ▶ or die "content_type not found in subfile_meta for $File!";
Branch: 1 branch
BranchTrueFalseTotal
my $content_type = $self->subfile_meta->{$File}{"content_type"} or die "content_type not found in subfile_meta for $File!" 0 0 0
60 0 return $content_type;
61 }
62  
63 # CodeRef used to determine the Content-Type of each 'directory' subfile
64 1 ▶has 'content_type_resolver', is => 'ro', isa => 'CodeRef', default => sub{ \&_ext_to_type };
Subroutine __ANON__: called CC=1 SCAR=0.0
65  
66 1 ▶has 'MimeTypes', is => 'ro', isa => 'MIME::Types', lazy => 1, default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
67 1 my $self = shift;
68 1 return MIME::Types->new( only_complete => 1 );
69 1 };
70  
71 # looks up the correct MIME type for the current file extension
72 # (adapted from Static::Simple)
73 5 ▶sub _ext_to_type {
Subroutine _ext_to_type: called CC=4 SCAR=15.2
74 5 my ( $self, $full_path ) = @_;
75 5 my $c = $self->_app;
76  
77 5 ▶ if ( $full_path =~ /.*\.(\S{1,})$/xms ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($full_path =~ /.*\.(\S{1,})$/msx) { } 5 0 5
78 5 my $ext = $1;
79 5 my $type = $self->MimeTypes->mimeTypeOf( $ext );
80 5 ▶ if ( $type ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type) { } 5 0 5
81 5 ▶ return ( ref $type ) ? $type->type : $type;
Branch: 1 branch
BranchTrueFalseTotal
ref $type ? : 5 0 5
82 }
83 else {
84 0 return 'text/plain';
85 }
86 }
87 else {
88 0 return 'text/plain';
89 }
90 }
91  
92 # subfile_meta applies only to 'directory' assets. It is a cache of mtimes of
93 # individual files within the directory since 'inc_mtimes' only conatins the top
94 # directory. This is used to check for mtime changes on individual subfiles when
95 # they are requested. This is for performance since it would be too expensive to
96 # attempt to check all the mtimes on every request
97 1 ▶has 'subfile_meta', is => 'rw', isa => 'HashRef', default => sub {{}};
Subroutine __ANON__: called CC=1 SCAR=0.0
98 1 ▶sub set_subfile_meta {
Subroutine set_subfile_meta: called CC=1 SCAR=0.0
Pod undocumented
99 1 my $self = shift;
100 1 my $list = shift;
101 $self->subfile_meta({
102 1 map { join('/', grep { $_ ne '.' } $_->relative($self->dir_root)->components) => {
103 file => $_,
104 mtime => $_->stat->mtime,
105 content_type => $self->content_type_resolver->($self,$_)
106 } } @$list
107 });
108 }
109  
110 1 ▶has '_persist_attrs', is => 'ro', isa => 'ArrayRef', default => sub{[qw(
Subroutine __ANON__: called CC=1 SCAR=0.0
111 built_mtime
112 inc_mtimes
113 last_fingerprint_calculated
114 subfile_meta
115 _excluded_paths
116 1 )]};
117  
118  
119 1 ▶has 'dir_root', is => 'ro', isa => 'Path::Class::Dir', lazy => 1, default => sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
120 1 my $self = shift;
121  
122 die "'directory' assets must have exactly one include path"
123 1 ▶ unless (scalar @{$self->includes} == 1);
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @{$self->includes;} == 1 0 1 1
124  
125 1 my $dir = $self->includes->[0]->absolute;
126 1 ▶ die "include path '$dir' is not a directory" unless (-d $dir);
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 1 1
127  
128 1 return $dir;
129 1 };
130  
131 8 ▶sub _subfile_mtime_verify {
Subroutine _subfile_mtime_verify: called CC=5 SCAR=19.4
132 8 my ($self, $path) = @_;
133 8 my $File = $self->dir_root->file($path);
134
135 # If the file doesn't exist on disk or is in the excluded paths there
136 # is no need to clear the asset. We already know it will return a 404
137 8 ▶ return if ($self->_excluded_paths->{$path} || ! -f $File);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_excluded_paths->{$path} or not -f $File 0 8 8
Condition33%1/3
$self->_excluded_paths->{$path} or not -f $File
l!l&&r!l&&!r
008
MC/DC0%0/2
$self->_excluded_paths->{$path} or not -f $File
$self->_excluded_paths->{$path} not -f $File
Truth table33%1/3
A or not(B)
A= $self->_excluded_paths->{$path}B= not -f $File
ABresult
1X1
011
000
138  
139 # Check the mtime of the requested file to see if it has changed
140 # and force a rebuild if it has. This is done because it is too
141 # expensive to check all the subfile mtimes on every request, and
142 # changes within files would not otherwise be caught since file
143 # content changes do not update the parent directory mtime
144 $self->clear_asset unless (
145 exists $self->subfile_meta->{$path} &&
146 $File->stat->mtime eq $self->subfile_meta->{$path}->{mtime}
147 8 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->subfile_meta->{$path} and $File->stat->mtime eq $self->subfile_meta->{$path}{"mtime"} 0 8 8
Condition33%1/3
exists $self->subfile_meta->{$path} and $File->stat->mtime eq $self->subfile_meta->{$path}{"mtime"}
!ll&&!rl&&r
008
MC/DC0%0/2
exists $self->subfile_meta->{$path} and $File->stat->mtime eq $self->subfile_meta->{$path}{"mtime"}
exists $self->subfile_meta->{$path} $File->stat->mtime eq $self->subfile_meta->{$path}{"mtime"}
Truth table33%1/3
A and B
A= exists $self->subfile_meta->{$path}B= $File->stat->mtime eq $self->subfile_meta->{$path}{"mtime"}
ABresult
0X0
100
111
148 }
149  
150 # Provides a mechanism for preparing a set of subfiles all at once. This
151 # is a critical pre-step whenever multiple subfiles are being used together
152 # because if any have changed the asset path for *all* will be updated as
153 # soon as the changed file is detected. If this happens halfway through the list,
154 # the asset path of earlier processed items will retroactively change.
155 0 ▶sub prepare_asset_subfiles {
Subroutine prepare_asset_subfiles: not called CC=2 SCAR=17.9
Pod undocumented
156 0 my ($self, @files) = @_;
157 0 $self->_subfile_mtime_verify($_) for (@files);
158 0 $self->prepare_asset;
159 }
160  
161 5 ▶around asset_path => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
162 5 my ($orig, $self, @subpath) = @_;
163
164 5 my $base = $self->$orig(@subpath);
165 5 ▶ return $base unless (scalar @subpath > 0);
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @subpath > 0 3 2 5
166  
167 2 my $File = $self->dir_root->file(@subpath);
168 2 ▶ Catalyst::Exception->throw("sub file $File not found") unless (-f $File);
Branch: 1 branch
BranchTrueFalseTotal
unless -f $File 0 2 2
169  
170 2 return join('/',$base,@subpath);
171 1 };
172  
173 12 ▶sub before_prepare_asset {
Subroutine before_prepare_asset: called CC=2 SCAR=6.9
Pod undocumented
174 12 my ($self, @args) = @_;
175 12 my $path = join('/',@args);
176
177 # Special code path: if this is associated with a sub file request
178 # in a 'directory' type asset, clear the asset to force a rebuild
179 # below if the *subfile* mtime has changed
180 12 ▶ $self->_subfile_mtime_verify($path) if (scalar @args > 0);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @args > 0 8 4 12
181 }
182  
183 12 ▶sub get_prepare_data {
Subroutine get_prepare_data: called CC=1 SCAR=0.0
Pod undocumented
184 12 my $self = shift;
185
186 # For 'directory' only consider the mtime of the top directory and don't
187 # read in all the files (yet... we will read them in only if we need to rebuild)
188 # WARNING: this means that changes *within* sub files will not be detected here
189 # because that doesn't update the directory mtime; only filename changes will be seen.
190 # Update: That is what _subfile_mtime_verify above is for... to inexpensively catch
191 # this case for individual sub files
192 12 my $files = $self->includes;
193 12 my $inc_mtimes = $self->get_inc_mtime_concat($files);
194 12 my $built_mtime = $self->get_built_mtime;
195
196 return {
197 12 files => $files,
198 inc_mtimes => $inc_mtimes,
199 built_mtime => $built_mtime
200 };
201 }
202  
203 1 ▶around build_asset => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
204 1 my ($orig, $self, $d) = @_;
205
206 # Get the real list of files that we put off in get_prepare_data()
207 1 $d->{files} = $self->get_include_files;
208  
209 # update the mtime cache of all directory subfiles
210 1 $self->set_subfile_meta($d->{files});
211  
212 1 return $self->$orig($d);
213 1 };
214  
215 # Keep track of excluded files so we can return a 404 without rebuilding
216 # the asset
217 1 ▶has '_excluded_paths', is => 'rw', isa => 'HashRef', default => sub {{}};
Subroutine __ANON__: called CC=1 SCAR=0.0
218 1 ▶sub _record_excluded_files {
Subroutine _record_excluded_files: called CC=1 SCAR=0.0
219 1 my ($self, $files) = @_;
220 1 my @relative = map { join('/', grep { $_ ne '.' } file($_)->relative($self->dir_root)->components) } @$files;
221 1 my %hash = map { $_ => 1 } map { "$_" } @relative;
222 1 $self->_excluded_paths(\%hash);
223 }
224  
225 1 ▶sub write_built_file {
Subroutine write_built_file: called CC=1 SCAR=0.0
Pod undocumented
226 1 my ($self, $fd, $files) = @_;
227 # The built file is just a placeholder in the case of 'directory' type
228 # asset whose data is served from the original files
229 1 my @relative = map { join('/', grep { $_ ne '.' } file($_)->relative($self->dir_root)->components) } @$files;
230 1 $fd->write(join("\r\n",@relative) . "\r\n");
231 }
232  
233  
234 # These apply only to 'directory' asset type
235 1 ▶has 'html_head_css_subfiles', is => 'ro', isa => 'ArrayRef', default => sub {[]};
Subroutine __ANON__: called CC=1 SCAR=0.0
236 1 ▶has 'html_head_js_subfiles', is => 'ro', isa => 'ArrayRef', default => sub {[]};
Subroutine __ANON__: called CC=1 SCAR=0.0
237  
238 # --------------------
239 # html_head_tags()
240 #
241 # Convenience method to generate a set of CSS <link> and JS <script> tags
242 # suitable to drop into the <head> section of an HTML document.
243 #
244 # For 'css' and 'js' assets this will be a single tag pointing at the current
245 # valid asset path. For 'directory' asset types this will be a listing of
246 # css and/or js tags pointing at subfile asset paths supplied in the attrs:
247 # 'html_head_css_subfiles' and 'html_head_js_subfiles', or, supplied in a
248 # hash(ref) argument with 'css' and/or 'js' keys and arrayref values.
249 #
250 # ### More about the 'directory' asset type:
251 #
252 # This could be considered a violation of separation of concerns, but the main
253 # reason this method is provided at all, besides the fact that it is a common
254 # use case, is that it handles the preprocessing required to ensure the dir asset
255 # is in an atomic/consistent state by calling prepare_asset_subfiles() on all
256 # supplied subfiles as a group to catch any content changes before rendering/returning
257 # the active asset paths. This is something that users might not realize they
258 # need to do if they don't read the docs closely. So, it is a common use case
259 # and this provides a simple and easy to understand interface that spares the user
260 # from needing to know about details they might not want to know about. It's
261 # practical/useful, self-documenting, and doesn't have to be used...
262 #
263 # The only actual "risk" if this the preprocessing step is missed, and the user builds
264 # head tags themselves with multiple calls to asset_path('path/to/subfile') [such as in
265 # a TT file] is that during a request where the content of one of the subfiles has changed,
266 # the asset paths of all the subfiles processed/returned prior to hitting the changed file
267 # will already be invalid (retroactively) because the sha1 will have changed. This is
268 # because the sha1/fingerprint is based on the asset as *whole*, and for performance, subfile
269 # content changes are not detected until they are accessed. This is only an issue when the
270 # content changes *in-place*, which shouldn't happen in a production environment. And, it
271 # only effects the first request immediately after the change. This issue can also be avoided
272 # altogether by using static 'current' alias redirect URLs instead off calling asset_path(),
273 # but this is *slightly* less efficient, as discussed in the documentation.
274 #
275 # This long-winded explanation is more about documenting/explaining the internal design
276 # for development purposes (and to be a reminder for me) than it is anything else. Also,
277 # it is intentionally in a comment rather than the POD for the sake of avoiding information
278 # overload since from the user perspective this is barely an issue (but very useful for
279 # developers who need to understand the internals of this module)
280 #
281 # Note: This has nothing to do with 'css' or 'js' asset types which are always atomic
282 # (because they are single files and have no "subfiles"). This *only* applies to
283 # the 'directory' asset type
284 #
285 0 ▶sub html_head_tags {
Subroutine html_head_tags: not called CC=8 SCAR=42.8
Pod undocumented
286 0 my ($self, @args) = @_;
287  
288 # get the files from either supplied arguments or defaults in object attrs:
289 my %cnf = scalar @args > 0
290 0 ▶ ? ( (ref($args[0]) eq 'HASH') ? %{ $args[0] } : @args ) # <-- arg as hash or hashref
Branch: 2 branches
BranchTrueFalseTotal
scalar @args > 0 ? : 0 0 0
ref $args[0] eq 'HASH' ? : 0 0 0
291 : ( css => $self->html_head_css_subfiles, js => $self->html_head_js_subfiles );
292
293 # note that we're totally trusting the caller to know that these files are
294 # in fact js/css files. We're just generating the correct tags for each type
295 0 ▶ my @css = $cnf{css} ? @{$cnf{css}} : ();
Branch: 1 branch
BranchTrueFalseTotal
$cnf{'css'} ? : 0 0 0
296 0 ▶ my @js = $cnf{js} ? @{$cnf{js}} : ();
Branch: 1 branch
BranchTrueFalseTotal
$cnf{'js'} ? : 0 0 0
297  
298 # This is the line that ensures any content changes are detected before we start
299 # building the tags/urls:
300 0 $self->prepare_asset_subfiles(@css,@js);
301  
302 # This spares repeating the stat/mtime calls by asset_path() below.
303 # Maybe overkill, but every little bit of performance helps (and I'm OCD)...
304 0 $self->_asset_path_skip_prepare(1);
305
306 0 my @tags = ();
307
308 push @tags, '<link rel="stylesheet" type="text/css" href="' .
309 0 $self->asset_path($_) . '" />' for (@css);
310  
311 push @tags, '<script type="text/javascript" src="' .
312 0 $self->asset_path($_) . '"></script>' for (@js);
313  
314 # FIXME: shame on me
315 0 $self->_asset_path_skip_prepare(0);
316
317 0 ▶ my $html =
Branch: 1 branch
BranchTrueFalseTotal
scalar @tags > 0 ? : 0 0 0
318 "<!-- AUTO GENERATED BY " . ref($self->Controller) . " (/" .
319 $self->action_namespace($self->_app) . ") -->\r\n" .
320 ( scalar @tags > 0 ?
321 join("\r\n",@tags) : '<!-- NO ASSETS AVAILABLE -->'
322 ) .
323 "\r\n<!-- ---- END AUTO GENERATED ASSETS ---- -->\r\n";
324  
325 0 return $html;
326 }
327 # --------------------
328  
329 1 1;
330  
331 __END__
↑ Summary Plugin/AutoAssets.pm »