lib/App/Dapper/Utils.pm

filter: Statementstmt 36.1% 60 / 166 Branchbran 8.1% 7 / 86 Conditioncond 22.2% 2 / 9 MC/DCmcdc 16.6% 1 / 6 Subroutinesub 48.4% 16 / 33 Podpod 100% 15 / 15 totaltotal 32.0% 101 / 315 CC 47 SCAR 30.0
CC
47
Cov
26%
__ANON__
72.0
split_frontmatter
42.0
write_file
30.0
CRAP 20.0
« lib/App/Dapper/Init.pm ↑ Summary lib/App/Dapper/Markdown.pm »
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 32 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 32 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 32 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 32 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 32 ▶use POSIX;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 32 ▶use Unicode::Normalize;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 32 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 32 ▶use File::Spec::Functions qw/ canonpath catfile /;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 32 ▶use File::Path qw/ make_path /;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 32 ▶use File::Basename qw/ dirname /;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 32 ▶use File::Copy ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 32 ▶use File::Find ();
Subroutine BEGIN: called CC=1 SCAR=0.0
24 32 ▶use Cwd qw/ abs_path /;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 32 ▶use YAML::PP qw/ Load /;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 32 ▶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 32 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 0 ▶sub read_file {
Subroutine read_file: not called CC=4 SCAR=30.0
Pod documented
38 0 my ($file_name) = @_;
39  
40 0 ▶ 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] 0 0 0
41 or die "error: could not open \"$file_name\": $!\n";
42 0 my $file_contents = do { local $/; <$fh> };
43 0 ▶ 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] 0 0 0
44  
45 0 ▶ return defined $file_contents ? $file_contents : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $file_contents ? : 0 0 0
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 0 ▶sub write_file {
Subroutine write_file: not called CC=5 SCAR=34.0
Pod documented
56 0 my ($file_name, $content) = @_;
57  
58 0 my $dir = dirname($file_name);
59 0 ▶ make_path($dir) unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 0 0
60  
61 0 ▶ 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] 0 0 0
62 or die "error: could not open \"$file_name\" for writing: $!\n";
63 0 ▶ 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] 0 0 0
64 0 ▶ 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] 0 0 0
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 0 ▶sub has_frontmatter {
Subroutine has_frontmatter: not called CC=4 SCAR=30.0
Pod documented
76 0 my ($file_name) = @_;
77  
78 0 ▶ 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] 0 0 0
79 or die "error: could not open \"$file_name\": $!\n";
80 0 my $read = read($fh, my $head, 64);
81 0 close($fh);
82  
83 0 ▶ return 0 unless $read;
Branch: 1 branch
BranchTrueFalseTotal
unless $read 0 0 0
84 0 ▶ 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)/ ? : 0 0 0
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 0 ▶sub split_frontmatter {
Subroutine split_frontmatter: not called CC=6 SCAR=37.4
Pod documented
98 0 my ($text, $name) = @_;
99  
100 0 ▶ return unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 0 0
101 0 ▶ 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 0 0 0
102  
103 0 my ($yaml, $body) = ($1, $2);
104  
105 0 my $data = eval { Load($yaml) };
106 0 ▶ die "error: could not parse front matter in \"$name\": $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
107  
108 0 ▶ $data = {} unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 0 0
109 0 ▶ die "error: front matter in \"$name\" must be a set of key: value pairs\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 0 0
110 unless ref $data eq 'HASH';
111  
112 0 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 2 ▶sub parse_date {
Subroutine parse_date: called CC=9 SCAR=23.5
Pod documented
125 2 my ($input, $name) = @_;
126  
127 2 ▶ if (ref $input and eval { $input->isa('DateTime') }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input and eval { do { $input->isa("DateTime") } }) 1 1 2
Condition66%2/3
ref $input and eval { do { $input->isa("DateTime") } }
!ll&&!rl&&r
101
MC/DC50%1/2
ref $input and eval { do { $input->isa("DateTime") } }
ref $input eval { do { $input->isa("DateTime") } }
Truth table66%2/3
A and B
A= ref $inputB= eval { do { $input->isa("DateTime") } }
ABresult
0X0
100
111
128 1 ▶ return $input->isa('App::Dapper::Date') ? $input : bless($input->clone, 'App::Dapper::Date');
Branch: 1 branch
BranchTrueFalseTotal
$input->isa('App::Dapper::Date') ? : 0 1 1
129 }
130  
131 1 ▶ my $date = defined $input ? "$input" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $input ? : 1 0 1
132 1 $date =~ s/^\s+|\s+$//g;
133 1 $date =~ s/^(\d{4}-\d{2}-\d{2})[ ]+(\d)/$1T$2/;
134 1 ▶ $date .= "T00:00:00" if $date =~ /^\d{4}-\d{2}-\d{2}$/;
Branch: 1 branch
BranchTrueFalseTotal
if $date =~ /^\d{4}-\d{2}-\d{2}$/ 0 1 1
135 1 ▶ $date .= ":00" if $date =~ /T\d{2}:\d{2}$/;
Branch: 1 branch
BranchTrueFalseTotal
if $date =~ /T\d{2}:\d{2}$/ 0 1 1
136  
137 1 my $dt = eval { DateTime::Format::XSD->parse_datetime($date) };
138 1 ▶ die "error: could not understand the date \"$input\""
Branch: 2 branches
BranchTrueFalseTotal
unless $dt 0 1 1
defined $name ? : 0 0 0
139 . (defined $name ? " in \"$name\"" : "")
140 . ". Use the ISO 8601 format, e.g. 2014-05-02T10:30:00\n"
141 unless $dt;
142  
143 1 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 0 ▶sub get_modified_time {
Subroutine get_modified_time: not called CC=1 SCAR=6.9
Pod documented
153 0 my ($file) = @_;
154 0 my $date = POSIX::strftime( "%Y-%m-%dT%H:%M:%S", localtime((stat $file)[9]));
155 0 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 0 ▶sub slugify {
Subroutine slugify: not called CC=2 SCAR=17.9
Pod documented
170 0 my ($input) = @_;
171  
172 0 ▶ if (not defined $input) { return; }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $input) 0 0 0
173  
174 0 $input = NFKD($input); # Normalize the Unicode string
175 0 $input =~ tr/\000-\177//cd; # Strip non-ASCII characters (>127)
176 0 $input =~ s/[^\w\s-]//g; # Remove all characters that are not word characters (includes _), spaces, or hyphens
177 0 $input =~ s/^\s+|\s+$//g; # Trim whitespace from both ends
178 0 $input = lc($input);
179 0 $input =~ s/[-\s]+/-/g; # Replace all occurrences of spaces and hyphens with a single hyphen
180  
181 0 return $input;
182 }
183  
184 =head2 filter_extension
185  
186 Takes a string (filename) and returns the extension.
187  
188 =cut
189  
190 0 ▶sub filter_extension {
Subroutine filter_extension: not called CC=1 SCAR=6.9
Pod documented
191 0 my ($filename) = @_;
192 0 $filename = canonpath $filename;
193  
194 0 my ($ext) = $filename =~ /(\.[^.\/]+)$/;
195  
196 0 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 0 ▶sub filter_stem {
Subroutine filter_stem: not called CC=1 SCAR=6.9
Pod documented
206 0 my ($filename) = @_;
207 0 $filename = canonpath $filename;
208  
209 0 (my $stem = $filename) =~ s/\.[^.\/]+$//;
210  
211 0 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 0 ▶sub create_file {
Subroutine create_file: not called CC=4 SCAR=30.0
Pod documented
222 0 my ($filename, $content) = @_;
223 0 ▶ die "Invalid number of arguments to create_file" if @_ != 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ != 2 0 0 0
224 0 $filename = canonpath $filename;
225 0 ▶ die "error: \"$filename\" already exists\n" if -e $filename;
Branch: 1 branch
BranchTrueFalseTotal
if -e $filename 0 0 0
226  
227 0 ▶ print "Creating $filename\n" unless $QUIET;
Branch: 1 branch
BranchTrueFalseTotal
unless $App::Dapper::Utils::QUIET 0 0 0
228 0 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 0 ▶sub create_dir {
Subroutine create_dir: not called CC=4 SCAR=30.0
Pod documented
238 0 my ($dirname) = @_;
239 0 ▶ die "Invalid number of arguments to create_dir" if @_ != 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ != 1 0 0 0
240 0 $dirname = canonpath $dirname;
241  
242 0 ▶ return if -d $dirname;
Branch: 1 branch
BranchTrueFalseTotal
if -d $dirname 0 0 0
243 0 ▶ make_path($dirname)
Branch: 1 branch
BranchTrueFalseTotal
make_path($dirname) or die qq[error: could not create directory "$dirname": $!\n] 0 0 0
244 or die "error: could not create directory \"$dirname\": $!\n";
245 }
246  
247 =head2 name_chars
248  
249 Takes a file name as read from the file system (bytes) and returns it as
250 characters, decoding UTF-8. Names that are not valid UTF-8 are returned as
251 they are. Every name read from a directory goes through this, so that joining
252 it to other text (such as a directory name from C<_config.yml>) doesn't
253 mangle accented letters.
254  
255 =cut
256  
257 0 ▶sub name_chars {
Subroutine name_chars: not called CC=2 SCAR=17.9
Pod documented
258 0 my ($name) = @_;
259 0 ▶ return $name unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 0 0
260 0 utf8::decode($name);
261 0 return $name;
262 }
263  
264 =head2 name_bytes
265  
266 Takes a file name and returns it as UTF-8 bytes, for code (like
267 L<File::Find>) that joins it to names it reads itself.
268  
269 =cut
270  
271 0 ▶sub name_bytes {
Subroutine name_bytes: not called CC=3 SCAR=24.8
Pod documented
272 0 my ($name) = @_;
273 0 ▶ return $name unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 0 0
274 0 ▶ utf8::encode($name) if utf8::is_utf8($name);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($name) 0 0 0
275 0 return $name;
276 }
277  
278 =head2 read_dir
279  
280 Takes a directory and returns the names in it (without C<.> and C<..>), as
281 characters, sorted. Dies if the directory can't be read.
282  
283 =cut
284  
285 0 ▶sub read_dir {
Subroutine read_dir: not called CC=3 SCAR=24.8
Pod documented
286 0 my ($dir) = @_;
287  
288 0 ▶ 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] 0 0 0
289 0 ▶ my @names = sort map { name_chars($_) } grep { $_ ne '.' and $_ ne '..' } readdir($dh);
Condition0%0/3
$_ ne '.' && $_ ne '..'
!ll&&!rl&&r
000
MC/DC0%0/2
$_ ne '.' && $_ ne '..'
$_ ne '.' $_ ne '..'
Truth table0%0/3
A && B
A= $_ ne '.'B= $_ ne '..'
ABresult
0X0
100
111
290 0 closedir($dh);
291  
292 0 return @names;
293 }
294  
295 =head2 copy_recursive
296  
297 Takes a source path (a file or directory), a destination path, and an
298 optional list of absolute paths to skip. Copies the source to the
299 destination, recursing into directories and creating them as needed. No shell
300 is involved, so file names with spaces or special characters are safe.
301 Returns the list of files written.
302  
303 =cut
304  
305 0 ▶sub copy_recursive {
Subroutine copy_recursive: not called CC=3 SCAR=24.8
Pod documented
306 0 my ($source, $destination, @skip) = @_;
307  
308 0 my %skip = map { $_ => 1 } grep { defined } map { abs_path($_) } @skip;
309  
310 0 ▶ if (-f $source) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $source) 0 0 0
311 0 _copy_file($source, $destination);
312 0 return ($destination);
313 }
314  
315 0 ▶ die "error: \"$source\" is not a file or directory\n" unless -d $source;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $source 0 0 0
316  
317 0 my @copied;
318 File::Find::find({
319 no_chdir => 1,
320 0 ▶ wanted => sub {
Subroutine __ANON__: not called CC=8 SCAR=42.8
321 0 my $path = name_chars($File::Find::name);
322 0 ▶ if (-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $path) 0 0 0
323 0 my $abs = abs_path($path);
324 0 ▶ if (defined $abs and $skip{$abs}) { $File::Find::prune = 1; return; }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $abs and $skip{$abs}) 0 0 0
Condition0%0/3
defined $abs and $skip{$abs}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $abs and $skip{$abs}
defined $abs $skip{$abs}
Truth table0%0/3
A and B
A= defined $absB= $skip{$abs}
ABresult
0X0
100
111
325 }
326 0 my $relative = File::Spec->abs2rel($path, name_chars(name_bytes($source)));
327 0 ▶ my $target = $relative eq '.' ? $destination : catfile($destination, $relative);
Branch: 1 branch
BranchTrueFalseTotal
$relative eq '.' ? : 0 0 0
328 0 ▶ if (-d $path) { make_path($target) unless -d $target; }
Branch: 3 branches
BranchTrueFalseTotal
if (-d $path) { } 0 0 0
elsif (-f $path) { } 0 0 0
unless -d $target 0 0 0
329 0 elsif (-f $path) { _copy_file($path, $target); push @copied, $target; }
330 },
331 0 }, name_bytes($source));
332  
333 0 return @copied;
334 }
335  
336 0 ▶sub _copy_file {
Subroutine _copy_file: not called CC=3 SCAR=24.8
337 0 my ($source, $destination) = @_;
338  
339 0 my $dir = dirname($destination);
340 0 ▶ make_path($dir) unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 0 0
341  
342 0 ▶ 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] 0 0 0
343 or die "error: could not copy \"$source\" to \"$destination\": $!\n";
344 }
345  
346 package App::Dapper::Date;
347  
348 =head1 App::Dapper::Date
349  
350 Dates in Dapper (C<page.date>, C<site.time>) are L<DateTime> objects with one
351 extra method, C<xmlschema>, which returns the date in XML Schema format with
352 its time zone. Template filters only apply to plain strings, so use the
353 method form for dates:
354  
355 <updated>[% page.date.xmlschema %]</updated>
356  
357 =cut
358  
359 32 our @ISA = ('DateTime');
360  
361 0 ▶sub xmlschema {
Subroutine xmlschema: not called CC=1 SCAR=6.9
362 0 my ($self) = @_;
363 0 return DateTime::Format::XSD->format_datetime($self);
364 }
365  
366 32 1;
« lib/App/Dapper/Init.pm ↑ Summary lib/App/Dapper/Markdown.pm »