blib/lib/Config/NINI.pm untested

filter: Statementstmt 0.0% 0 / 202 Branchbran 0.0% 0 / 120 Conditioncond 0.0% 0 / 62 MC/DCmcdc 0.0% 0 / 41 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 447 CC 61 SCAR 53.3
CC
61
Cov
0%
nini_parse_data
506.0
__nini_load_file_data
132.0
__nini_parse_path
110.0
CRAP 206.4
1 ##############################################################################
2 #
3 # Config::NINI is NINI format configuration files parser.
4 # 2026 (c) Vladi Belperchinov-Shabanski "Cade" <cade@noxrun.com>
5 #
6 # DISTRIBUTED UNDER GPLv2
7 #
8 ##############################################################################
9 package Config::NINI;
10 use Exporter;
11 use Storable qw( dclone );
12 use Data::Dumper;
13 use strict;
14  
15 our @ISA = qw( Exporter );
16  
17 our @EXPORT = qw(
18 nini_load_file
19  
20 nini_parse_data
21 );
22  
23 our $VERSION = '0.12';
24  
25 ##############################################################################
26  
27 sub nini_load_file
28 {
29 my $fn = shift; # file name to load
30 my $opt = shift; # options: hash ref
31  
32 my @data;
33  
34 __nini_load_file_data( \@data, $fn, $opt, {} );
35 chomp( @data );
36  
37 return \@data;
38 }
39  
40 sub __nini_load_file_data
41 {
42 my $ar = shift; # current data: array ref
43 my $fn = shift; # file name to load
44 my $opt = shift; # options: hash ref
45 my $seen = shift; # hashref, seen files lookup, guards loops
46  
47 die "nini: error: file load: loop detected for file [$fn]\n" if $seen->{ $fn }++;
48  
49 my $dl = $opt->{ 'DL' };
50 die "nini_load_file: error: 'DL' (debug locations) must be array reference\n" if $dl and ref $dl ne 'ARRAY';
51  
52 # force every file beginning to be anchored to root section
53 push @$ar, "=";
54 push @$dl, "$fn top" if $dl; # this will not happen, just keeps the space
55  
56 open( my $if, $fn );
57  
58 my $ln = 0;
59 while(<$if>)
60 {
61 $ln++;
62 next unless /\S/;
63 next if /^\s*#/;
64 s/^\s*//;
65 s/\s*$//;
66 if( /^\s*\@inc(lude)?\s*(\S+)/i )
67 {
68 my $nf = __nini_find_file( $2, $opt );
69 if( ! $nf )
70 {
71 # warn if debug
72 next;
73 }
74 push @$ar, '@@@push'; # save current section
75 push @$dl, "$nf top" if $dl; # this will not happen, just keeps the space
76 __nini_load_file_data( $ar, $nf, $opt, $seen );
77 push @$ar, '@@@pop'; # restore nini.comlast saved section
78 push @$dl, "$nf bottom" if $dl; # this will not happen, just keeps the space
79 }
80 else
81 {
82 push @$ar, $_;
83 }
84 push @$dl, "$fn line $ln" if $dl;
85 }
86  
87 close( $if );
88  
89 }
90  
91 # TODO: backport to Data::Tools
92 sub __nini_find_file
93 {
94 my $fn = shift; # file name to load
95 my $opt = shift; # options: hash ref
96  
97 return $fn if $fn =~ /^\// and -e $fn;
98 return undef unless exists $opt->{ 'DIRS' } and ref( $opt->{ 'DIRS' } ) eq 'ARRAY';
99  
100 for my $p ( @{ $opt->{ 'DIRS' } } )
101 {
102 my $nf = "$p/$fn";
103 return $nf if -e $nf;
104 }
105  
106 return undef;
107 }
108  
109 ##############################################################################
110  
111 sub __nini_find_next_autoindex
112 {
113 my $n = shift; # hashref of current NINI branch
114  
115 my $x = 0;
116 while( my ( $k, $v ) = each %$n )
117 {
118 next unless ref $v; # skip keys, search for branches only
119 next unless $k =~ /^\d+$/; # skip non-numeric ones, '05' is non-numeric also
120 $x = $k if $k > $x;
121 }
122 return $x + 1;
123 }
124  
125 # parse path, current NINI data ref and takes string and returns current branch hashref
126 sub __nini_parse_path
127 {
128 my $N = shift; # hashref of the result NINI structure
129 my $y = shift; # path type: = regular or * abstract
130 my $p = shift; # path string
131  
132 $p =~ s/^\s*//;
133 $p =~ s/\s*$//;
134  
135 $y = undef unless $y eq '*';
136 my $n = $N; # current branch
137 my @na; # current path names
138 my @p = split /\s+/, $p;
139 for my $e ( @p )
140 {
141 if( $e =~ /\!+/ )
142 {
143 my $el = length $e;
144 for my $k ( keys %$n )
145 {
146 my $r = ref $n->{ $k };
147 delete $n->{ $k } if ! $r and ( $el == 1 or $el > 2 ); # handles keys and ! or !!!+
148 delete $n->{ $k } if $r and ( $el > 1 ); # handles branches and !! or !!!+
149 }
150 }
151 elsif( $e =~ /^([A-Za-z0-9:._\/-]+|[*])$/ )
152 {
153 if( $e eq '*' )
154 {
155 $e = __nini_find_next_autoindex( $n );
156 }
157  
158 if( exists $n->{ $e } and ! ref $n->{ $e } )
159 {
160 # TODO: error, item exists but is a key
161 die "path [$p] resolve hits existing key at [$e]";
162 }
163 else
164 {
165 if( $y eq '*' )
166 {
167 $e = $y . $e;
168 $y = undef;
169 }
170 $n->{ $e } ||= {};
171 $n = $n->{ $e };
172 push @na, $e;
173 }
174 }
175 elsif( $e =~ /^#/ )
176 {
177 # this is start of a comment, exit loop
178 last;
179 }
180 else
181 {
182 # TODO: error
183 die "path [$p] resolve hits invalid element name at [$e]";
184 }
185 }
186 return ( $n, \@na );
187 }
188  
189 sub __nini_find_path
190 {
191 my $N = shift; # hashref of the result NINI structure
192 my $p = shift; # path string
193  
194 $p =~ s/^\s*//;
195 $p =~ s/\s*$//;
196  
197 my $n = $N;
198 my @na;
199 my @p = split /\s+/, $p;
200 for my $e ( @p )
201 {
202 return undef unless exists $n->{ $e };
203 return undef unless ref $n->{ $e };
204 $n = $n->{ $e };
205 push @na, $e;
206 }
207  
208 return ( $n, \@na );
209 }
210  
211 # compare two paths (array refs)
212 # return: 1 if first is exact subset (from pos 0) of the second
213 # 2 if second is exact subset (from pos 0) of the first
214 # undef if any element does not match or one array has zero elements
215 sub __nini_compare_path
216 {
217 my $na1 = shift;
218 my $na2 = shift;
219  
220 return undef if $#$na1 < 0 or $#$na2 < 0; # one is empty, no match
221  
222 my ( $x, $rc ) = $#$na1 < $#$na2 ? ( $#$na1, 1 ) : ( $#$na2, 2 );
223 for( 0 .. $x )
224 {
225 my $e1 = $na1->[$_];
226 my $e2 = $na2->[$_];
227 # print ">>>>>>>>>>>>>> comp path: $e1 === $e2\n";
228 return undef unless $e1 eq $e2;
229 }
230 # print ">>>>>>>>>>>>>> comp rc: $rc\n";
231 return $rc;
232 }
233  
234 # NOTE: this is backported from Data::Tools::CSV
235 # extended with whitespace delimiters and more quote characters
236 sub __nini_parse_values
237 { #OK
238 my @line = split //, shift();
239 my $delim = shift();
240  
241 $delim = length $delim > 0 ? substr( $delim, 0, 1 ) : undef; # sanity
242  
243 my @out;
244 my $fld;
245 my $q; # delimiters count in current data element
246 my $u; # if quotes used, which one is in play
247 for( @line, undef )
248 {
249 if( ! defined $fld )
250 {
251 last if ! defined and ! defined $delim;
252 next if /\s/;
253 $u = $_ if ! $u and index( q['"|], $_ ) > -1;
254 }
255 $q++ if $_ eq $u;
256 if( ( ( defined $delim ? $_ eq $delim : /\s/ ) and $q % 2 == 0 ) or ! defined )
257 {
258 $fld =~ s/\s*$//;
259 $fld =~ s/^\Q$u\E(.*?)\Q$u\E$/$1/,$fld =~ s/\Q$u$u\E/$u/g if $u;
260 push @out, $fld;
261 $fld = $u = $q = undef;
262 next;
263 }
264 $fld .= $_;
265 }
266  
267 return \@out;
268 }
269  
270 sub nini_parse_data
271 {
272 my $ar = shift;
273 my $opt = shift; # options: hash ref
274  
275 my %N; # result NINI config
276  
277 my $debug = $opt->{ 'DEBUG' };
278  
279 my $dl = $opt->{ 'DL' };
280 die "nini_load_file: error: 'DL' (debug locations) must be array reference\n" if $dl and ref $dl ne 'ARRAY';
281  
282 my $n = \%N; # current NINI branch
283 my $na;
284  
285 my @stash;
286  
287 my $ssq = 1; # section sequence
288 my $on = -1; # location number
289 $n->{ ':ord' } = $ssq++;
290 for( @$ar )
291 {
292 $on++;
293 my $ons = $dl ? $dl->[ $on ] : "row $on";
294  
295 if( /^\@\@\@push/ )
296 {
297 push @stash, [ $n, $na ];
298 next;
299 }
300 if( /^\@\@\@pop/ )
301 {
302 ( $n, $na ) = @{ pop @stash };
303 next;
304 }
305  
306 if( /^([=*])\s*(.*)/ )
307 {
308 my $y = $1; # section type, "=" is regular, "*" is abstract
309 my $p = $2; # section path
310 ( $n, $na ) = __nini_parse_path( \%N, $y, $p );
311 push @{ $n->{ ':origin' } }, $ons if $debug;
312 #print ">>>>>>>>>>>>> SECTION [$y$p] seq [$ssq]\n";
313 $n->{ ':ord' } ||= $ssq++ if $y eq '='; # sequences for regular sections
314 }
315 elsif( /^([&]+)\s*(.*)/ )
316 {
317 my $isa = $1; # inherit keys (&), branches (&&) or both (&&&+)
318 my $isap = $2; # inherit path
319 my $lisa = length $isa;
320 my ( $fn, $fna ) = __nini_find_path( \%N, $isap );
321  
322 if( ! $fn )
323 {
324 push @{ $N{ ':warn' } }, "cannot find path to inherit [$isap] at $ons";
325 next;
326 }
327  
328 #print ">>>>>>>>>>>>> $fn -> $n (@$fna) -> {@$na}\n";
329 if( $fn eq $n )
330 {
331 push @{ $N{ ':warn' } }, "cannot inherit self at $ons" if $debug;
332 next;
333 }
334 die "nini: error: cannot inherit parent branch into current (@$fna) -> (@$na) at $ons\n" if ( $lisa == 2 or $lisa > 2 ) and __nini_compare_path( $fna, $na ) == 1;
335  
336 for my $k ( grep /^[^:]/, keys %$fn )
337 {
338 $n->{ $k } = $fn->{ $k } if ! ref $fn->{ $k } and ( $lisa == 1 or $lisa > 2 );
339 $n->{ $k } = dclone( $fn->{ $k } ) if ref $fn->{ $k } and ( $lisa == 2 or $lisa > 2 );
340 }
341 push @{ $n->{ ':origin' } }, $ons, exists $fn->{ ':origin' } ? @{ $fn->{ ':origin' } } : () if $debug;
342 }
343 elsif( /^([+-])?([A-Za-z0-9_:\/][A-Za-z0-9:._\/-]*)(\[(.)?\])?(\s+(.+))?$/ )
344 {
345 my $o = $1; # operator, + add, - remove, etc...
346 my $k = $2; # key name
347 my $a = $3; # array request
348 my $s = $4; # separator
349 my $v = $6; # value data
350  
351 $v = '1' unless length $v;
352  
353 my $vv = __nini_parse_values( $v, $a ? $s : "\000" );
354 # $n->{ $k } = $a ? __nini_parse_array( $v, $s ) : __nini_parse_scalar( $v );
355 $n->{ $k } = $a ? $vv : $vv->[ 0 ];
356 die "nini: error: syntax error in data [$_] at $ons\n" unless defined $n->{ $k };
357 }
358 else
359 {
360 # TODO: error
361 die "nini: error: unrecognisable data [$_] at $ons";
362 }
363 }
364  
365 return \%N;
366 }
367  
368 ##############################################################################
369  
370 1;
371  
372 =pod
373  
374 =head1 NAME
375  
376 Config::NINI - NINI configuration format parser
377  
378 =head1 SYNOPSIS
379  
380 use Config::NINI qw( nini_load_file nini_parse_data );
381  
382 # Load and parse a NINI file
383 my $data = nini_load_file('config.nini');
384 my $config = nini_parse_data( $data );
385  
386 # or
387  
388 my $dl = []; # debug locations
389 my $data = nini_load_file('config.nini', { DL => $dl } );
390 my $config = nini_parse_data( $data, { DL => $dl, DEBUG => 1 } );
391  
392 # Access configuration
393 my $value = $config->{section_name}{key_name};
394 my $arrayref = $config->{section_name}{array_key};
395 my $hashref = $config->{section_name}{subsection_name};
396  
397 =head1 DESCRIPTION
398  
399 Config::NINI is a Perl module for parsing and loading configuration files in
400 the NINI format (Not INI). NINI extends traditional INI file concepts with
401 hierarchical sections, inheritance, array values, and dynamic file inclusion.
402  
403 Specification, examples, notes on NINI format can be found at:
404  
405 https://github.com/cade-vs/NINI
406 https://github.com/cade-vs/NINI/blob/master/nini-spec-19.txt
407 https://github.com/cade-vs/NINI/blob/master/nini-examples-19.txt
408  
409 =head2 Key Features
410  
411 =over
412  
413 =item * Trivial to write manually
414  
415 =item * Allow hierarchical section organization
416  
417 =item * Inheritance of keys and branches between sections
418  
419 =item * Array value support with configurable delimiters
420  
421 =item * Dynamic file inclusion via @include directives
422  
423 =item * Loop detection for included files
424  
425 =item * Debug location tracking (file and line numbers)
426  
427 =item * Abstract section paths with auto-indexing
428  
429 =item * Flexible path navigation and data manipulation
430  
431 =back
432  
433 =head1 INSTALLATION
434  
435 Place Config::NINI in your Perl module search path (@INC). Typically:
436  
437 /usr/lib/perl/
438 /usr/local/lib/perl/
439 ~/perl5/lib/perl5/
440  
441 Or reference it directly:
442  
443 use lib '/path/to/lib';
444 use Config::NINI;
445  
446 =head1 QUICK START
447  
448 Configuration file example (config.nini):
449  
450 = Database
451 host example.com
452 port 5432
453 user admin
454 password secret
455  
456 = Database Cache
457 & Database
458 ttl 3600
459 enabled 1
460  
461 Perl script:
462  
463 my $config = nini_parse_data( nini_load_file( 'config.nini' ), {} );
464  
465 print $config->{Database}{host}; # example.com
466 print $config->{'Database Cache'}{host}; # inherited: example.com
467  
468 =head1 FUNCTIONS
469  
470 =head2 nini_load_file( FILENAME, OPTIONS )
471  
472 Loads a NINI configuration file from disk, processing includes and
473 returning raw data as array reference.
474  
475 =over
476  
477 =item B<Arguments>
478  
479 =over
480  
481 =item FILENAME
482  
483 Path to NINI file to load (string)
484  
485 =item OPTIONS
486  
487 Hash reference with options:
488  
489 =over
490  
491 =item DIRS
492  
493 Array ref of directories to search for @include directives
494  
495 =item DL
496  
497 Array ref for debug location tracking
498  
499 =back
500  
501 =back
502  
503 =item B<Returns>
504  
505 Array reference containing parsed file lines. This must be variable, since
506 nini_load_file() will populate it and nini_parse_data() will use it to report
507 warnings and errors.
508  
509 =item B<Example>
510  
511 my $dl = [];
512 my $data = nini_load_file('app.nini', {
513 DIRS => ['/etc/config', '/home/user/.config'],
514 DL => $dl, # Enable and keep debug locations tracking
515 });
516  
517 my $nini = nini_parse_data( $data, { DL => $dl } );
518  
519 =item B<Notes>
520  
521 =over
522  
523 =item * Automatically anchors each file to root section (=)
524  
525 =item * Detects and prevents file inclusion loops
526  
527 =item * Strips trailing whitespace from all lines
528  
529 =item * Returns array of configuration directives ready for nini_parse_data
530  
531 =back
532  
533 =back
534  
535 =head2 nini_parse_data( DATA, OPTIONS )
536  
537 Parses processed configuration data into hierarchical hash structure.
538  
539 =over
540  
541 =item amazB<Arguments>
542  
543 =over
544  
545 =item DATA
546  
547 Array reference (output from nini_load_file)
548  
549 =item OPTIONS
550  
551 Hash reference with options:
552  
553 =over
554  
555 =item DEBUG
556  
557 Enable debug information (boolean)
558  
559 =item DL
560  
561 Array ref for debug location tracking. See nini_load_file() for examples and
562 explanation how it works.
563  
564 =back
565  
566 =back
567  
568 =item B<Returns>
569  
570 Hash reference containing parsed configuration structure
571  
572 =item B<Special Keys>
573  
574 The result hash contains special metadata keys:
575  
576 =over
577  
578 =item :ord
579  
580 Section sequence number (regular sections only)
581  
582 =item :origin
583  
584 Array of debug location strings (if DEBUG enabled). It includes all locations
585 in files where the parser went to gather keys information. Can be backtracked
586 to see when values are coming from.
587  
588 =item :warn
589  
590 Array of warning messages encountered
591  
592 =back
593  
594 =item B<Example>
595  
596 my $config = nini_parse_data($data, {
597 DEBUG => 1,
598 DL => $debug_locations
599 });
600  
601 # Access warnings
602 if ($config->{':warn'}) {
603 for my $w (@{$config->{':warn'}}) {
604 warn "Config warning: $w\n";
605 }
606 }
607  
608 =back
609  
610 =head1 NINI FORMAT SPECIFICATION
611  
612 =head2 Overview
613  
614 NINI files consist of:
615  
616 =over
617  
618 =item * Sections: Hierarchical organizational units
619  
620 =item * Keys: Named data elements with scalar or array values
621  
622 =item * Inheritance: Section can inherit from another section
623  
624 =item * Comments: Lines starting with #
625  
626 =item * Includes: Dynamic file inclusion with @include
627  
628 =item * Paths: Whitespace-separated hierarchical navigation
629  
630 =back
631  
632 File structure:
633  
634 =Section_Name
635 key1 value1
636 key2[,] v1, v2, v3
637 key3[|] v1 | v2 | v3
638 & Parent_Section
639  
640 =Section_Name Sub_Section_Name
641 & Other Sub_Section
642 key4 value4
643 text[] those are space delimited 6 words
644  
645 Blank lines and comment lines (starting with #) are ignored.
646  
647 =head2 Comments
648  
649 Lines starting with C<#> are treated as comments and ignored entirely.
650  
651 Lines with content are treated as-is; there is no support for trailing/inline
652 comments. Unless line begins with '#', the '#' symbol is verbatim and has no
653 special meaning.
654  
655 # port number 5566
656 port #5566
657  
658 # anywhere in-between
659 url https://www.gocomics.com/extras/first-calvin-and-hobbes-comic-strip#rulz
660  
661 =head1 SECTIONS
662  
663 =head2 Regular Sections
664  
665 Marked with C<=> (equals sign). Create new hierarchical branch.
666  
667 = Top_Level_Section
668  
669 = Top_Level_Section Sub_Section
670 (continues in parent section by default)
671  
672 = Another_Top_Level
673  
674 Whitespace-separated path components create hierarchy:
675  
676 = level1 level2 level3
677  
678 Creates Perl structure:
679  
680 %hash = (
681 level1 => {
682 level2 => {
683 level3 => { ... }
684 }
685 }
686 );
687  
688 =head2 Abstract Sections
689  
690 Marked with C<*> (asterisk). Used for dynamic array-indexed branches.
691  
692 * items # Creates branch at index 0
693 key1 value1
694  
695 * items # Creates branch at index 1
696 key2 value2
697  
698 Creates structure:
699  
700 items => {
701 *0 => { key1 => 'value1' },
702 *1 => { key2 => 'value2' }
703 }
704  
705 Auto-indexing with C<*> wildcard in path:
706  
707 = data *
708 name Widget A
709  
710 Expands C<*> to next available integer index. Integer indexes are not required
711 to be continuous. If there are 1, 5, 16 the next auto-index will be 17 etc.
712  
713 =head2 Section Modifiers
714  
715 Delete section contents using C<!> operators:
716  
717 =over
718  
719 =item C<!>
720  
721 Delete all keys.
722  
723 =item C<!!>
724  
725 Delete all sub-section branches.
726  
727 =item C<!!!>
728  
729 Delete everything (keys and branches)
730  
731 =back
732  
733 Example:
734  
735 = Section
736 key1 value1
737 branch_name branch_data
738  
739 = Section
740 !!
741 # only key1 left
742  
743 =head1 KEYS AND VALUES
744  
745 =head2 Key Syntax
746  
747 [+|-]KEY[ARRAY][WHITESPACE]VALUE
748  
749 Components:
750  
751 =over
752  
753 =item [+|-]
754  
755 Operator (optional) - Add or remove operation
756  
757 =item KEY
758  
759 Key name (required)
760  
761 Pattern: C<[a-zA-Z0-9_:\/][a-zA-Z0-9:._\/-]*>
762  
763 =item [X]
764  
765 Array indicator with delimiter (optional)
766  
767 =item VALUE
768  
769 Data value (optional, defaults to '1' if omitted)
770  
771 =back
772  
773 Examples:
774  
775 key1 # Scalar, value = '1'
776 key2 hello world # Scalar, value = 'hello world'
777 key3 [,] a,b,c # Array, comma-separated
778 key4 [|] x|y|z # Array, pipe-separated
779 key5 [ ] space separated # Array, space-separated
780 +key6 append_value # Add operation (modifier)
781  
782 =head2 Delimiters
783  
784 Array delimiter specified in C<[X]> where X is:
785  
786 =over
787  
788 =item C<,>
789  
790 Comma
791  
792 =item C<|>
793  
794 Pipe
795  
796 =item C<;>
797  
798 Semicolon
799  
800 =item C<:>
801  
802 Colon
803  
804 =item (empty)
805  
806 Whitespace (implicit)
807  
808 =back
809  
810 =head3 Quote Handling
811  
812 =over
813  
814 =item Single quotes (C<'>)
815  
816 Preserve content, remove quotes
817  
818 =item Double quotes (C<">)
819  
820 Preserve content, remove quotes
821  
822 =item Pipe quotes (C<|>)
823  
824 Preserve content, remove quotes
825  
826 =item Escaped quotes (C<"">)
827  
828 Become single quote in output
829  
830 =back
831  
832 =head2 Value Parsing
833  
834 Whitespace handling:
835  
836 =over
837  
838 =item * Leading/trailing whitespace stripped
839  
840 =item * Quoted values preserve internal whitespace
841  
842 =back
843  
844 Examples:
845  
846 key1 value with spaces
847 key2 " quoted value "
848 key3 "#hash_included"
849  
850 Results:
851  
852 key1 => 'value with spaces'
853 key2 => ' quoted value '
854 key3 => '#hash_included'
855  
856 =head1 ARRAYS
857  
858 =head2 Array Declaration
859  
860 Arrays specified with delimiter in brackets:
861  
862 array_name [DELIMITER] item1 DELIMITER item2 DELIMITER item3
863  
864 Returns Perl array reference.
865  
866 Access in code:
867  
868 my @items = @{$config->{section}{array_name}};
869 my $count = scalar @{$config->{section}{array_name}};
870 my $first = $config->{section}{array_name}->[0];
871  
872 =head2 Whitespace-Separated Arrays
873  
874 Using space as implicit delimiter:
875  
876 array_name[] one two three four
877  
878 Results in:
879  
880 array_name => ['one', 'two', 'three', 'four']
881  
882 =head2 Single-Character Delimiters
883  
884 All delimiters are single-character:
885  
886 ports[,] 8080,8081,8082,8443
887 formats[|] json|xml|csv|yaml
888 paths[:] /etc:/opt:/home
889  
890 =head2 Quote Handling in Arrays
891  
892 Quotes included in array delimiters:
893  
894 items[,] "first item", 'second item', third
895  
896 Results in:
897  
898 items => ['first item', 'second item', 'third']
899  
900 =head1 INHERITANCE
901  
902 =head2 Basic Inheritance
903  
904 Sections can inherit from other sections using C<&> operator.
905  
906 = Base
907 key1 value1
908 key2 value2
909  
910 = Derived_Section
911 & Base
912 key3 value3
913  
914 Derived Section inherits C<key1> and C<key2> from Base Section.
915  
916 Result:
917  
918 'Derived_Section' => {
919 key1 => 'value1', # inherited
920 key2 => 'value2', # inherited
921 key3 => 'value3' # own
922 }
923  
924 =head2 Inheritance Levels
925  
926 Multiple C<&> specifiers control inheritance depth:
927  
928 =over
929  
930 =item C<& SOURCE>
931  
932 Inherit keys only
933  
934 =item C<&& SOURCE>
935  
936 Inherit branches only (deep copy, no keys at the same level)
937  
938 =item C<&&& SOURCE>
939  
940 Inherit keys AND branches. Any number of '&'s beyond 2 is the same.
941  
942 =back
943  
944 =head2 Selective Inheritance
945  
946 = Parent
947 key1 value1
948 sub_branch sub_data
949  
950 = Child
951 & Parent # Inherits key1 only
952 && Parent # Inherits sub_branch only
953 &&& Parent # Inherits both
954  
955 =head2 Inherited Branch Structure
956  
957 When inheriting branches (C<&&>), nested structures are deep-copied:
958  
959 = Source
960 nested parent_value
961  
962 = Target
963 && Source # Copies entire nested structure
964  
965 Resulting structure:
966  
967 Target => {
968 nested => { ... } # Deep copy, modifications don't affect Source
969 }
970  
971 =head2 Inheritance Loops
972  
973 Since inheritance is a deep copy, loops are allowed but may lead to not
974 obvious results.
975  
976 = A
977 asd 999
978 & A
979 # no-op, silent, warning if debug
980  
981 = B
982 qwe 333
983 & A
984 # ok
985  
986 = A
987 & B
988 # still ok since deep copy, now both A and B will have asd and qwe keys
989  
990 =head1 INCLUDE DIRECTIVES
991  
992 =head2 File Inclusion
993  
994 Include other NINI files with C<@include>:
995  
996 @include filename.nini
997 @include /path/to/config.nini
998  
999 Syntax variations:
1000  
1001 @include filename.nini
1002 @include path/to/file.nini
1003 @include /absolute/path/file.nini
1004  
1005 =head2 Directory Search
1006  
1007 Specify search directories in OPTIONS:
1008  
1009 my $config = nini_parse_data(
1010 nini_load_file('main.nini', {
1011 DIRS => [
1012 '/etc/app',
1013 '/opt/app/config',
1014 '/home/user/.app'
1015 ]
1016 }),
1017 {}
1018 );
1019  
1020 If C<@include> uses relative path, directories are searched in order.
1021 First match wins. Absolute paths (starting with C</>) used directly.
1022  
1023 =head2 Include Context
1024  
1025  
1026 When including a file, the context will be forced to be the root section.
1027 When exit included file, the previous secont will be restored. This is needed
1028 so that all keys at the beginning of the included file will not be injected
1029 into the current section of the base file and all keys after the include
1030 will not be attached into the last section of the include file:
1031  
1032 = Mid_Section
1033 # all leading keys of included.nini will be forced to be in the root
1034 @include included.nini
1035 # key1 will be into "Mid_Section", not in the last open section in
1036 # included.nini
1037 key1 value1
1038  
1039 This behaviour was selected to match close the "what you (probably) expect is
1040 what you get" :)
1041  
1042 =head2 Loop Detection
1043  
1044 Circular includes are detected and prevented:
1045  
1046 # file1.nini
1047 @include file2.nini
1048  
1049 # file2.nini
1050 @include file1.nini
1051  
1052 Attempting to load file1.nini will error:
1053  
1054 nini: error: file load: loop detected for file [file1.nini]
1055  
1056 =head2 Include Failure Handling
1057  
1058 If included file not found:
1059  
1060 =over
1061  
1062 =item * Silent skip (no error, warning if debug)
1063  
1064 =item * Processing continues with next line
1065  
1066 =item * No explicit error message (can enable via DEBUG)
1067  
1068 =back
1069  
1070 =head1 PATH RESOLUTION
1071  
1072 =head2 Path Navigation
1073  
1074 Paths are whitespace-separated section names:
1075  
1076 = level1 level2 level3
1077 key value
1078  
1079 Creates:
1080  
1081 level1/level2/level3/key => value
1082  
1083 =head2 Path Syntax
1084  
1085 Valid path elements:
1086  
1087 [A-Za-z0-9:._\/-]+ # Alphanumeric with special chars
1088 * # Auto-index wildcard
1089 ! # Delete key modifier
1090 !! # Delete branch modifier
1091 !!! # Delete all modifier
1092  
1093 =head2 Deleting Path Elements
1094  
1095 Single C<!> deletes matching keys:
1096  
1097 = section
1098 # Remove all keys in section, mostly for debug or temporary purpose
1099 !
1100  
1101 Double C<!!> deletes matching branches:
1102  
1103 = section
1104 # Remove all branches
1105 !!
1106  
1107 Triple C<!!!> deletes both:
1108  
1109 = section
1110 # Remove everything
1111 !!!
1112  
1113 =head2 Auto-Indexing with *
1114  
1115 Wildcard C<*> finds next available numeric index:
1116  
1117 = items *
1118 name First
1119  
1120 = items *
1121 name Second
1122  
1123 Sections become:
1124  
1125 'items' => {
1126 1 => { name => 'First' },
1127 2 => { name => 'Second' }
1128 }
1129  
1130 =head1 OPTIONS AND DEBUG TRACKING
1131  
1132 =head2 Load Options
1133  
1134 C<nini_load_file> OPTIONS hash:
1135  
1136 =over
1137  
1138 =item DIRS
1139  
1140 Array ref of directories for C<@include> search
1141  
1142 =item DL
1143  
1144 Array ref to collect debug locations
1145  
1146 =back
1147  
1148 Example:
1149  
1150 my @locations;
1151 my $data = nini_load_file('app.nini', {
1152 DIRS => ['/etc', '/home/user'],
1153 DL => \@locations
1154 });
1155  
1156 # @locations now contains file:line information for each line
1157  
1158 =head2 Parse Options
1159  
1160 C<nini_parse_data> OPTIONS hash:
1161  
1162 =over
1163  
1164 =item DEBUG
1165  
1166 Enable debug collection (boolean)
1167  
1168 =item DL
1169  
1170 Array ref for debug location strings
1171  
1172 =back
1173  
1174 Example:
1175  
1176 my @locations;
1177 my $config = nini_parse_data($data, {
1178 DEBUG => 1,
1179 DL => \@locations
1180 });
1181  
1182 =head2 Debug Information
1183  
1184 =over
1185  
1186 =item :ord
1187  
1188 Integer sequence number (regular sections only).
1189 Reflects section order in file.
1190  
1191 =item :origin
1192  
1193 Array ref of location strings.
1194 Each location: "filename line N" or "filename top/bottom"
1195  
1196 Exists only when DEBUG is enabled.
1197  
1198 =item :warn
1199  
1200 Array ref of warning messages.
1201 Includes unresolved inherits, self-reference attempts, etc.
1202  
1203 Exists only when DEBUG is enabled.
1204  
1205 =back
1206  
1207 Accessing debug info:
1208  
1209 for my $origin (@{$config->{section}{':origin'}}) {
1210 print "Defined at: $origin\n";
1211 }
1212  
1213 if (exists $config->{':warn'}) {
1214 for my $warning (@{$config->{':warn'}}) {
1215 warn "Config warning: $warning\n";
1216 }
1217 }
1218  
1219 =head2 Error Messages
1220  
1221 Error messages include context:
1222  
1223 nini: error: file load: loop detected for file [FILE]
1224 nini: error: syntax error in data [LINE] at LOCATION
1225 nini: error: unrecognisable data [LINE] at LOCATION
1226 nini: error: cannot inherit parent branch into current at LOCATION
1227  
1228 =head1 EXAMPLES
1229  
1230 =head2 Simple Configuration
1231  
1232 File: C<database.nini>
1233  
1234 = Database
1235 host localhost
1236 port 5432
1237 user dbuser
1238 password secure_pass
1239 options[,] ssl,compression,timeout
1240  
1241 Perl:
1242  
1243 my $cfg = nini_parse_data( nini_load_file( 'database.nini' ) );
1244  
1245 print $cfg->{Database}{host}; # localhost
1246 print $cfg->{Database}{port}; # 5432
1247  
1248 my @opts = @{$cfg->{Database}{options}};
1249 # @opts = ('ssl', 'compression', 'timeout')
1250  
1251 =head2 Hierarchical Configuration
1252  
1253 File: C<app.nini>
1254  
1255 = Application
1256 name MyApp
1257 version 1.0
1258  
1259 = Application Database
1260 host db.example.com
1261 port 5432
1262  
1263 = Application Cache
1264 enabled 1
1265 ttl 3600
1266  
1267 Perl:
1268  
1269 my $cfg = nini_parse_data( nini_load_file('app.nini') );
1270  
1271 print $cfg->{Application}{name};
1272 print $cfg->{Application}{Database}{host};
1273 print $cfg->{Application}{Cache}{enabled};
1274  
1275 =head2 Inheritance
1276  
1277 File: C<servers.nini>
1278  
1279 = Default Server
1280 user ubuntu
1281 ssh_key_file /home/ubuntu/.ssh/id_rsa
1282 timeout 30
1283  
1284 = Production Web Server
1285 & Default Server
1286 hostname prod-web-01
1287 ip_address 192.168.1.100
1288 cpu_count 8
1289  
1290 = Staging Web Server
1291 & Default Server
1292 hostname staging-web-01
1293 ip_address 192.168.1.101
1294 cpu_count 4
1295  
1296 Perl:
1297  
1298 my $cfg = nini_parse_data( nini_load_file('servers.nini') );
1299  
1300 my $prod = $cfg->{'Production Web Server'};
1301 print $prod->{user}; # Inherited: ubuntu
1302 print $prod->{hostname}; # Own: prod-web-01
1303 print $prod->{timeout}; # Inherited: 30
1304  
1305 =head2 Arrays and Delimiters
1306  
1307 File: C<services.nini>
1308  
1309 = Services
1310 tcp_ports[,] 22,80,443,8080
1311 http_methods[|] GET|POST|PUT|DELETE
1312 workers[] worker1 worker2 worker3
1313  
1314 Perl:
1315  
1316 my $cfg = nini_parse_data( nini_load_file('services.nini') );
1317  
1318 my @tcp = @{ $cfg->{Services}{tcp_ports} };
1319 # @tcp = ('22', '80', '443', '8080')
1320  
1321 my @methods = @{$cfg->{Services}{http_methods}};
1322 # @methods = ('GET', 'POST', 'PUT', 'DELETE')
1323  
1324 my @w = @{ $cfg->{Services}{workers} };
1325 # @w = ('worker1', 'worker2', 'worker3')
1326  
1327 =head2 File Inclusion
1328  
1329 File: C<main.nini>
1330  
1331 = Application
1332 name MyApp
1333  
1334 @include database.nini
1335 @include services.nini
1336  
1337 File: C<database.nini>
1338  
1339 = Application Database
1340 host localhost
1341 port 5432
1342  
1343 File: C<services.nini>
1344  
1345 = Application Services
1346 api_port 8000
1347  
1348 Perl:
1349  
1350 my $cfg = nini_parse_data(
1351 nini_load_file('main.nini', {
1352 DIRS => ['.']
1353 }),
1354 {}
1355 );
1356  
1357 print $cfg->{Application}{name};
1358 print $cfg->{Application}{Database}{host};
1359 print $cfg->{Application}{Services}{api_port};
1360  
1361 =head2 Abstract Sections and Auto-Indexing
1362  
1363 File: C<items.nini>
1364  
1365 inventory *
1366 name Laptop
1367 quantity 5
1368 price 1200
1369  
1370 inventory *
1371 name Mouse
1372 quantity 25
1373 price 50
1374  
1375 inventory *
1376 name Monitor
1377 quantity 10
1378 price 350
1379  
1380 Perl:
1381  
1382 my $cfg = nini_parse_data(
1383 nini_load_file('items.nini'),
1384 {}
1385 );
1386  
1387 # Access by numeric index
1388 for my $i (0..2) {
1389 my $key = "$i";
1390 my $item = $cfg->{inventory}{$key};
1391 print "$item->{name}: $item->{quantity}\n";
1392 }
1393  
1394 Output:
1395  
1396 Laptop: 5
1397 Mouse: 25
1398 Monitor: 10
1399  
1400 =head2 Debug Information
1401  
1402 File: C<config.nini>
1403  
1404 = Section1
1405 key1 value1
1406  
1407 = Section2
1408 & NonExistent
1409  
1410 Perl:
1411  
1412 my @locations;
1413 my $cfg = nini_parse_data(
1414 nini_load_file('config.nini', { DL => \@locations }),
1415 { DEBUG => 1, DL => \@locations }
1416 );
1417  
1418 # Check for warnings
1419 if (exists $cfg->{':warn'}) {
1420 for my $w (@{$cfg->{':warn'}}) {
1421 print "Warning: $w\n";
1422 }
1423 }
1424  
1425 Output:
1426  
1427 Warning: cannot find path to inherit [NonExistent] at config.nini line 5
1428  
1429 =head1 ERROR HANDLING
1430  
1431 =head2 Fatal Errors
1432  
1433 Parser dies on:
1434  
1435 =over
1436  
1437 =item * Syntax errors in key/value lines
1438  
1439 =item * Unrecognizable data format
1440  
1441 =item * File load loop detection
1442  
1443 =item * Invalid inheritance (circular references)
1444  
1445 =item * Self-inheritance attempts
1446  
1447 =back
1448  
1449 Use eval to catch:
1450  
1451 my $cfg;
1452 eval {
1453 $cfg = nini_parse_data(
1454 nini_load_file('config.nini'),
1455 {}
1456 );
1457 };
1458  
1459 if ($@) {
1460 die "Failed to load config: $@\n";
1461 }
1462  
1463 =head2 Non-Fatal Issues
1464  
1465 Warnings collected in C<:warn> key:
1466  
1467 =over
1468  
1469 =item * Cannot find path to inherit
1470  
1471 =item * Self-inheritance attempted
1472  
1473 =item * Invalid optional syntax
1474  
1475 =back
1476  
1477 Access warnings:
1478  
1479 if (exists $config->{':warn'}) {
1480 for my $warning (@{$config->{':warn'}}) {
1481 warn "Config issue: $warning\n";
1482 }
1483 }
1484  
1485 =head2 Common Issues and Solutions
1486  
1487 =head3 Value contains # character
1488  
1489 Solution: Quote the value
1490  
1491 key1 "#important" # Value is: #important
1492 key2 "URL: http://..." # Value is: URL: http://...
1493  
1494 =head3 Array parsing fails
1495  
1496 Solution: Ensure separator is single character and matches usage
1497  
1498 correct: items [,] a,b,c
1499 wrong: items [,] a, b, c # Spaces included in values
1500 solution: items [,] a, b, c # Use proper format
1501  
1502 =head3 Include file not found
1503  
1504 Solution: Verify DIRS paths or use absolute paths
1505  
1506 Relative: @include config.nini
1507 Absolute: @include /etc/app/config.nini
1508  
1509 =head3 Inheritance path not found
1510  
1511 Solution: Ensure section exists and is defined before use
1512  
1513 = Parent Section
1514 key1 value1
1515  
1516 = Child Section
1517 & Parent Section
1518 key2 value2
1519  
1520 =head1 DEPENDENCIES
1521  
1522 NINI uses dclone() from Storable module.
1523  
1524 =head1 AUTHOR
1525  
1526 Copyright: 2026 (c) Vladi Belperchinov-Shabanski "Cade" E<lt>cade@noxrun.comE<gt>
1527  
1528 =head1 LICENSE
1529  
1530 This module is distributed under the terms of the GNU General Public License,
1531 version 2 (GPLv2). See http://www.gnu.org/licenses/gpl-2.0.html for details.
1532  
1533 =cut