Debian Codegraph @

inc/YAML/Tiny.pm

raw symbols SCIP
1 #line 1
2 package YAML::Tiny;
3
4 use strict;
5 use Carp 'croak';
6
7 # UTF Support?
8 sub HAVE_UTF8 () { $] >= 5.007003 }
9 BEGIN {
10 if ( HAVE_UTF8 ) {
11 # The string eval helps hide this from Test::MinimumVersion
12 eval "require utf8;";
13 die "Failed to load UTF-8 support" if $@;
14 }
15
16 # Class structure
17 require 5.004;
18 require Exporter;
19 $YAML::Tiny::VERSION = '1.41';
20 @YAML::Tiny::ISA = qw{ Exporter };
21 @YAML::Tiny::EXPORT = qw{ Load Dump };
22 @YAML::Tiny::EXPORT_OK = qw{ LoadFile DumpFile freeze thaw };
23
24 # Error storage
25 $YAML::Tiny::errstr = '';
26 }
27
28 # The character class of all characters we need to escape
29 # NOTE: Inlined, since it's only used once
30 # my $RE_ESCAPE = '[\\x00-\\x08\\x0b-\\x0d\\x0e-\\x1f\"\n]';
31
32 # Printed form of the unprintable characters in the lowest range
33 # of ASCII characters, listed by ASCII ordinal position.
34 my @UNPRINTABLE = qw(
35 z x01 x02 x03 x04 x05 x06 a
36 x08 t n v f r x0e x0f
37 x10 x11 x12 x13 x14 x15 x16 x17
38 x18 x19 x1a e x1c x1d x1e x1f
39 );
40
41 # Printable characters for escapes
42 my %UNESCAPES = (
43 z => "\x00", a => "\x07", t => "\x09",
44 n => "\x0a", v => "\x0b", f => "\x0c",
45 r => "\x0d", e => "\x1b", '\\' => '\\',
46 );
47
48 # Special magic boolean words
49 my %QUOTE = map { $_ => 1 } qw{
50 null Null NULL
51 y Y yes Yes YES n N no No NO
52 true True TRUE false False FALSE
53 on On ON off Off OFF
54 };
55
56
57
58
59
60 #####################################################################
61 # Implementation
62
63 # Create an empty YAML::Tiny object
64 sub new {
65 my $class = shift;
66 bless [ @_ ], $class;
67 }
68
69 # Create an object from a file
70 sub read {
71 my $class = ref $_[0] ? ref shift : shift;
72
73 # Check the file
74 my $file = shift or return $class->_error( 'You did not specify a file name' );
75 return $class->_error( "File '$file' does not exist" ) unless -e $file;
76 return $class->_error( "'$file' is a directory, not a file" ) unless -f _;
77 return $class->_error( "Insufficient permissions to read '$file'" ) unless -r _;
78
79 # Slurp in the file
80 local $/ = undef;
81 local *CFG;
82 unless ( open(CFG, $file) ) {
83 return $class->_error("Failed to open file '$file': $!");
84 }
85 my $contents = <CFG>;
86 unless ( close(CFG) ) {
87 return $class->_error("Failed to close file '$file': $!");
88 }
89
90 $class->read_string( $contents );
91 }
92
93 # Create an object from a string
94 sub read_string {
95 my $class = ref $_[0] ? ref shift : shift;
96 my $self = bless [], $class;
97 my $string = $_[0];
98 unless ( defined $string ) {
99 return $self->_error("Did not provide a string to load");
100 }
101
102 # Byte order marks
103 # NOTE: Keeping this here to educate maintainers
104 # my %BOM = (
105 # "\357\273\277" => 'UTF-8',
106 # "\376\377" => 'UTF-16BE',
107 # "\377\376" => 'UTF-16LE',
108 # "\377\376\0\0" => 'UTF-32LE'
109 # "\0\0\376\377" => 'UTF-32BE',
110 # );
111 if ( $string =~ /^(?:\376\377|\377\376|\377\376\0\0|\0\0\376\377)/ ) {
112 return $self->_error("Stream has a non UTF-8 BOM");
113 } else {
114 # Strip UTF-8 bom if found, we'll just ignore it
115 $string =~ s/^\357\273\277//;
116 }
117
118 # Try to decode as utf8
119 utf8::decode($string) if HAVE_UTF8;
120
121 # Check for some special cases
122 return $self unless length $string;
123 unless ( $string =~ /[\012\015]+\z/ ) {
124 return $self->_error("Stream does not end with newline character");
125 }
126
127 # Split the file into lines
128 my @lines = grep { ! /^\s*(?:\#.*)?\z/ }
129 split /(?:\015{1,2}\012|\015|\012)/, $string;
130
131 # Strip the initial YAML header
132 @lines and $lines[0] =~ /^\%YAML[: ][\d\.]+.*\z/ and shift @lines;
133
134 # A nibbling parser
135 while ( @lines ) {
136 # Do we have a document header?
137 if ( $lines[0] =~ /^---\s*(?:(.+)\s*)?\z/ ) {
138 # Handle scalar documents
139 shift @lines;
140 if ( defined $1 and $1 !~ /^(?:\#.+|\%YAML[: ][\d\.]+)\z/ ) {
141 push @$self, $self->_read_scalar( "$1", [ undef ], \@lines );
142 next;
143 }
144 }
145
146 if ( ! @lines or $lines[0] =~ /^(?:---|\.\.\.)/ ) {
147 # A naked document
148 push @$self, undef;
149 while ( @lines and $lines[0] !~ /^---/ ) {
150 shift @lines;
151 }
152
153 } elsif ( $lines[0] =~ /^\s*\-/ ) {
154 # An array at the root
155 my $document = [ ];
156 push @$self, $document;
157 $self->_read_array( $document, [ 0 ], \@lines );
158
159 } elsif ( $lines[0] =~ /^(\s*)\S/ ) {
160 # A hash at the root
161 my $document = { };
162 push @$self, $document;
163 $self->_read_hash( $document, [ length($1) ], \@lines );
164
165 } else {
166 croak("YAML::Tiny failed to classify the line '$lines[0]'");
167 }
168 }
169
170 $self;
171 }
172
173 # Deparse a scalar string to the actual scalar
174 sub _read_scalar {
175 my ($self, $string, $indent, $lines) = @_;
176
177 # Trim trailing whitespace
178 $string =~ s/\s*\z//;
179
180 # Explitic null/undef
181 return undef if $string eq '~';
182
183 # Single quote
184 if ( $string =~ /^\'(.*?)\'\z/ ) {
185 return '' unless defined $1;
186 $string = $1;
187 $string =~ s/\'\'/\'/g;
188 return $string;
189 }
190
191 # Double quote.
192 # The commented out form is simpler, but overloaded the Perl regex
193 # engine due to recursion and backtracking problems on strings
194 # larger than 32,000ish characters. Keep it for reference purposes.
195 # if ( $string =~ /^\"((?:\\.|[^\"])*)\"\z/ ) {
196 if ( $string =~ /^\"([^\\"]*(?:\\.[^\\"]*)*)\"\z/ ) {
197 # Reusing the variable is a little ugly,
198 # but avoids a new variable and a string copy.
199 $string = $1;
200 $string =~ s/\\"/"/g;
201 $string =~ s/\\([never\\fartz]|x([0-9a-fA-F]{2}))/(length($1)>1)?pack("H2",$2):$UNESCAPES{$1}/gex;
202 return $string;
203 }
204
205 # Special cases
206 if ( $string =~ /^[\'\"!&]/ ) {
207 croak("YAML::Tiny does not support a feature in line '$lines->[0]'");
208 }
209 return {} if $string eq '{}';
210 return [] if $string eq '[]';
211
212 # Regular unquoted string
213 return $string unless $string =~ /^[>|]/;
214
215 # Error
216 croak("YAML::Tiny failed to find multi-line scalar content") unless @$lines;
217
218 # Check the indent depth
219 $lines->[0] =~ /^(\s*)/;
220 $indent->[-1] = length("$1");
221 if ( defined $indent->[-2] and $indent->[-1] <= $indent->[-2] ) {
222 croak("YAML::Tiny found bad indenting in line '$lines->[0]'");
223 }
224
225 # Pull the lines
226 my @multiline = ();
227 while ( @$lines ) {
228 $lines->[0] =~ /^(\s*)/;
229 last unless length($1) >= $indent->[-1];
230 push @multiline, substr(shift(@$lines), length($1));
231 }
232
233 my $j = (substr($string, 0, 1) eq '>') ? ' ' : "\n";
234 my $t = (substr($string, 1, 1) eq '-') ? '' : "\n";
235 return join( $j, @multiline ) . $t;
236 }
237
238 # Parse an array
239 sub _read_array {
240 my ($self, $array, $indent, $lines) = @_;
241
242 while ( @$lines ) {
243 # Check for a new document
244 if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) {
245 while ( @$lines and $lines->[0] !~ /^---/ ) {
246 shift @$lines;
247 }
248 return 1;
249 }
250
251 # Check the indent level
252 $lines->[0] =~ /^(\s*)/;
253 if ( length($1) < $indent->[-1] ) {
254 return 1;
255 } elsif ( length($1) > $indent->[-1] ) {
256 croak("YAML::Tiny found bad indenting in line '$lines->[0]'");
257 }
258
259 if ( $lines->[0] =~ /^(\s*\-\s+)[^\'\"]\S*\s*:(?:\s+|$)/ ) {
260 # Inline nested hash
261 my $indent2 = length("$1");
262 $lines->[0] =~ s/-/ /;
263 push @$array, { };
264 $self->_read_hash( $array->[-1], [ @$indent, $indent2 ], $lines );
265
266 } elsif ( $lines->[0] =~ /^\s*\-(\s*)(.+?)\s*\z/ ) {
267 # Array entry with a value
268 shift @$lines;
269 push @$array, $self->_read_scalar( "$2", [ @$indent, undef ], $lines );
270
271 } elsif ( $lines->[0] =~ /^\s*\-\s*\z/ ) {
272 shift @$lines;
273 unless ( @$lines ) {
274 push @$array, undef;
275 return 1;
276 }
277 if ( $lines->[0] =~ /^(\s*)\-/ ) {
278 my $indent2 = length("$1");
279 if ( $indent->[-1] == $indent2 ) {
280 # Null array entry
281 push @$array, undef;
282 } else {
283 # Naked indenter
284 push @$array, [ ];
285 $self->_read_array( $array->[-1], [ @$indent, $indent2 ], $lines );
286 }
287
288 } elsif ( $lines->[0] =~ /^(\s*)\S/ ) {
289 push @$array, { };
290 $self->_read_hash( $array->[-1], [ @$indent, length("$1") ], $lines );
291
292 } else {
293 croak("YAML::Tiny failed to classify line '$lines->[0]'");
294 }
295
296 } elsif ( defined $indent->[-2] and $indent->[-1] == $indent->[-2] ) {
297 # This is probably a structure like the following...
298 # ---
299 # foo:
300 # - list
301 # bar: value
302 #
303 # ... so lets return and let the hash parser handle it
304 return 1;
305
306 } else {
307 croak("YAML::Tiny failed to classify line '$lines->[0]'");
308 }
309 }
310
311 return 1;
312 }
313
314 # Parse an array
315 sub _read_hash {
316 my ($self, $hash, $indent, $lines) = @_;
317
318 while ( @$lines ) {
319 # Check for a new document
320 if ( $lines->[0] =~ /^(?:---|\.\.\.)/ ) {
321 while ( @$lines and $lines->[0] !~ /^---/ ) {
322 shift @$lines;
323 }
324 return 1;
325 }
326
327 # Check the indent level
328 $lines->[0] =~ /^(\s*)/;
329 if ( length($1) < $indent->[-1] ) {
330 return 1;
331 } elsif ( length($1) > $indent->[-1] ) {
332 croak("YAML::Tiny found bad indenting in line '$lines->[0]'");
333 }
334
335 # Get the key
336 unless ( $lines->[0] =~ s/^\s*([^\'\" ][^\n]*?)\s*:(\s+|$)// ) {
337 if ( $lines->[0] =~ /^\s*[?\'\"]/ ) {
338 croak("YAML::Tiny does not support a feature in line '$lines->[0]'");
339 }
340 croak("YAML::Tiny failed to classify line '$lines->[0]'");
341 }
342 my $key = $1;
343
344 # Do we have a value?
345 if ( length $lines->[0] ) {
346 # Yes
347 $hash->{$key} = $self->_read_scalar( shift(@$lines), [ @$indent, undef ], $lines );
348 } else {
349 # An indent
350 shift @$lines;
351 unless ( @$lines ) {
352 $hash->{$key} = undef;
353 return 1;
354 }
355 if ( $lines->[0] =~ /^(\s*)-/ ) {
356 $hash->{$key} = [];
357 $self->_read_array( $hash->{$key}, [ @$indent, length($1) ], $lines );
358 } elsif ( $lines->[0] =~ /^(\s*)./ ) {
359 my $indent2 = length("$1");
360 if ( $indent->[-1] >= $indent2 ) {
361 # Null hash entry
362 $hash->{$key} = undef;
363 } else {
364 $hash->{$key} = {};
365 $self->_read_hash( $hash->{$key}, [ @$indent, length($1) ], $lines );
366 }
367 }
368 }
369 }
370
371 return 1;
372 }
373
374 # Save an object to a file
375 sub write {
376 my $self = shift;
377 my $file = shift or return $self->_error('No file name provided');
378
379 # Write it to the file
380 open( CFG, '>' . $file ) or return $self->_error(
381 "Failed to open file '$file' for writing: $!"
382 );
383 print CFG $self->write_string;
384 close CFG;
385
386 return 1;
387 }
388
389 # Save an object to a string
390 sub write_string {
391 my $self = shift;
392 return '' unless @$self;
393
394 # Iterate over the documents
395 my $indent = 0;
396 my @lines = ();
397 foreach my $cursor ( @$self ) {
398 push @lines, '---';
399
400 # An empty document
401 if ( ! defined $cursor ) {
402 # Do nothing
403
404 # A scalar document
405 } elsif ( ! ref $cursor ) {
406 $lines[-1] .= ' ' . $self->_write_scalar( $cursor, $indent );
407
408 # A list at the root
409 } elsif ( ref $cursor eq 'ARRAY' ) {
410 unless ( @$cursor ) {
411 $lines[-1] .= ' []';
412 next;
413 }
414 push @lines, $self->_write_array( $cursor, $indent, {} );
415
416 # A hash at the root
417 } elsif ( ref $cursor eq 'HASH' ) {
418 unless ( %$cursor ) {
419 $lines[-1] .= ' {}';
420 next;
421 }
422 push @lines, $self->_write_hash( $cursor, $indent, {} );
423
424 } else {
425 croak("Cannot serialize " . ref($cursor));
426 }
427 }
428
429 join '', map { "$_\n" } @lines;
430 }
431
432 sub _write_scalar {
433 my $string = $_[1];
434 return '~' unless defined $string;
435 return "''" unless length $string;
436 if ( $string =~ /[\x00-\x08\x0b-\x0d\x0e-\x1f\"\'\n]/ ) {
437 $string =~ s/\\/\\\\/g;
438 $string =~ s/"/\\"/g;
439 $string =~ s/\n/\\n/g;
440 $string =~ s/([\x00-\x1f])/\\$UNPRINTABLE[ord($1)]/g;
441 return qq|"$string"|;
442 }
443 if ( $string =~ /(?:^\W|\s)/ or $QUOTE{$string} ) {
444 return "'$string'";
445 }
446 return $string;
447 }
448
449 sub _write_array {
450 my ($self, $array, $indent, $seen) = @_;
451 if ( $seen->{refaddr($array)}++ ) {
452 die "YAML::Tiny does not support circular references";
453 }
454 my @lines = ();
455 foreach my $el ( @$array ) {
456 my $line = (' ' x $indent) . '-';
457 my $type = ref $el;
458 if ( ! $type ) {
459 $line .= ' ' . $self->_write_scalar( $el, $indent + 1 );
460 push @lines, $line;
461
462 } elsif ( $type eq 'ARRAY' ) {
463 if ( @$el ) {
464 push @lines, $line;
465 push @lines, $self->_write_array( $el, $indent + 1, $seen );
466 } else {
467 $line .= ' []';
468 push @lines, $line;
469 }
470
471 } elsif ( $type eq 'HASH' ) {
472 if ( keys %$el ) {
473 push @lines, $line;
474 push @lines, $self->_write_hash( $el, $indent + 1, $seen );
475 } else {
476 $line .= ' {}';
477 push @lines, $line;
478 }
479
480 } else {
481 die "YAML::Tiny does not support $type references";
482 }
483 }
484
485 @lines;
486 }
487
488 sub _write_hash {
489 my ($self, $hash, $indent, $seen) = @_;
490 if ( $seen->{refaddr($hash)}++ ) {
491 die "YAML::Tiny does not support circular references";
492 }
493 my @lines = ();
494 foreach my $name ( sort keys %$hash ) {
495 my $el = $hash->{$name};
496 my $line = (' ' x $indent) . "$name:";
497 my $type = ref $el;
498 if ( ! $type ) {
499 $line .= ' ' . $self->_write_scalar( $el, $indent + 1 );
500 push @lines, $line;
501
502 } elsif ( $type eq 'ARRAY' ) {
503 if ( @$el ) {
504 push @lines, $line;
505 push @lines, $self->_write_array( $el, $indent + 1, $seen );
506 } else {
507 $line .= ' []';
508 push @lines, $line;
509 }
510
511 } elsif ( $type eq 'HASH' ) {
512 if ( keys %$el ) {
513 push @lines, $line;
514 push @lines, $self->_write_hash( $el, $indent + 1, $seen );
515 } else {
516 $line .= ' {}';
517 push @lines, $line;
518 }
519
520 } else {
521 die "YAML::Tiny does not support $type references";
522 }
523 }
524
525 @lines;
526 }
527
528 # Set error
529 sub _error {
530 $YAML::Tiny::errstr = $_[1];
531 undef;
532 }
533
534 # Retrieve error
535 sub errstr {
536 $YAML::Tiny::errstr;
537 }
538
539
540
541
542
543 #####################################################################
544 # YAML Compatibility
545
546 sub Dump {
547 YAML::Tiny->new(@_)->write_string;
548 }
549
550 sub Load {
551 my $self = YAML::Tiny->read_string(@_);
552 unless ( $self ) {
553 croak("Failed to load YAML document from string");
554 }
555 if ( wantarray ) {
556 return @$self;
557 } else {
558 # To match YAML.pm, return the last document
559 return $self->[-1];
560 }
561 }
562
563 BEGIN {
564 *freeze = *Dump;
565 *thaw = *Load;
566 }
567
568 sub DumpFile {
569 my $file = shift;
570 YAML::Tiny->new(@_)->write($file);
571 }
572
573 sub LoadFile {
574 my $self = YAML::Tiny->read($_[0]);
575 unless ( $self ) {
576 croak("Failed to load YAML document from '" . ($_[0] || '') . "'");
577 }
578 if ( wantarray ) {
579 return @$self;
580 } else {
581 # Return only the last document to match YAML.pm,
582 return $self->[-1];
583 }
584 }
585
586
587
588
589
590 #####################################################################
591 # Use Scalar::Util if possible, otherwise emulate it
592
593 BEGIN {
594 eval {
595 require Scalar::Util;
596 };
597 if ( $@ ) {
598 # Failed to load Scalar::Util
599 eval <<'END_PERL';
600 sub refaddr {
601 my $pkg = ref($_[0]) or return undef;
602 if (!!UNIVERSAL::can($_[0], 'can')) {
603 bless $_[0], 'Scalar::Util::Fake';
604 } else {
605 $pkg = undef;
606 }
607 "$_[0]" =~ /0x(\w+)/;
608 my $i = do { local $^W; hex $1 };
609 bless $_[0], $pkg if defined $pkg;
610 $i;
611 }
612 END_PERL
613 } else {
614 Scalar::Util->import('refaddr');
615 }
616 }
617
618 1;
619
620 __END__
621
622 #line 1132