File Coverage

blib/lib/Portable/LoadYaml.pm
Criterion Covered Total %
statement 12 175 7.4
branch 0 120 0.0
condition 0 33 0.0
subroutine 4 12 33.3
pod 0 1 0.0
total 16 341 4.9


line stmt bran cond sub pod time code
1             package Portable::LoadYaml;
2            
3             ### UGLY HACK: these functions where completely copied from Parse::CPAN::Meta
4            
5 4     4   51 use 5.008;
  4         12  
  4         131  
6 4     4   28 use strict;
  4         6  
  4         97  
7 4     4   23 use warnings;
  4         6  
  4         2502  
8            
9             our $VERSION = '1.22';
10            
11             sub load_file {
12 0     0 0   my $file = shift;
13 0           my $self = __PACKAGE__->_load_file($file);
14 0           return $self->[-1];
15             }
16            
17             #####################################################################
18             # Constants
19            
20             # Printed form of the unprintable characters in the lowest range
21             # of ASCII characters, listed by ASCII ordinal position.
22             my @UNPRINTABLE = qw(
23             0 x01 x02 x03 x04 x05 x06 a
24             b t n v f r x0E x0F
25             x10 x11 x12 x13 x14 x15 x16 x17
26             x18 x19 x1A e x1C x1D x1E x1F
27             );
28            
29             # Printable characters for escapes
30             my %UNESCAPES = (
31             0 => "\x00", z => "\x00", N => "\x85",
32             a => "\x07", b => "\x08", t => "\x09",
33             n => "\x0a", v => "\x0b", f => "\x0c",
34             r => "\x0d", e => "\x1b", '\\' => '\\',
35             );
36            
37             # These 3 values have special meaning when unquoted and using the
38             # default YAML schema. They need quotes if they are strings.
39             my %QUOTE = map { $_ => 1 } qw{
40             null true false
41             };
42            
43             # The commented out form is simpler, but overloaded the Perl regex
44             # engine due to recursion and backtracking problems on strings
45             # larger than 32,000ish characters. Keep it for reference purposes.
46             # qr/\"((?:\\.|[^\"])*)\"/
47             my $re_capture_double_quoted = qr/\"([^\\"]*(?:\\.[^\\"]*)*)\"/;
48             my $re_capture_single_quoted = qr/\'([^\']*(?:\'\'[^\']*)*)\'/;
49             # unquoted re gets trailing space that needs to be stripped
50             my $re_capture_unquoted_key = qr/([^:]+(?::+\S[^:]*)*)(?=\s*\:(?:\s+|$))/;
51             my $re_trailing_comment = qr/(?:\s+\#.*)?/;
52             my $re_key_value_separator = qr/\s*:(?:\s+(?:\#.*)?|$)/;
53            
54             ###
55             # Loader functions:
56            
57             # Create an object from a file
58             sub _load_file {
59 0 0   0     my $class = ref $_[0] ? ref shift : shift;
60            
61             # Check the file
62 0 0         my $file = shift or $class->_error( 'You did not specify a file name' );
63 0 0         $class->_error( "File '$file' does not exist" )
64             unless -e $file;
65 0 0         $class->_error( "'$file' is a directory, not a file" )
66             unless -f _;
67 0 0         $class->_error( "Insufficient permissions to read '$file'" )
68             unless -r _;
69            
70             # Open unbuffered
71 0           open( my $fh, "<:unix", $file );
72 0 0         unless ( $fh ) {
73 0           $class->_error("Failed to open file '$file': $!");
74             }
75            
76             # slurp the contents
77 0           my $contents = eval {
78 4     4   18 use warnings FATAL => 'utf8';
  4         7  
  4         10662  
79 0           local $/;
80             <$fh>
81 0           };
82 0 0         if ( my $err = $@ ) {
83 0           $class->_error("Error reading from file '$file': $err");
84             }
85            
86             # close the file (release the lock)
87 0 0         unless ( close $fh ) {
88 0           $class->_error("Failed to close file '$file': $!");
89             }
90            
91 0           $class->_load_string( $contents );
92             }
93            
94             # Create an object from a string
95             sub _load_string {
96 0 0   0     my $class = ref $_[0] ? ref shift : shift;
97 0           my $self = bless [], $class;
98 0           my $string = $_[0];
99 0           eval {
100 0 0         unless ( defined $string ) {
101 0           die \"Did not provide a string to load";
102             }
103            
104             # Check if Perl has it marked as characters, but it's internally
105             # inconsistent. E.g. maybe latin1 got read on a :utf8 layer
106 0 0 0       if ( utf8::is_utf8($string) && ! utf8::valid($string) ) {
107 0           die \<<'...';
108             Read an invalid UTF-8 string (maybe mixed UTF-8 and 8-bit character set).
109             Did you decode with lax ":utf8" instead of strict ":encoding(UTF-8)"?
110             ...
111             }
112            
113             # Ensure Unicode character semantics, even for 0x80-0xff
114 0           utf8::upgrade($string);
115            
116             # Check for and strip any leading UTF-8 BOM
117 0           $string =~ s/^\x{FEFF}//;
118            
119             # Check for some special cases
120 0 0         return $self unless length $string;
121            
122             # Split the file into lines
123 0           my @lines = grep { ! /^\s*(?:\#.*)?\z/ }
  0            
124             split /(?:\015{1,2}\012|\015|\012)/, $string;
125            
126             # Strip the initial YAML header
127 0 0 0       @lines and $lines[0] =~ /^\%YAML[: ][\d\.]+.*\z/ and shift @lines;
128            
129             # A nibbling parser
130 0           my $in_document = 0;
131 0           while ( @lines ) {
132             # Do we have a document header?
133 0 0         if ( $lines[0] =~ /^---\s*(?:(.+)\s*)?\z/ ) {
134             # Handle scalar documents
135 0           shift @lines;
136 0 0 0       if ( defined $1 and $1 !~ /^(?:\#.+|\%YAML[: ][\d\.]+)\z/ ) {
137 0           push @$self,
138             $self->_load_scalar( "$1", [ undef ], \@lines );
139 0           next;
140             }
141 0           $in_document = 1;
142             }
143            
144 0 0 0       if ( ! @lines or $lines[0] =~ /^(?:---|\.\.\.)/ ) {
    0 0        
    0          
    0          
145             # A naked document
146 0           push @$self, undef;
147 0   0       while ( @lines and $lines[0] !~ /^---/ ) {
148 0           shift @lines;
149             }
150 0           $in_document = 0;
151            
152             # XXX The final '-+$' is to look for -- which ends up being an
153             # error later.
154             } elsif ( ! $in_document && @$self ) {
155             # only the first document can be explicit
156 0           die \"failed to classify the line '$lines[0]'";
157             } elsif ( $lines[0] =~ /^\s*\-(?:\s|$|-+$)/ ) {
158             # An array at the root
159 0           my $document = [ ];
160 0           push @$self, $document;
161 0           $self->_load_array( $document, [ 0 ], \@lines );
162            
163             } elsif ( $lines[0] =~ /^(\s*)\S/ ) {
164             # A hash at the root
165 0           my $document = { };
166 0           push @$self, $document;
167 0           $self->_load_hash( $document, [ length($1) ], \@lines );
168            
169             } else {
170             # Shouldn't get here. @lines have whitespace-only lines
171             # stripped, and previous match is a line with any
172             # non-whitespace. So this clause should only be reachable via
173             # a perlbug where \s is not symmetric with \S
174            
175             # uncoverable statement
176 0           die \"failed to classify the line '$lines[0]'";
177             }
178             }
179             };
180 0 0         if ( ref $@ eq 'SCALAR' ) {
    0          
181 0           $self->_error(${$@});
  0            
182             } elsif ( $@ ) {
183 0           $self->_error($@);
184             }
185            
186 0           return $self;
187             }
188            
189             sub _unquote_single {
190 0     0     my ($self, $string) = @_;
191 0 0         return '' unless length $string;
192 0           $string =~ s/\'\'/\'/g;
193 0           return $string;
194             }
195            
196             sub _unquote_double {
197 0     0     my ($self, $string) = @_;
198 0 0         return '' unless length $string;
199 0           $string =~ s/\\"/"/g;
200 0           $string =~
201             s{\\([Nnever\\fartz0b]|x([0-9a-fA-F]{2}))}
202 0 0         {(length($1)>1)?pack("H2",$2):$UNESCAPES{$1}}gex;
203 0           return $string;
204             }
205            
206             # Load a YAML scalar string to the actual Perl scalar
207             sub _load_scalar {
208 0     0     my ($self, $string, $indent, $lines) = @_;
209            
210             # Trim trailing whitespace
211 0           $string =~ s/\s*\z//;
212            
213             # Explitic null/undef
214 0 0         return undef if $string eq '~';
215            
216             # Single quote
217 0 0         if ( $string =~ /^$re_capture_single_quoted$re_trailing_comment\z/ ) {
218 0           return $self->_unquote_single($1);
219             }
220            
221             # Double quote.
222 0 0         if ( $string =~ /^$re_capture_double_quoted$re_trailing_comment\z/ ) {
223 0           return $self->_unquote_double($1);
224             }
225            
226             # Special cases
227 0 0         if ( $string =~ /^[\'\"!&]/ ) {
228 0           die \"does not support a feature in line '$string'";
229             }
230 0 0         return {} if $string =~ /^{}(?:\s+\#.*)?\z/;
231 0 0         return [] if $string =~ /^\[\](?:\s+\#.*)?\z/;
232            
233             # Regular unquoted string
234 0 0         if ( $string !~ /^[>|]/ ) {
235 0 0 0       die \"found illegal characters in plain scalar: '$string'"
236             if $string =~ /^(?:-(?:\s|$)|[\@\%\`])/ or
237             $string =~ /:(?:\s|$)/;
238 0           $string =~ s/\s+#.*\z//;
239 0           return $string;
240             }
241            
242             # Error
243 0 0         die \"failed to find multi-line scalar content" unless @$lines;
244            
245             # Check the indent depth
246 0           $lines->[0] =~ /^(\s*)/;
247 0           $indent->[-1] = length("$1");
248 0 0 0       if ( defined $indent->[-2] and $indent->[-1] <= $indent->[-2] ) {
249 0           die \"found bad indenting in line '$lines->[0]'";
250             }
251            
252             # Pull the lines
253 0           my @multiline = ();
254 0           while ( @$lines ) {
255 0           $lines->[0] =~ /^(\s*)/;
256 0 0         last unless length($1) >= $indent->[-1];
257 0           push @multiline, substr(shift(@$lines), length($1));
258             }
259            
260 0 0         my $j = (substr($string, 0, 1) eq '>') ? ' ' : "\n";
261 0 0         my $t = (substr($string, 1, 1) eq '-') ? '' : "\n";
262 0           return join( $j, @multiline ) . $t;
263             }
264            
265             # Load an array
266             sub _load_array {
267 0     0     my ($self, $array, $indent, $lines) = @_;
268            
269 0           while ( @$lines ) {
270             # Check for a new document
271 0 0         if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) {
272 0   0       while ( @$lines and $lines->[0] !~ /^---/ ) {
273 0           shift @$lines;
274             }
275 0           return 1;
276             }
277            
278             # Check the indent level
279 0           $lines->[0] =~ /^(\s*)/;
280 0 0         if ( length($1) < $indent->[-1] ) {
    0          
281 0           return 1;
282             } elsif ( length($1) > $indent->[-1] ) {
283 0           die \"found bad indenting in line '$lines->[0]'";
284             }
285            
286 0 0 0       if ( $lines->[0] =~ /^(\s*\-\s+)[^\'\"]\S*\s*:(?:\s+|$)/ ) {
    0          
    0          
    0          
287             # Inline nested hash
288 0           my $indent2 = length("$1");
289 0           $lines->[0] =~ s/-/ /;
290 0           push @$array, { };
291 0           $self->_load_hash( $array->[-1], [ @$indent, $indent2 ], $lines );
292            
293             } elsif ( $lines->[0] =~ /^\s*\-\s*\z/ ) {
294 0           shift @$lines;
295 0 0         unless ( @$lines ) {
296 0           push @$array, undef;
297 0           return 1;
298             }
299 0 0         if ( $lines->[0] =~ /^(\s*)\-/ ) {
    0          
300 0           my $indent2 = length("$1");
301 0 0         if ( $indent->[-1] == $indent2 ) {
302             # Null array entry
303 0           push @$array, undef;
304             } else {
305             # Naked indenter
306 0           push @$array, [ ];
307 0           $self->_load_array(
308             $array->[-1], [ @$indent, $indent2 ], $lines
309             );
310             }
311            
312             } elsif ( $lines->[0] =~ /^(\s*)\S/ ) {
313 0           push @$array, { };
314 0           $self->_load_hash(
315             $array->[-1], [ @$indent, length("$1") ], $lines
316             );
317            
318             } else {
319 0           die \"failed to classify line '$lines->[0]'";
320             }
321            
322             } elsif ( $lines->[0] =~ /^\s*\-(\s*)(.+?)\s*\z/ ) {
323             # Array entry with a value
324 0           shift @$lines;
325 0           push @$array, $self->_load_scalar(
326             "$2", [ @$indent, undef ], $lines
327             );
328            
329             } elsif ( defined $indent->[-2] and $indent->[-1] == $indent->[-2] ) {
330             # This is probably a structure like the following...
331             # ---
332             # foo:
333             # - list
334             # bar: value
335             #
336             # ... so lets return and let the hash parser handle it
337 0           return 1;
338            
339             } else {
340 0           die \"failed to classify line '$lines->[0]'";
341             }
342             }
343            
344 0           return 1;
345             }
346            
347             # Load a hash
348             sub _load_hash {
349 0     0     my ($self, $hash, $indent, $lines) = @_;
350            
351 0           while ( @$lines ) {
352             # Check for a new document
353 0 0         if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) {
354 0   0       while ( @$lines and $lines->[0] !~ /^---/ ) {
355 0           shift @$lines;
356             }
357 0           return 1;
358             }
359            
360             # Check the indent level
361 0           $lines->[0] =~ /^(\s*)/;
362 0 0         if ( length($1) < $indent->[-1] ) {
    0          
363 0           return 1;
364             } elsif ( length($1) > $indent->[-1] ) {
365 0           die \"found bad indenting in line '$lines->[0]'";
366             }
367            
368             # Find the key
369 0           my $key;
370            
371             # Quoted keys
372 0 0         if ( $lines->[0] =~
    0          
    0          
    0          
373             s/^\s*$re_capture_single_quoted$re_key_value_separator//
374             ) {
375 0           $key = $self->_unquote_single($1);
376             }
377             elsif ( $lines->[0] =~
378             s/^\s*$re_capture_double_quoted$re_key_value_separator//
379             ) {
380 0           $key = $self->_unquote_double($1);
381             }
382             elsif ( $lines->[0] =~
383             s/^\s*$re_capture_unquoted_key$re_key_value_separator//
384             ) {
385 0           $key = $1;
386 0           $key =~ s/\s+$//;
387             }
388             elsif ( $lines->[0] =~ /^\s*\?/ ) {
389 0           die \"does not support a feature in line '$lines->[0]'";
390             }
391             else {
392 0           die \"failed to classify line '$lines->[0]'";
393             }
394            
395             # Do we have a value?
396 0 0         if ( length $lines->[0] ) {
397             # Yes
398 0           $hash->{$key} = $self->_load_scalar(
399             shift(@$lines), [ @$indent, undef ], $lines
400             );
401             } else {
402             # An indent
403 0           shift @$lines;
404 0 0         unless ( @$lines ) {
405 0           $hash->{$key} = undef;
406 0           return 1;
407             }
408 0 0         if ( $lines->[0] =~ /^(\s*)-/ ) {
    0          
409 0           $hash->{$key} = [];
410 0           $self->_load_array(
411             $hash->{$key}, [ @$indent, length($1) ], $lines
412             );
413             } elsif ( $lines->[0] =~ /^(\s*)./ ) {
414 0           my $indent2 = length("$1");
415 0 0         if ( $indent->[-1] >= $indent2 ) {
416             # Null hash entry
417 0           $hash->{$key} = undef;
418             } else {
419 0           $hash->{$key} = {};
420 0           $self->_load_hash(
421             $hash->{$key}, [ @$indent, length($1) ], $lines
422             );
423             }
424             }
425             }
426             }
427            
428 0           return 1;
429             }
430            
431             1;