lib/App/Dapper/Utils.pm

filter: Statementstmt 100% 170 / 170 Branchbran 93.1% 82 / 88 Conditioncond 83.3% 10 / 12 MC/DCmcdc 75.0% 6 / 8 Subroutinesub 100% 33 / 33 Podpod 100% 15 / 15 totaltotal 96.9% 316 / 326 CC 49 SCAR 15.0
CC
49
Cov
97%
parse_date
10.0
__ANON__
8.1
split_frontmatter
6.0
CRAP 4.5
« lib/App/Dapper/Init.pm ↑ Summary bin/dapper »
1 package App::Dapper::Utils;
2  
3 =encoding utf8
4  
5 =head1 NAME
6  
7 App::Dapper::Utils - Common utility functions used throughout Dapper.
8  
9 =cut
10  
11 191 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 191 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 191 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 191 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 191 ▶use POSIX;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 191 ▶use Unicode::Normalize;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 191 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 191 ▶use File::Spec::Functions qw/ canonpath catfile /;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 191 ▶use File::Path qw/ make_path /;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 191 ▶use File::Basename qw/ dirname /;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 191 ▶use File::Copy ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 191 ▶use File::Find ();
Subroutine BEGIN: called CC=1 SCAR=0.0
24 191 ▶use Cwd qw/ abs_path /;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 191 ▶use YAML::PP qw/ Load /;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 191 ▶use DateTime::Format::XSD;
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 # Set to a true value to stop create_file printing what it creates
29 191 our $QUIET = 0;
30  
31 =head2 read_file
32  
33 Read a file and return a scalar with the file's contents, decoded as UTF-8.
34  
35 =cut
36  
37 44 ▶sub read_file {
Subroutine read_file: called CC=4 SCAR=14.0
Pod documented
38 44 my ($file_name) = @_;
39  
40 44 ▶ open(my $fh, "<:encoding(UTF-8)", $file_name)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:encoding(UTF-8)", $file_name or die qq[error: could not open "$file_name": $!\n] 43 1 44
41 or die "error: could not open \"$file_name\": $!\n";
42 43 my $file_contents = do { local $/; <$fh> };
43 43 ▶ close($fh) or die "error: could not close \"$file_name\": $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die qq[error: could not close "$file_name": $!\n] 43 0 43
44  
45 43 ▶ return defined $file_contents ? $file_contents : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $file_contents ? : 43 0 43
46 }
47  
48 =head2 write_file
49  
50 Takes a file name and a string, creates any missing parent directories, and
51 writes the string to the file encoded as UTF-8.
52  
53 =cut
54  
55 61 ▶sub write_file {
Subroutine write_file: called CC=5 SCAR=16.2
Pod documented
56 61 my ($file_name, $content) = @_;
57  
58 61 my $dir = dirname($file_name);
59 61 ▶ make_path($dir) unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 28 33 61
60  
61 60 ▶ open(my $fh, ">:encoding(UTF-8)", $file_name)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:encoding(UTF-8)", $file_name or die qq[error: could not open "$file_name" for writing: $!\n] 59 1 60
62 or die "error: could not open \"$file_name\" for writing: $!\n";
63 59 ▶ print $fh $content or die "error: could not write to \"$file_name\": $!\n";
Branch: 1 branch
BranchTrueFalseTotal
print $fh $content or die qq[error: could not write to "$file_name": $!\n] 59 0 59
64 59 ▶ close($fh) or die "error: could not close \"$file_name\": $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die qq[error: could not close "$file_name": $!\n] 59 0 59
65 }
66  
67 =head2 has_frontmatter
68  
69 Takes a file name and returns true if the file begins with a YAML front matter
70 delimiter (C<--->). Only the first few bytes are read, so this is safe to call
71 on binary files.
72  
73 =cut
74  
75 18 ▶sub has_frontmatter {
Subroutine has_frontmatter: called CC=4 SCAR=13.9
Pod documented
76 18 my ($file_name) = @_;
77  
78 18 ▶ open(my $fh, "<:raw", $file_name)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file_name or die qq[error: could not open "$file_name": $!\n] 17 1 18
79 or die "error: could not open \"$file_name\": $!\n";
80 17 my $read = read($fh, my $head, 64);
81 17 close($fh);
82  
83 17 ▶ return 0 unless $read;
Branch: 1 branch
BranchTrueFalseTotal
unless $read 1 16 17
84 16 ▶ return $head =~ /\A(?:\xEF\xBB\xBF)?---[ \t]*(?:\r?\n|\z)/ ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$head =~ /\A(?:\xEF\xBB\xBF)?---[ \t]*(?:\r?\n|\z)/ ? : 9 7 16
85 }
86  
87 =head2 split_frontmatter
88  
89 Takes a string (and a name used in error messages) and splits it into its YAML
90 front matter and its body. The front matter must start on the first line and
91 be closed by a line containing only C<--->. Returns a list of the parsed front
92 matter (a hash reference) and the body, or an empty list if the string does
93 not start with front matter.
94  
95 =cut
96  
97 25 ▶sub split_frontmatter {
Subroutine split_frontmatter: called CC=6 SCAR=17.9
Pod documented
98 25 my ($text, $name) = @_;
99  
100 25 ▶ return unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 1 24 25
101 24 ▶ return unless $text =~ /\A\x{FEFF}?---[ \t]*\r?\n(.*?)^---[ \t]*(?=\r?\n|\z)(.*)\z/ms;
Branch: 1 branch
BranchTrueFalseTotal
unless $text =~ /\A\x{FEFF}?---[ \t]*\r?\n(.*?)^---[ \t]*(?=\r?\n|\z)(.*)\z/ms 8 16 24
102  
103 16 my ($yaml, $body) = ($1, $2);
104  
105 16 my $data = eval { Load($yaml) };
106 16 ▶ die "error: could not parse front matter in \"$name\": $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 15 16
107  
108 15 ▶ $data = {} unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 2 13 15
109 15 ▶ die "error: front matter in \"$name\" must be a set of key: value pairs\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 2 13 15
110 unless ref $data eq 'HASH';
111  
112 13 return ($data, $body);
113 }
114  
115 =head2 parse_date
116  
117 Takes a date string and returns a L<DateTime> object. Accepts ISO 8601 / XML
118 Schema date-times (C<2014-05-02T10:30:00>, optionally with a time zone), the
119 pre-0.19 format with a space instead of a C<T> (C<2014-05-02 10:30:00>), and
120 plain dates (C<2014-05-02>). Dies with a helpful message otherwise.
121  
122 =cut
123  
124 113 ▶sub parse_date {
Subroutine parse_date: called CC=10 SCAR=23.0
Pod documented
125 113 my ($input, $name) = @_;
126  
127 113 ▶ if (ref $input and eval { $input->isa('DateTime') }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input and eval { do { $input->isa("DateTime") } }) 15 98 113
Condition100%3/3
ref $input and eval { do { $input->isa("DateTime") } }
!ll&&!rl&&r
97115
MC/DC100%2/2
ref $input and eval { do { $input->isa("DateTime") } }
ref $input eval { do { $input->isa("DateTime") } }
Truth table100%3/3
A and B
A= ref $inputB= eval { do { $input->isa("DateTime") } }
ABresult
0X0
100
111
128 15 ▶ return $input->isa('App::Dapper::Date') ? $input : bless($input->clone, 'App::Dapper::Date');
Branch: 1 branch
BranchTrueFalseTotal
$input->isa('App::Dapper::Date') ? : 2 13 15
129 }
130  
131 98 ▶ my $date = defined $input ? "$input" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $input ? : 97 1 98
132 98 $date =~ s/^\s+|\s+$//g;
133 98 $date =~ s/^(\d{4}-\d{2}-\d{2})[ ]+(\d)/$1T$2/;
134 98 ▶ $date .= "T00:00:00" if $date =~ /^\d{4}-\d{2}-\d{2}$/;
Branch: 1 branch
BranchTrueFalseTotal
if $date =~ /^\d{4}-\d{2}-\d{2}$/ 9 89 98
135 98 ▶ $date .= ":00" if $date =~ /T\d{2}:\d{2}$/;
Branch: 1 branch
BranchTrueFalseTotal
if $date =~ /T\d{2}:\d{2}$/ 4 94 98
136  
137 98 my $dt = eval { DateTime::Format::XSD->parse_datetime($date) };
138 98 ▶ die "error: could not understand the date \"" . (defined $input ? $input : '') . "\""
Branch: 3 branches
BranchTrueFalseTotal
unless $dt 19 79 98
defined $input ? : 18 1 19
defined $name ? : 2 17 19
139 . (defined $name ? " in \"$name\"" : "")
140 . ". Use the ISO 8601 format, e.g. 2014-05-02T10:30:00\n"
141 unless $dt;
142  
143 79 return bless($dt, 'App::Dapper::Date');
144 }
145  
146 =head2 get_modified_time
147  
148 Takes a file and returns the last modified time of the file.
149  
150 =cut
151  
152 4 ▶sub get_modified_time {
Subroutine get_modified_time: called CC=1 SCAR=0.0
Pod documented
153 4 my ($file) = @_;
154 4 my $date = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime((stat $file)[9]));
155 4 return $date;
156 }
157  
158 =head2 slugify
159  
160 Takes an input string (e.g. the title of a blog post) and "slugifies" it: accented
161 letters are reduced to their plain form, other non-ASCII characters are removed,
162 punctuation is removed (letters, digits, underscores, hyphens and spaces are kept),
163 leading and trailing whitespace is trimmed, the result is lowercased, and runs of
164 spaces and hyphens become a single hyphen. For example, "Café: A Story" becomes
165 "cafe-a-story".
166  
167 =cut
168  
169 35 ▶sub slugify {
Subroutine slugify: called CC=2 SCAR=6.9
Pod documented
170 35 my ($input) = @_;
171  
172 35 ▶ if (not defined $input) { return; }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $input) 2 33 35
173  
174 33 $input = NFKD($input); # Normalize the Unicode string
175 33 $input =~ tr/\000-\177//cd; # Strip non-ASCII characters (>127)
176 33 $input =~ s/[^\w\s-]//g; # Remove all characters that are not word characters (includes _), spaces, or hyphens
177 33 $input =~ s/^\s+|\s+$//g; # Trim whitespace from both ends
178 33 $input = lc($input);
179 33 $input =~ s/[-\s]+/-/g; # Replace all occurrences of spaces and hyphens with a single hyphen
180  
181 33 return $input;
182 }
183  
184 =head2 filter_extension
185  
186 Takes a string (filename) and returns the extension.
187  
188 =cut
189  
190 18 ▶sub filter_extension {
Subroutine filter_extension: called CC=1 SCAR=0.0
Pod documented
191 18 my ($filename) = @_;
192 18 $filename = canonpath $filename;
193  
194 18 my ($ext) = $filename =~ /(\.[^.\/]+)$/;
195  
196 18 return $ext;
197 }
198  
199 =head2 filter_stem
200  
201 Takes a filename and returns the stem of the file name (without the extension).
202  
203 =cut
204  
205 24 ▶sub filter_stem {
Subroutine filter_stem: called CC=1 SCAR=0.0
Pod documented
206 24 my ($filename) = @_;
207 24 $filename = canonpath $filename;
208  
209 24 (my $stem = $filename) =~ s/\.[^.\/]+$//;
210  
211 24 return $stem;
212 }
213  
214 =head2 create_file
215  
216 Takes a file name and a string of the content and writes it to disk. Dies if
217 the file already exists.
218  
219 =cut
220  
221 46 ▶sub create_file {
Subroutine create_file: called CC=4 SCAR=13.9
Pod documented
222 46 my ($filename, $content) = @_;
223 46 ▶ die "Invalid number of arguments to create_file" if @_ != 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ != 2 2 44 46
224 44 $filename = canonpath $filename;
225 44 ▶ die "error: \"$filename\" already exists\n" if -e $filename;
Branch: 1 branch
BranchTrueFalseTotal
if -e $filename 2 42 44
226  
227 42 ▶ print "Creating $filename\n" unless $QUIET;
Branch: 1 branch
BranchTrueFalseTotal
unless $App::Dapper::Utils::QUIET 5 37 42
228 42 write_file($filename, $content);
229 }
230  
231 =head2 create_dir
232  
233 Takes a directory name and creates it (and any missing parents) on disk.
234  
235 =cut
236  
237 10 ▶sub create_dir {
Subroutine create_dir: called CC=5 SCAR=16.1
Pod documented
238 10 my ($dirname) = @_;
239 10 ▶ die "Invalid number of arguments to create_dir" if @_ != 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ != 1 2 8 10
240 8 $dirname = canonpath $dirname;
241  
242 8 ▶ return if -d $dirname;
Branch: 1 branch
BranchTrueFalseTotal
if -d $dirname 1 7 8
243 7 make_path($dirname, { error => \my $errors });
244 7 ▶ if ($errors and @$errors) {
Branch: 1 branch
BranchTrueFalseTotal
if ($errors and @$errors) 1 6 7
Condition66%2/3
$errors and @$errors
!ll&&!rl&&r
061
MC/DC50%1/2
$errors and @$errors
$errors @$errors
Truth table66%2/3
A and B
A= $errorsB= @$errors
ABresult
0X0
100
111
245 1 my ($message) = values %{ $errors->[-1] };
246 1 die "error: could not create directory \"$dirname\": $message\n";
247 }
248 }
249  
250 =head2 name_chars
251  
252 Takes a file name as read from the file system (bytes) and returns it as
253 characters, decoding UTF-8. Names that are not valid UTF-8 are returned as
254 they are. Every name read from a directory goes through this, so that joining
255 it to other text (such as a directory name from C<_config.yml>) doesn't
256 mangle accented letters.
257  
258 =cut
259  
260 158 ▶sub name_chars {
Subroutine name_chars: called CC=2 SCAR=6.9
Pod documented
261 158 my ($name) = @_;
262 158 ▶ return $name unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 1 157 158
263 157 utf8::decode($name);
264 157 return $name;
265 }
266  
267 =head2 name_bytes
268  
269 Takes a file name and returns it as UTF-8 bytes, for code (like
270 L<File::Find>) that joins it to names it reads itself.
271  
272 =cut
273  
274 31 ▶sub name_bytes {
Subroutine name_bytes: called CC=3 SCAR=11.0
Pod documented
275 31 my ($name) = @_;
276 31 ▶ return $name unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 1 30 31
277 30 ▶ utf8::encode($name) if utf8::is_utf8($name);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($name) 3 27 30
278 30 return $name;
279 }
280  
281 =head2 read_dir
282  
283 Takes a directory and returns the names in it (without C<.> and C<..>), as
284 characters, sorted. Dies if the directory can't be read.
285  
286 =cut
287  
288 12 ▶sub read_dir {
Subroutine read_dir: called CC=3 SCAR=11.0
Pod documented
289 12 my ($dir) = @_;
290  
291 12 ▶ opendir(my $dh, $dir) or die "error: could not open \"$dir\": $!\n";
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $dir or die qq[error: could not open "$dir": $!\n] 11 1 12
292 11 ▶ my @names = sort map { name_chars($_) } grep { $_ ne '.' and $_ ne '..' } readdir($dh);
Condition100%3/3
$_ ne '.' && $_ ne '..'
!ll&&!rl&&r
111124
MC/DC100%2/2
$_ ne '.' && $_ ne '..'
$_ ne '.' $_ ne '..'
Truth table100%3/3
A && B
A= $_ ne '.'B= $_ ne '..'
ABresult
0X0
100
111
293 11 closedir($dh);
294  
295 11 return @names;
296 }
297  
298 =head2 copy_recursive
299  
300 Takes a source path (a file or directory), a destination path, and an
301 optional list of absolute paths to skip. Copies the source to the
302 destination, recursing into directories and creating them as needed. No shell
303 is involved, so file names with spaces or special characters are safe.
304 Returns the list of files written.
305  
306 =cut
307  
308 6 ▶sub copy_recursive {
Subroutine copy_recursive: called CC=3 SCAR=11.0
Pod documented
309 6 my ($source, $destination, @skip) = @_;
310  
311 6 my %skip = map { $_ => 1 } grep { defined } map { abs_path($_) } @skip;
312  
313 6 ▶ if (-f $source) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $source) 2 4 6
314 2 _copy_file($source, $destination);
315 1 return ($destination);
316 }
317  
318 4 ▶ die "error: \"$source\" is not a file or directory\n" unless -d $source;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $source 1 3 4
319  
320 3 my @copied;
321 File::Find::find({
322 no_chdir => 1,
323 17 ▶ wanted => sub {
Subroutine __ANON__: called CC=8 SCAR=20.9
324 17 my $path = name_chars($File::Find::name);
325 17 ▶ if (-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $path) 10 7 17
326 10 my $abs = abs_path($path);
327 10 ▶ if (defined $abs and $skip{$abs}) { $File::Find::prune = 1; return; }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $abs and $skip{$abs}) 1 9 10
Condition66%2/3
defined $abs and $skip{$abs}
!ll&&!rl&&r
091
MC/DC50%1/2
defined $abs and $skip{$abs}
defined $abs $skip{$abs}
Truth table66%2/3
A and B
A= defined $absB= $skip{$abs}
ABresult
0X0
100
111
328 }
329 16 my $relative = File::Spec->abs2rel($path, name_chars(name_bytes($source)));
330 16 ▶ my $target = $relative eq '.' ? $destination : catfile($destination, $relative);
Branch: 1 branch
BranchTrueFalseTotal
$relative eq '.' ? : 3 13 16
331 16 ▶ if (-d $path) { make_path($target) unless -d $target; }
Branch: 3 branches
BranchTrueFalseTotal
if (-d $path) { } 9 7 16
elsif (-f $path) { } 7 0 7
unless -d $target 9 0 9
332 7 elsif (-f $path) { _copy_file($path, $target); push @copied, $target; }
333 },
334 3 }, name_bytes($source));
335  
336 3 return @copied;
337 }
338  
339 9 ▶sub _copy_file {
Subroutine _copy_file: called CC=3 SCAR=11.0
340 9 my ($source, $destination) = @_;
341  
342 9 my $dir = dirname($destination);
343 9 ▶ make_path($dir) unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 1 8 9
344  
345 9 ▶ File::Copy::copy($source, $destination)
Branch: 1 branch
BranchTrueFalseTotal
File::Copy::copy($source, $destination) or die qq[error: could not copy "$source" to "$destination": $!\n] 8 1 9
346 or die "error: could not copy \"$source\" to \"$destination\": $!\n";
347 }
348  
349 package App::Dapper::Date;
350  
351 =head1 App::Dapper::Date
352  
353 Dates in Dapper (C<page.date>, C<site.time>) are L<DateTime> objects with one
354 extra method, C<xmlschema>, which returns the date in XML Schema format with
355 its time zone. Template filters only apply to plain strings, so use the
356 method form for dates:
357  
358 <updated>[% page.date.xmlschema %]</updated>
359  
360 =cut
361  
362 191 our @ISA = ('DateTime');
363  
364 48 ▶sub xmlschema {
Subroutine xmlschema: called CC=1 SCAR=0.0
365 48 my ($self) = @_;
366 48 return DateTime::Format::XSD->format_datetime($self);
367 }
368  
369 191 1;
« lib/App/Dapper/Init.pm ↑ Summary bin/dapper »