blib/lib/CSS/Squish.pm

filter: Statementstmt 87.5% 133 / 152 Branchbran 75.9% 41 / 54 Conditioncond 50.0% 6 / 12 MC/DCmcdc 28.5% 2 / 7 Subroutinesub 88.2% 15 / 17 Podpod 100% 7 / 7 totaltotal 81.9% 204 / 249 CC 34 SCAR 19.6
CC
34
Cov
83%
_concatenate_to
15.4
new
6.0
resolve_uri
5.0
CRAP 7.1
↑ Summary
1 8 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 package CSS::Squish;
6  
7 8 $CSS::Squish::VERSION = '0.10';
8  
9 # Setting this to true will enable lots of debug logging about what
10 # CSS::Squish is doing
11 8 $CSS::Squish::DEBUG = 0;
12  
13 8 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 8 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 8 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 8 ▶use URI::file;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 =head1 NAME
19  
20 CSS::Squish - Compact many CSS files into one big file
21  
22 =head1 SYNOPSIS
23  
24 use CSS::Squish;
25 my $concatenated = CSS::Squish->concatenate(@files);
26  
27 my $squisher = CSS::Squish->new( roots => ['/root1', '/root2'] );
28 my $concatenated = $squisher->concatenate(@files);
29  
30 =head1 DESCRIPTION
31  
32 This module takes a list of CSS files and concatenates them, making sure
33 to honor any valid @import statements included in the files.
34  
35 The benefit of this is that you get to keep your CSS as individual files,
36 but can serve it to users in one big file, saving the overhead of possibly
37 dozens of HTTP requests.
38  
39 Following the CSS 2.1 spec, @import statements must be the first rules in
40 a CSS file. Media-specific @import statements will be honored by enclosing
41 the included file in an @media rule. This has the side effect of actually
42 I<improving> compatibility in Internet Explorer, which ignores
43 media-specific @import rules but understands @media rules.
44  
45 It is possible that future versions will include methods to compact
46 whitespace and other parts of the CSS itself, but this functionality
47 is not supported at the current time.
48  
49 =cut
50  
51 #
52 # This should be a decently close CSS 2.1 compliant parser for @import rules
53 #
54 # XXX TODO: This does NOT deal with comments at all at the moment. Which
55 # is sort of a problem.
56 #
57  
58 8 my @ROOTS = qw( );
59  
60 8 my @MEDIA_TYPES = qw(all aural braille embossed handheld print
61 projection screen tty tv);
62 8 my $MEDIA_TYPES = '(?:' . join('|', @MEDIA_TYPES) . ')';
63 8 my $MEDIA_LIST = qr/$MEDIA_TYPES(?:\s*,\s*$MEDIA_TYPES)*/;
64  
65 8 my $AT_IMPORT = qr/^\s* # leading whitespace
66 \@import\s+ # @import
67 (?:url\( # url(
68 \s* # optional whitespace
69 (?:"|')? # optional " or '
70 | # or
71 (?:"|')) # " or '
72 (.+?) # the filename
73 (?:(?:"|')? # optional " or '
74 \s* # optional whitespace
75 \) # )
76 | # or
77 (?:"|')) # " or '
78 (?:\s($MEDIA_LIST))? # the optional media list
79 \; # finishing semi-colon
80 \s*$ # trailing whitespace
81 /x;
82  
83 =head1 COMMON METHODS
84  
85 =head2 new( [roots=>[...]] )
86  
87 A constructor. For backward compatibility with versions prior to 0.06
88 you can still call everything as a class method, but should remember
89 that roots are shared between all callers in this case.
90  
91 if you're using persistent environment (like mod_perl) then it's very
92 recomended to use objects.
93  
94 =cut
95  
96 0 ▶sub new {
Subroutine new: not called CC=2 SCAR=17.9
Pod documented
97 0 my $proto = shift;
98 0 ▶ return bless {@_}, ref($proto) || $proto;
Condition0%0/3
ref $proto || $proto
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table0%0/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
99 }
100  
101 =head2 concatenate( @files )
102  
103 Takes a list of files to concatenate and returns the results as one big scalar.
104  
105 =head2 concatenate_to( $dest, @files )
106  
107 Takes a filehandle to print to and a list of files to concatenate.
108 C<concatenate> uses this method with an C<open>ed scalar.
109  
110 =cut
111  
112 7 ▶sub concatenate {
Subroutine concatenate: called CC=2 SCAR=7.0
Pod documented
113 7 my $self = shift;
114 7 my $string = '';
115
116 7 $self->_debug("Opening scalar as file");
117
118 7 ▶ open my $fh, '>', \$string or die "Can't open scalar as file! $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", \$string or die "Can't open scalar as file! $!" 7 0 7
119 7 $self->concatenate_to($fh, @_);
120  
121 7 $self->_debug("Closing scalar as file");
122 7 close $fh;
123  
124 7 return $string;
125 }
126  
127 7 ▶sub concatenate_to {
Subroutine concatenate_to: called CC=4 SCAR=14.7
Pod documented
128 7 my $self = shift;
129 7 my $dest = shift;
130  
131 7 $self->_debug("Looping over list of files: ", join(", ", @_), "\n");
132  
133 7 my %seen = ();
134 7 ▶ while ( my $file = shift @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $file = shift @_) 7 7 14
135  
136 7 ▶ next if $seen{ $file }{'all'}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$file}{"all"}++ 0 7 7
137  
138 7 my $fh = $self->file_handle( $file );
139 7 ▶ unless ( defined $fh ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $fh) 0 7 7
140 0 $self->_debug("Skipping '$file'...");
141 0 print $dest qq[/* WARNING: Unable to find/open file '$file' */\n];
142 0 next;
143 }
144 7 $self->_concatenate_to( $dest, $fh, $file, \%seen );
145 }
146 }
147  
148 21 ▶sub _concatenate_to {
Subroutine _concatenate_to: called CC=15 SCAR=27.3
149 21 my $self = shift;
150 21 my $dest = shift;
151 21 my $fh = shift;
152 21 my $file = shift;
153 21 ▶ my $seen = shift || {};
Condition50%1/2
shift() || {}
l!l
210
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
154  
155 21 ▶ while ( my $line = <$fh> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 46 0 46
156 46 ▶ if ( $line =~ /$AT_IMPORT/o ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /$AT_IMPORT/o) { } 18 28 46
157 18 my $import = $1;
158 18 my $media = $2;
159  
160 18 $self->_debug("Processing import '$import'");
161  
162 # resolve URI against the current file and get the file path
163 # which is always relative to our root(s)
164 18 my $path = $self->resolve_uri( $import, $file );
165 18 ▶ unless ( defined $path ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path) 1 17 18
166 1 $self->_debug("Skipping import because couldn't resolve URL");
167 1 print $dest $line;
168 1 next;
169 }
170  
171 17 ▶ if ( $seen->{ $path }{'all'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen->{$path}{"all"}) 1 16 17
172 1 $self->_debug("Skipping import as it was included for all media types");
173 1 print $dest "/** Skipping: \n", $line, " */\n\n";
174 1 next;
175 }
176  
177 16 ▶ if ( $media ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($media) 8 8 16
178 8 ▶ my @list = sort map lc, split /\s*,\s*/, ($media||'');
Condition50%1/2
$media || ''
l!l
80
MC/DC0%0/1
$media || ''
$media
Truth table50%1/2
A
A= $media
Aresult
11
00
179 8 ▶ if ( grep $_ eq 'all', @list ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep(($_ eq "all"), @list)) 0 8 8
180 0 @list = ();
181 }
182 8 $media = join ', ', @list;
183 }
184 16 ▶ if ( $seen->{ $path }{ $media || 'all' }++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen->{$path}{$media or "all"}++) 0 16 16
Condition100%2/2
$media || 'all'
l!l
88
MC/DC100%1/1
$media || 'all'
$media
Truth table100%2/2
A
A= $media
Aresult
11
00
185 0 $self->_debug("Skipping import as it's recursion");
186 0 print $dest "/** Skipping: \n", $line, " */\n\n";
187 0 next;
188 }
189  
190 # Look up the new file in root(s), so we can leave import
191 # if something is wrong
192 16 my $new_fh = $self->file_handle( $path );
193 16 ▶ unless ( defined $new_fh ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $new_fh) 2 14 16
194 2 $self->_debug("Skipping import of '$import'");
195  
196 2 print $dest qq[/* WARNING: Unable to find import '$import' */\n];
197 2 print $dest $line;
198 2 next;
199 }
200  
201 14 print $dest "\n/**\n * From $file: $line */\n\n";
202  
203 14 ▶ if ( defined $media ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $media) { } 6 8 14
204 6 print $dest "\@media $media {\n";
205 6 $self->_concatenate_to($dest, $new_fh, $path, $seen);
206 6 print $dest "}\n";
207 }
208 else {
209 8 $self->_concatenate_to($dest, $new_fh, $path, $seen);
210 }
211  
212 14 print $dest "\n/** End of $import */\n\n";
213 }
214 else {
215 28 print $dest $line;
216 28 ▶ last if not $line =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /^\s*$/ 21 7 28
217 }
218 }
219 21 $self->_debug("Printing the rest");
220 21 local $_;
221 21 ▶ print $dest $_ while <$fh>;
Branch: 1 branch
BranchTrueFalseTotal
defined($_ = readline $fh) and do { print $dest $_ } 12 21 33
222 21 close $fh;
223 }
224  
225 =head1 RESOLVING METHODS
226  
227 The following methods help map URIs to files and find them on the disk.
228  
229 In common situation you control CSS and can adopt it to use imports with
230 relative URIs and most probably only have to set root(s).
231  
232 However, you can subclass these methods to parse css files before submitting,
233 implement advanced mapping of URIs to file system and other things.
234  
235 Mapping works in the following way. When you call concatenate method we get
236 content of file using file_handle method which as well lookup files in roots.
237 If roots are not defined then files are treated as absolute paths or relative
238 to the current directory. Using of absolute paths is not recommended as
239 unhide server dirrectory layout to clients in css comments and as well don't
240 allow to handle @import commands with absolute URIs. When files is found we
241 parse its content for @import commands. On each URI we call resolve_uri method
242 that convert absolute and relative URIs into file paths.
243  
244 Here is example of processing:
245  
246 roots: /www/overlay/, /www/shared/
247  
248 $squisher->concatenate('/css/main.css');
249
250 ->file_handle('/css/main.css');
251 ->resolve_file('/css/main.css');
252 <- '/www/shared/css/main.css';
253 <- handle;
254  
255 content parsing
256 find '@import url(nav.css)'
257 -> resolve_uri('nav.css', '/css/main.css');
258 <- '/css/nav.css';
259 ... recursivly process file
260 find '@import url(/css/another.css)'
261 -> resolve_uri('/css/another.css', '/css/main.css');
262 <- '/css/another.css'
263 ...
264  
265 =head2 roots( @dirs )
266  
267 A getter/setter for paths to search when looking for files.
268  
269 The paths specified here are searched for files. This is useful if
270 your server has multiple document roots or document root doesn't match
271 the current dir.
272  
273 See also 'resolve_file' below.
274  
275 =cut
276  
277 24 ▶sub roots {
Subroutine roots: called CC=4 SCAR=15.8
Pod documented
278 24 my $self = shift;
279 24 my @res;
280 24 ▶ unless ( blessed $self ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($self)) { } 0 24 24
281 24 ▶ @ROOTS = @_ if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 23 24
282 24 @res = @ROOTS;
283 } else {
284 0 ▶ $self->{'roots'} = [ grep defined, @_ ] if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
285 0 @res = @{ $self->{'roots'} };
286 }
287 24 $self->_debug("Roots are: ". join ", ", map "'$_'", @res);
288 24 return @res;
289 }
290  
291 =head2 file_handle( $file )
292  
293 Takes a path to a file, resolves (see resolve_file) it and returns a handle.
294  
295 Returns undef if file couldn't be resolved or it's impossible to open file.
296  
297 You can subclass it to filter content, process it with templating system or
298 generate it on the fly:
299  
300 package My::CSS::Squish;
301 use base qw(CSS::Squish);
302  
303 sub file_handle {
304 my $self = shift;
305 my $file = shift;
306
307 my $content = $self->my_prepare_content($file);
308 return undef unless defined $content;
309  
310 open my $fh, "<", \$content or warn "Couldn't open handle: $!";
311 return $fh;
312 }
313  
314 B<Note> that the file is not resolved yet and is relative to the root(s), so
315 you have to resolve it yourself or call resolve_file method.
316  
317 =cut
318  
319 23 ▶sub file_handle {
Subroutine file_handle: called CC=3 SCAR=11.2
Pod documented
320 23 my $self = shift;
321 23 my $file = shift;
322  
323 23 my $path = $self->resolve_file( $file );
324 23 ▶ unless ( defined $path ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path) 2 21 23
325 2 $self->_debug("Couldn't find '$file' in root(s)");
326 2 return undef;
327 }
328  
329 21 my $fh;
330 21 ▶ unless ( open $fh, '<', $path ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $fh, "<", $path) 0 21 21
331 0 $self->_debug("Skipping '$file' ($path) due to error: $!");
332 0 return undef;
333 }
334 21 return $fh;
335 }
336  
337 =head2 resolve_file( $file )
338  
339 Lookup file in the root(s) and returns first path it found or undef.
340  
341 When roots are not set just checks if file exists.
342  
343 =cut
344  
345 23 ▶sub resolve_file {
Subroutine resolve_file: called CC=5 SCAR=16.1
Pod documented
346 23 my $self = shift;
347 23 my $file = shift;
348  
349 23 $self->_debug("Looking for '$file'");
350 23 my @roots = $self->roots;
351 23 ▶ unless ( @roots ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@roots) 19 4 23
352 19 ▶ return undef unless -e $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $file 2 17 19
353 17 return $file;
354 }
355  
356 4 foreach my $root ( @roots ) {
357 9 $self->_debug("Searching in '$root'");
358 9 my @spec = File::Spec->splitpath( $root, 1 );
359 9 my $path = File::Spec->catpath( @spec[0,1], $file );
360  
361 9 ▶ return $path if -e $path;
Branch: 1 branch
BranchTrueFalseTotal
if -e $path 4 5 9
362 }
363 0 return undef;
364 }
365  
366 =head2 _resolve_file( $file, @roots )
367  
368 DEPRECATED. This private method is deprecated and do nothing useful except
369 maintaining backwards compatibility. If you were using it then most probably
370 to find files in roots before submitting them into concatenate method. Now,
371 it's not required and this method returns back file path without changes.
372  
373 =cut
374  
375 0 ▶sub _resolve_file {
Subroutine _resolve_file: not called CC=1 SCAR=6.9
376 0 my ($self, $file, @roots) = @_;
377 0 require Carp;
378 0 Carp::carp("You called ->_resolve_file($file, ...). The method is deprecated!");
379 0 return $file;
380 }
381  
382 =head2 resolve_uri( $uri_string, $base_file )
383  
384 Takes an URI and base file path and transforms it into new
385 file path.
386  
387 =cut
388  
389 18 ▶sub resolve_uri {
Subroutine resolve_uri: called CC=5 SCAR=16.2
Pod documented
390 18 my $self = shift;
391 18 my $uri_str = shift;
392 18 my $base_file = shift;
393  
394 18 my $uri = URI->new( $uri_str, 'http' );
395  
396 18 ▶ if ( defined $uri->scheme || defined $uri->authority ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $uri->scheme or defined $uri->authority) 1 17 18
Condition66%2/3
defined $uri->scheme or defined $uri->authority
l!l&&r!l&&!r
1017
MC/DC50%1/2
defined $uri->scheme or defined $uri->authority
defined $uri->scheme defined $uri->authority
Truth table66%2/3
A or B
A= defined $uri->schemeB= defined $uri->authority
ABresult
1X1
011
000
397 1 $self->_debug("Skipping uri because it's external");
398 1 return undef;
399 }
400  
401 17 my $strip_leading_slash = 0;
402 17 ▶ unless ( $base_file =~ m{^/} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($base_file =~ m[^/]) 17 0 17
403 17 $base_file = '/'. $base_file;
404 17 $strip_leading_slash = 1;
405 }
406 17 my $base_uri = URI::file->new( $base_file );
407  
408 17 my $path = $uri->abs( $base_uri )->path;
409 17 ▶ $path =~ s{^/}{} if $strip_leading_slash;
Branch: 1 branch
BranchTrueFalseTotal
if $strip_leading_slash 17 0 17
410 17 return $path;
411 }
412  
413 123 ▶sub _debug {
Subroutine _debug: called CC=2 SCAR=7.2
414 123 my $self = shift;
415 123 ▶ warn( ( caller(1) )[3], ": ", @_, "\n") if $CSS::Squish::DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $CSS::Squish::DEBUG 0 123 123
416 }
417  
418 =head1 BUGS AND SHORTCOMINGS
419  
420 At the current time, comments are not skipped. This means comments happening
421 before @import statements at the top of a file will cause the @import rules
422 to not be parsed. Make sure the @import rules are the very first thing in
423 the file (and only one per line). Processing of @import rules stops as soon
424 as the first line that doesn't match an @import rule is encountered.
425  
426 All other bugs should be reported via
427 L<http://rt.cpan.org/Public/Dist/Display.html?Name=CSS-Squish>
428 or L<bug-CSS-Squish@rt.cpan.org>.
429  
430 =head1 AUTHOR
431  
432 Thomas Sibley <trs@bestpractical.com>, Ruslan Zakirov <ruz@bestpractical.com>
433  
434 =head1 COPYRIGHT AND LICENSE
435  
436 Copyright (c) 2006.
437  
438 This library is free software; you can redistribute it and/or modify
439 it under the same terms as Perl itself, either Perl version 5.8.3 or,
440 at your option, any later version of Perl 5 you may have available.
441  
442 =cut
443  
444 8 1;
445  
↑ Summary