blib/lib/Config/Abstraction.pm

filter: Statementstmt 90.3% 962 / 1065 Branchbran 83.4% 639 / 766 Conditioncond 71.2% 203 / 285 MC/DCmcdc 56.7% 97 / 171 Subroutinesub 98.2% 57 / 58 Podpod 100% 11 / 11 totaltotal 83.5% 1969 / 2356 CC 508 SCAR 47.3
CC
508
Cov
85%
_load_config
331.0
_parse_file
181.9
new
36.1
CRAP 113.5
↑ Summary
1 package Config::Abstraction;
2  
3 # TODO: import from __DATA__ like Config::Auto in Geo::Coder::Free
4  
5 22 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 22 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 22 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 22 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 22 ▶use JSON::MaybeXS 'decode_json'; # Doesn't behave well with require
Subroutine BEGIN: called CC=1 SCAR=0.0
11 22 ▶use File::Basename ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 22 ▶use File::Slurp qw(read_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 22 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 22 ▶use Hash::Merge qw(merge);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 22 ▶use Params::Get 0.15;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 22 ▶use Params::Validate::Strict 0.37;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 22 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 22 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 # AES-256-GCM constants - do not change without updating _decrypt_enc_value and encrypt_value
21 22 Readonly::Scalar my $_AES_NONCE_SIZE => 12; # GCM standard nonce length in bytes
22 22 Readonly::Scalar my $_AES_TAG_SIZE => 16; # GCM authentication tag length in bytes
23 22 Readonly::Scalar my $_AES_KEY_SIZE => 32; # AES-256 key length in bytes
24 22 Readonly::Scalar my $_ENC_PAYLOAD_MIN => 28; # shortest valid payload: nonce(12) + tag(16)
25 22 Readonly::Scalar my $_HEX_KEY_LEN => 64; # 32 bytes expressed as hexadecimal
26 22 Readonly::Scalar my $_B64_KEY_MIN => 43; # minimum base64/base64url chars for 32 bytes
27 22 Readonly::Scalar my $_B64_KEY_MAX => 44; # maximum base64/base64url chars for 32 bytes
28  
29 # The running script, resolved when the module is loaded, while a relative $0
30 # still means what it did when the program started. Undef under perl -e and
31 # the like. _load_config() never reads this file as configuration.
32 22 ▶Readonly::Scalar my $_RUNNING_SCRIPT => ((defined($0) && (-f $0)) ? Cwd::abs_path($0) : undef);
Branch: 1 branch
BranchTrueFalseTotal
defined $0 && -f $0 ? : 22 0 22
Condition33%1/3
defined $0 and -f $0
!ll&&!rl&&r
0022
MC/DC0%0/2
defined $0 and -f $0
defined $0 -f $0
Truth table33%1/3
A and B
A= defined $0B= -f $0
ABresult
0X0
100
111
33  
34 =head1 NAME
35  
36 Config::Abstraction - Merge and manage configuration data from different sources
37  
38 =head1 VERSION
39  
40 Version 0.43
41  
42 =cut
43  
44 22 our $VERSION = '0.43';
45  
46 =head1 SYNOPSIS
47  
48 =head2 Pattern 1: Environment overrides file overrides in-code defaults
49  
50 The most common pattern for twelve-factor-style apps.
51 The C<data> argument supplies defaults, a YAML file supplies site configuration,
52 and environment variables allow per-deployment overrides without touching any file.
53  
54 # config/base.yaml
55 # database:
56 # host: db.example.com
57 # port: 5432
58 # user: app
59  
60 use Config::Abstraction;
61  
62 my $config = Config::Abstraction->new(
63 data => { database => { host => 'localhost', port => 5432 } },
64 config_dirs => ['config'],
65 env_prefix => 'APP_',
66 );
67  
68 # In production, set APP_DATABASE__HOST=db.prod.example.com in the environment.
69 # That silently overrides the file value, which in turn overrides the default.
70 my $host = $config->get('database.host');
71 my $port = $config->get('database.port');
72  
73 =head2 Pattern 2: Command-line arguments override everything
74  
75 Useful for CLI tools where operator flags must win over every other source.
76  
77 # Run as: myscript.pl --APP_LOGLEVEL=debug --APP_DATABASE__HOST=localhost
78  
79 use Config::Abstraction;
80  
81 my $config = Config::Abstraction->new(
82 config_dirs => ['config'],
83 env_prefix => 'APP_',
84 );
85  
86 # @ARGV is consumed and stripped during new(); the resulting config already
87 # has cli-layer values at the highest precedence.
88 my $loglevel = $config->get('loglevel'); # 'debug' (from --APP_LOGLEVEL)
89 my $db_host = $config->get('database.host'); # 'localhost' (from --APP_DATABASE__HOST)
90  
91 =head2 Pattern 3: Multi-file layering (base + local override)
92  
93 Separates shared defaults from machine-specific tweaks.
94 Every developer has a C<base.yaml>; only the production server has C<local.yaml>.
95  
96 # config/base.yaml -- checked into version control
97 # database:
98 # host: localhost
99 # user: dev
100 #
101 # config/local.yaml -- NOT checked in; production only
102 # database:
103 # host: db.prod.example.com
104 # user: produser
105 # password: s3cr3t
106  
107 use Config::Abstraction;
108  
109 my $config = Config::Abstraction->new(
110 config_dirs => ['config'], # loads base.yaml then local.yaml
111 env_prefix => 'APP_',
112 );
113  
114 # On a dev machine (no local.yaml): host='localhost', user='dev'
115 # On the prod server: host='db.prod.example.com', user='produser'
116 my $db = $config->get('database.host');
117 my $user = $config->get('database.user');
118  
119 =head1 DESCRIPTION
120  
121 C<Config::Abstraction> is a flexible configuration management layer that sits above C<Config::*> modules.
122 It provides a simple way to layer multiple configuration sources with predictable merge order.
123 It lets you define sources such as:
124  
125 =over 4
126  
127 =item * Perl hashes (in-memory defaults or dynamic values)
128  
129 =item * Environment variables (with optional prefixes)
130  
131 =item * Configuration files (YAML, JSON, INI, or plain key=value)
132  
133 =item * Command-line arguments
134  
135 =back
136  
137 Sources are applied in the order they are provided. Later sources override
138 earlier ones unless a key is explicitly set to C<undef> in the later source.
139  
140 In addition to using drivers to load configuration data from multiple file
141 formats (YAML, JSON, XML, and INI),
142 it also allows levels of configuration, each of which overrides the lower levels.
143 So, it also integrates environment variable
144 overrides and command line arguments for runtime configuration adjustments.
145 This module is designed to help developers manage layered configurations that can be loaded from files and overridden at run-time for debugging,
146 offering a modern, robust and dynamic approach
147 to configuration management.
148  
149 =head2 Merge Precedence
150  
151 Sources are applied in the order shown below. Each row wins over every row
152 above it. When the same key appears in multiple sources, the highest-priority
153 source always determines the final value - including when that value is C<undef>.
154  
155 Priority Source Set with
156 -------- ------ --------
157 1 (lo) data constructor argument data => { key => 'default' }
158 2 base.* config files config/base.yaml, base.json, ...
159 3 base.{env}.* config files config/base.prod.yaml, ...
160 4 local.* config files config/local.yaml, local.json, ...
161 5 local.{env}.* config files config/local.prod.yaml, ...
162 6 default / script-name files config/default.yaml, myapp.yaml, ...
163 7 config_file / config_files config_file => '/etc/myapp.yaml'
164 8 Environment variables APP_DATABASE__HOST=db.prod.example.com
165 9 (hi) CLI arguments (@ARGV) --APP_DATABASE__HOST=db.prod.example.com
166  
167 The active environment is set by the C<environment> constructor option, or
168 auto-detected from C<{env_prefix}ENV> (e.g. C<APP_ENV>), C<PLACK_ENV>, or
169 C<NODE_ENV>. When no environment is configured, rows 3 and 5 are skipped.
170  
171 Within the file tier (rows 2-7), later files override earlier files using
172 C<Hash::Merge> LEFT_PRECEDENT: every key in the later file wins over the same
173 key in an earlier file, even when the later value is C<undef> (YAML C<~>).
174 Nested hashes are merged recursively, so a C<local.yaml> that only sets
175 C<database.host> will not erase C<database.port> from C<base.yaml>.
176  
177 Example - what wins for the key C<database.host> when APP_ENV=prod:
178  
179 data => 'localhost' (overridden by base.yaml)
180 base.yaml => 'db.example.com' (overridden by base.prod.yaml)
181 base.prod.yaml => 'db.prod.example.com' (overridden by local.yaml)
182 local.yaml => 'db.local.example.com' (overridden by local.prod.yaml)
183 local.prod.yaml => 'db.prod-local.example.com' (overridden by $APP_DATABASE__HOST)
184 $APP_DATABASE__HOST => 'db.override.example.com' <-- this wins
185  
186 =head2 KEY FEATURES
187  
188 =over 4
189  
190 =item * Multi-Format Support
191  
192 Supports configuration files in YAML, JSON, XML, and INI formats.
193 Automatically merges configuration data from these different formats,
194 allowing hierarchical configuration management.
195  
196 =item * Environment Variable Overrides
197  
198 Allows environment variables to override values in the configuration files.
199 By setting environment variables with a specific prefix (default: C<APP_>),
200 values in the configuration files can be dynamically adjusted without modifying
201 the file contents.
202  
203 =item * Flattened Configuration Option
204  
205 Optionally supports flattening the configuration structure. This converts deeply
206 nested configuration keys into a flat key-value format (e.g., C<database.user>
207 instead of C<database-E<gt>{user}>). This makes accessing values easier for
208 applications that prefer flat structures or need compatibility with flat
209 key-value stores.
210  
211 =item * Layered Configuration
212  
213 Supports merging multiple layers of configuration files. For example, you can
214 have a C<base.yaml> configuration file that provides default values, and a
215 C<local.yaml> (or C<local.json>, C<local.xml>, etc.) file that overrides
216 specific values. This allows for environment-specific configurations while
217 keeping defaults intact.
218  
219 =item * Merge Strategy
220  
221 The module merges the configuration data intelligently, allowing values in more
222 specific files (like C<local.yaml>, C<local.json>, C<local.xml>, C<local.ini>)
223 to override values in base files. This enables a flexible and layered configuration
224 system where you can set defaults and override them for specific environments.
225  
226 =item * Error Handling
227  
228 Includes error handling for loading configuration files.
229 If any file fails to
230 load (e.g., due to syntax issues), the module will throw descriptive error
231 messages to help with debugging.
232  
233 =item * Centralized Configuration Management
234  
235 Supports remote configuration management files,
236 so that configuration on remote machines can be centrally managed.
237  
238 =back
239  
240 =head2 SUPPORTED FILE FORMATS
241  
242 =over 4
243  
244 =item * YAML (C<*.yaml>, C<*.yml>)
245  
246 Loaded with L<YAML::XS>.
247  
248 =item * JSON (C<*.json>)
249  
250 Loaded with L<JSON::MaybeXS>.
251  
252 =item * XML (C<*.xml>)
253  
254 Loaded with L<XML::Simple> (preferred) or L<XML::PP> (fallback).
255  
256 =item * INI (C<*.ini>)
257  
258 Loaded with L<Config::IniFiles>.
259  
260 =item * TOML (C<*.toml>)
261  
262 Loaded with L<TOML::Tiny>, which implements TOML 1.0. TOML is a good choice
263 for human-editable configuration because its syntax is unambiguous: all values
264 are typed, strings must be quoted, and nesting uses C<[section]> headers or
265 dotted keys rather than indentation.
266  
267 # Example: config/base.toml
268 [database]
269 host = "db.example.com"
270 port = 5432
271 user = "app"
272  
273 [cache]
274 ttl = 300
275 debug = false
276  
277 C<base.toml> and C<local.toml> are discovered automatically in C<config_dirs>;
278 C<local.toml> has higher precedence than C<base.toml>, following the same
279 layering rules as all other formats. TOML is also tried as a fallback parser
280 in the all-parsers chain used for extensionless C<config_file> entries.
281  
282 If C<TOML::Tiny> is not installed, TOML files are silently skipped with a
283 C<carp> warning.
284  
285 =item * Apache-style (C<*.conf>)
286  
287 Loaded with L<Config::General>, which is optional. C<base.conf>,
288 C<local.conf> and their environment-specific forms are discovered like the
289 other formats, and Config::General is the last parser tried for an
290 extensionless C<config_file>. If it is not installed, C<.conf> files are
291 skipped.
292  
293 name = myapp
294 log debug
295 log trace # repeated keys become an array
296 <database>
297 host = db.example.com
298 port = 5432
299 </database>
300 <host www.example.com> # a named block nests one level further
301 root /var/www
302 </host>
303  
304 Config::General's own C<E<lt>E<lt>include ...E<gt>E<gt>> directive is B<not>
305 honoured, and a file that uses it is skipped with a warning, because it reads
306 any file the process can read. Use the C<include> key described under
307 L</INCLUDING FILES> instead. Config::General's variable interpolation is
308 switched off in favour of L</VARIABLE INTERPOLATION>.
309  
310 Apache-style content has C<E<lt>blockE<gt>...E<lt>/blockE<gt>> tags that look
311 like XML. When an extensionless C<config_file> that does not begin with an
312 C<E<lt>?xmlE<gt>> declaration fails to parse as XML, it is given one attempt
313 as Apache-style configuration before the XML error is reported.
314  
315 =back
316  
317 =head2 INCLUDING FILES
318  
319 With C<allow_includes =E<gt> 1>, a configuration file may name other files
320 in a top-level C<include> key (a path, a glob, or an arrayref of them):
321  
322 # base.yaml
323 include:
324 - defaults/common.yaml
325 - conf.d/*.json
326 name: myapp
327  
328 Any format may include any other. The included files are merged I<under> the
329 file that includes them, so the including file wins over its includes and,
330 of several includes, the later one wins over the earlier. Globs are expanded
331 in sorted order. A relative path is taken relative to the including file, not
332 to the current directory. Included files appear in C<config_path> and, with
333 their own entries, in C<explain_sources()>.
334  
335 Because an include is a way to make the module read a file, it is confined:
336 an included file must be within the directory of the file that began the
337 chain (any depth below it), or within a directory listed in C<include_dirs>.
338 Symbolic links are resolved before the check. A file outside those
339 directories, a circular include, or a chain deeper than C<include_max_depth>
340 croaks. An include that does not exist is skipped with a warning.
341  
342 The key name can be changed with C<include_key>. A glob that matches no
343 file is silently ignored, whereas an explicit path that does not exist warns.
344 A file that starts with C<#!> is a program and is never read as an include, and
345 the running script is never included. An included file with an unrecognised
346 extension is detected by its content (JSON, YAML, TOML, then Apache-style).
347  
348 Includes are not followed in files fetched from remote directories
349 (Newcastle Connection).
350  
351 =head2 VARIABLE INTERPOLATION
352  
353 With C<interpolate =E<gt> 1>, string values may refer to other values:
354  
355 database:
356 host: db.example.com
357 port: 5432
358 dsn: "dbi:Pg:host=${database.host};port=${database.port}"
359 home: "${env:HOME}/app"
360 lang: "${env:LANG:-C}"
361 cost: "$$5" # a literal $5
362  
363 =over 4
364  
365 =item * C<${a.b}> -- the value of the configuration key C<a.b> (always C<.>-separated, whatever C<sep_char> is)
366  
367 =item * C<${env:NAME}> -- the environment variable C<NAME>
368  
369 =item * C<${...:-default}> -- C<default> when the key or variable is missing
370  
371 =item * C<$$> -- a literal C<$>
372  
373 =back
374  
375 Expansion happens after every source (files, includes, environment, command
376 line) has been merged, so a reference sees the final value of its key, and
377 references may chain. A bare C<$name> is not special. Values that are
378 C<ENC[...]> tokens are left alone, so a secret can be referred to only after
379 decryption by not referring to it. An undefined key or variable, a circular
380 reference, or a reference to a hash or array croaks, unless
381 C<interpolate_strict> is false. The caller's C<data> hashref is never
382 modified.
383  
384 Turn this on only for configuration you trust: a value taken from an
385 environment variable or command-line argument that contains
386 C<${env:NAME}> will be expanded too.
387  
388 =head2 ENVIRONMENT VARIABLE HANDLING
389  
390 Configuration values can be overridden via environment variables. Environment variables use double underscores (__) to denote nested configuration keys and single underscores remain as part of the key name under the prefix namespace.
391  
392 For example:
393  
394 APP_DATABASE__USER becomes database.user (nested structure)
395  
396 $ export APP_DATABASE__USER="env_user"
397  
398 will override any value set for `database.user` in the configuration files.
399  
400 APP_LOGLEVEL becomes APP.loglevel (flat under prefix namespace)
401  
402 APP_API__RATE_LIMIT becomes api.rate_limit (mixed usage)
403  
404 This allows you to override both top-level and nested configuration values using environment variables.
405  
406 Configuration values can be overridden via the command line (C<@ARGV>).
407 For instance, if you have a key in the configuration such as C<database.user>,
408 you can override it by adding C<"--APP_DATABASE__USER=other_user_name"> to the command line arguments.
409 This will override any value set for C<database.user> in the configuration files.
410  
411 =head2 EXAMPLE CONFIGURATION FLOW
412  
413 =over 4
414  
415 =item 1. Data Argument
416  
417 The data passed into the constructor via the C<data> argument is the starting point.
418 Essentially,
419 this contains the default values.
420  
421 =item 2. Loading Files
422  
423 The module then looks for configuration files in the specified directories.
424 It loads the following files in order of preference:
425 C<base.yaml>, C<local.yaml>, C<base.json>, C<local.json>, C<base.xml>,
426 C<local.xml>, C<base.ini>, and C<local.ini>.
427  
428 If C<config_file> or C<config_files> is set, those files are loaded last.
429  
430 If no C<config_dirs> is given,
431 C<Config::Abstraction> tries hard to find the files in various places.
432  
433 The value of C<config_dirs> can be overridden at runtime by the environment variable CONFIG_DIR
434 (note that is just one directory, hence it's CONFIG_DIR not CONFIG_DIRS).
435  
436 =item 3. Merging and Resolving
437  
438 The module merges the contents of these files, with more specific configurations
439 (e.g., C<local.*>) overriding general ones (e.g., C<base.*>).
440  
441 =item 4. Environment Overrides
442  
443 After loading and merging the configuration files,
444 the environment variables are
445 checked and used to override any conflicting settings.
446  
447 =item 5. Command Line
448  
449 Next, the command line arguments are checked and used to override any conflicting settings.
450  
451 =item 6. Accessing Values
452  
453 Values in the configuration can be accessed using a dotted notation
454 (e.g., C<'database.user'>), regardless of the file format used.
455  
456 =back
457  
458 =head1 METHODS
459  
460 =head2 new
461  
462 Constructor for creating a new configuration object.
463  
464 Options:
465  
466 =over 4
467  
468 =item * C<config_dirs>
469  
470 An arrayref of directories to look for configuration files
471 (default: C<$CONFIG_DIR>, C<$HOME/.conf>, C<$HOME/config>, C<$HOME/conf>, C<$DOCUMENT_ROOT/conf>, C<$DOCUMENT_ROOT/../conf>, C<conf>).
472  
473 For centralised configuration management,
474 entries beginning with C</../> are treated as remote specifications using the
475 Newcastle Connection convention -- see L</Remote configuration directories (Newcastle Connection)>.
476  
477 =item * C<config_file>
478  
479 Points to a configuration file of any format.
480  
481 =item * C<config_files>
482  
483 An arrayref of files to look for in the configuration directories.
484 Put the more important files later,
485 since later files override earlier ones.
486  
487 Considers the files C<default> and C<$script_name> before looking at C<config_file> and C<config_files>.
488  
489 The running script itself is never read as configuration, even when one of the
490 configuration directories is the directory it is in, and neither is any file
491 that starts with C<#!>, since such a file is a program rather than
492 configuration, and the Perl parser would run it.
493  
494 =item * C<data>
495  
496 A hash ref of default data to prime the configuration with.
497 These are applied before loading
498 other sources and can be overridden by later sources or by explicitly passing
499 options directly to C<new>.
500  
501 $config = Config::Abstraction->new(
502 data => {
503 log_level => 'info',
504 retries => 3,
505 }
506 );
507  
508 =item * C<defaults>
509  
510 A hash reference that provides default values for the object's own attributes (such as C<config_dirs>, C<logger>, C<flatten>, etc.).
511 If this option is supplied,
512 the object is initialized using the keys in this hash as the base;
513 any other options passed directly to C<new()> (aside from C<env_prefix>) are ignored.
514 This allows you to pre-define a standard configuration profile for the object itself.
515 Note that C<defaults> is distinct from the C<data> option - C<data> supplies the initial configuration values that will be merged with files, environment, and command line,
516 while C<defaults> sets the object's internal parameters.
517 The C<env_prefix> value,
518 if provided as a top-level argument,
519 still takes precedence over any C<env_prefix> that might exist inside the C<defaults> hash.
520  
521 =item * C<encryption_key>
522  
523 A 256-bit (32-byte) AES key used to transparently decrypt C<ENC[...]> values found in any
524 configuration source after the full merge. The key may be supplied as:
525  
526 =over 4
527  
528 =item 32 raw bytes
529  
530 =item 64 lowercase or uppercase hex characters
531  
532 =item 44 Base64 or Base64url characters (standard or URL-safe alphabet, with or without trailing C<=>)
533  
534 =back
535  
536 If no key is configured (and neither C<encryption_key_file> nor the corresponding
537 environment variables are set), C<ENC[...]> tokens are left as literal strings.
538 Decryption requires L<CryptX> (C<Crypt::AuthEnc::GCM>); if that module is absent a
539 C<croak> is raised when an encrypted value is encountered.
540  
541 See L</ENCRYPTED VALUES> for the full workflow.
542  
543 =item * C<encryption_key_file>
544  
545 Path to a file whose first line contains the encryption key in any of the formats accepted
546 by C<encryption_key>. Takes precedence over the C<ENCRYPTION_KEY_FILE> and
547 C<{env_prefix}ENCRYPTION_KEY_FILE> environment variables, but is overridden by a key
548 supplied directly via C<encryption_key>.
549  
550 =item * C<env_prefix>
551  
552 A prefix for environment variable keys and comment line options, e.g. C<MYAPP_DATABASE__USER>,
553 (default: C<'APP_'>).
554  
555 =item * C<environment>
556  
557 The name of the active deployment environment (e.g. C<'dev'>, C<'staging'>, C<'prod'>).
558 When set, config files named C<base.{env}.*> are loaded immediately after their C<base.*>
559 equivalents, and C<local.{env}.*> files are loaded immediately after C<local.*> files,
560 giving two additional override tiers at no cost to the base configuration.
561  
562 my $cfg = Config::Abstraction->new(
563 config_dirs => ['config'],
564 environment => 'prod', # loads base.prod.yaml, local.prod.yaml, ...
565 );
566  
567 If C<environment> is not given, the value is auto-detected in this order:
568  
569 =over 4
570  
571 =item 1. C<{env_prefix}ENV> environment variable (e.g. C<APP_ENV>)
572  
573 =item 2. C<PLACK_ENV>
574  
575 =item 3. C<NODE_ENV>
576  
577 =back
578  
579 When none of these is set, the environment-specific tiers are silently skipped.
580 The environment name must contain only ASCII letters, digits, hyphens, and underscores
581 (matched against C</^[A-Za-z0-9_\-]+$/>); any other value causes a C<croak>.
582  
583 =item * C<file>
584  
585 Synonym for C<config_file>
586  
587 =item * C<flatten>
588  
589 If true, returns a flat hash structure like C<{database.user}> (default: C<0>) instead of C<{database}{user}>.
590 `
591 =item * C<allow_includes>
592  
593 If true, a top-level C<include> key in any configuration file (YAML, JSON,
594 XML, INI, TOML or Apache-style) names further file(s) to read and merge in.
595 It is off by default, because an existing configuration may already use a key
596 called C<include> for something else. See L</INCLUDING FILES>.
597  
598 =item * C<include_key>
599  
600 The name of the key that holds the files to include (default: C<include>).
601  
602 =item * C<include_dirs>
603  
604 A directory, or an arrayref of directories, from which files may be included
605 in addition to the directory of the including file. See L</INCLUDING FILES>.
606  
607 =item * C<include_max_depth>
608  
609 How deeply includes may nest before the constructor croaks (default: 10).
610  
611 =item * C<interpolate>
612  
613 If true, C<${...}> references in string values are expanded once all the
614 sources have been merged. Off by default. See L</VARIABLE INTERPOLATION>.
615  
616 =item * C<interpolate_strict>
617  
618 When C<interpolate> is on, a reference that cannot be resolved croaks
619 (the default, C<1>). Set this to C<0> to leave such references as written.
620  
621 =item * C<level>
622  
623 Level for logging.
624  
625 =item * C<logger>
626  
627 Used for warnings and traces.
628 It can be an object that understands warn() and trace() messages,
629 such as a L<Log::Log4perl> or L<Log::Any> object,
630 a reference to code,
631 a reference to an array,
632 or a filename.
633  
634 =item * C<path>
635  
636 A synonym of C<config_dirs>.
637  
638 =item * C<sep_char>
639  
640 The separator in keys.
641 The default is a C<'.'>,
642 as in dotted notation,
643 such as C<'database.user'>.
644  
645 =item * C<schema>
646  
647 A L<Params::Validate::Strict> compatible schema to validate the configuration file against.
648  
649 =item * C<validators>
650  
651 A hashref mapping dotted config keys to validation rules. Each rule is applied to the
652 corresponding value in the merged configuration immediately after all sources have been
653 merged (or on first access when C<lazy> is set). A validation failure croaks.
654  
655 Each rule may be one of:
656  
657 =over 4
658  
659 =item A type name string
660  
661 validators => {
662 'database.port' => 'integer',
663 'app.name' => 'string',
664 'price' => 'number',
665 'enabled' => 'boolean',
666 'tags' => 'array',
667 'settings' => 'hash',
668 }
669  
670 Supported types: C<integer> (matches C</^-?\d+$/> -- no decimal point),
671 C<number> or C<float> (C<Scalar::Util::looks_like_number>), C<boolean>
672 (C<0>, C<1>, C<true>, C<false>, C<yes>, C<no> -- case-insensitive),
673 C<string> (any defined non-reference scalar), C<array> (arrayref),
674 C<hash> (hashref).
675  
676 =item A compiled regular expression
677  
678 validators => {
679 'log.level' => qr/^(?:debug|info|warn|error|fatal)$/i,
680 'app.name' => qr/^\w[\w\-]{1,63}$/,
681 }
682  
683 The value must be defined and must match the regex.
684  
685 =item A coderef
686  
687 validators => {
688 'database.port' => sub { my $v = shift; defined($v) && $v >= 1 && $v <= 65535 },
689 }
690  
691 Called with the value as its only argument. Must return a true value; otherwise the
692 constructor croaks.
693  
694 =item A hashref combining multiple constraints
695  
696 validators => {
697 'database.port' => {
698 type => 'integer',
699 min => 1,
700 max => 65535,
701 required => 1,
702 },
703 'api.key' => {
704 pattern => qr/^[A-Za-z0-9]{32}$/,
705 required => 1,
706 },
707 }
708  
709 Keys: C<type> (type-name string as above), C<pattern> (compiled regex), C<min> (numeric
710 lower bound, inclusive), C<max> (numeric upper bound, inclusive), C<required> (if true,
711 the key must exist and its value must be defined).
712  
713 =back
714  
715 All constraint types may be freely combined: specifying both C<type> and C<pattern>
716 requires the value to satisfy both.
717  
718 =item * C<checker>
719  
720 A prototype string (YAML) or hashref passed to L<Config::Checker> for template-based
721 structural validation. C<Config::Checker> must be installed; if it is absent a C<carp>
722 warning is emitted and validation is skipped.
723  
724 The prototype mirrors the expected config structure. Keys and values can carry type
725 annotations (C<[INTEGER]>, C<[PATH]>, C<[HOSTNAME]>, ...), custom code checks
726 (C<{...}>), and quantity specifiers (C<?>: optional, C<+>: one or more, C<*>: zero or
727 more):
728  
729 my $config = Config::Abstraction->new(
730 config_dirs => ['config'],
731 checker => <<'END_PROTOTYPE',
732 database:
733 host: hostname of the database server[HOSTNAME]
734 port: '?<5432>port number[INTEGER]'
735 user: database username
736 END_PROTOTYPE
737 );
738  
739 See L<Config::Checker> for the full prototype syntax.
740  
741 =item * C<lazy>
742  
743 When set to a true value, all source discovery and file I/O are deferred until the first
744 call to C<get()>, C<exists()>, C<all()>, C<explain_sources()>, C<prefer_*()>,
745 C<merge_defaults()>, or any AUTOLOAD accessor. This can reduce startup time in
746 applications that construct a C<Config::Abstraction> object before they know whether
747 they will access it.
748  
749 B<Differences from the default (eager) behaviour, and the debugging problems they cause:>
750  
751 =over 4
752  
753 =item 1. C<new()> always succeeds, even when no configuration exists.
754  
755 In eager mode, C<new()> returns C<undef> immediately when no files are found and no
756 C<data> was supplied, so a missing config is caught at the point of construction.
757 In lazy mode, C<new()> always returns a blessed object. If the configuration
758 directories do not exist, the files are missing, or the prefix is wrong, you will
759 not find out until the first accessor call - which may be deep inside your business
760 logic, far from where the object was created.
761  
762 # Problem: the typo in config_dirs goes unnoticed until runtime
763 my $cfg = Config::Abstraction->new(
764 config_dirs => ['/etc/myapp/conifg'], # typo - directory does not exist
765 lazy => 1,
766 );
767 # ... many lines later ...
768 my $host = $cfg->get('database.host'); # silently returns undef here
769  
770 =item 2. Schema validation errors appear at the wrong place in the call stack.
771  
772 When a C<schema> is supplied, eager mode validates the merged configuration inside
773 C<new()> and throws immediately if the config does not match. In lazy mode,
774 validation is deferred to the first accessor call. A schema violation therefore
775 surfaces as an exception thrown by C<get()> or C<all()>, not by C<new()>, and the
776 stack trace points to the accessor call rather than the construction site. If the
777 object is created in one module and accessed in another, the error message can be
778 very misleading.
779  
780 =item 3. Environment variables and C<@ARGV> are captured at access time, not construction time.
781  
782 The module reads C<%ENV> and C<@ARGV> during C<_load_config()>. In eager mode that
783 happens in C<new()>, so the configuration reflects the environment at the moment the
784 object is built. In lazy mode, any change to C<%ENV> or C<@ARGV> between C<new()>
785 and the first accessor call is silently picked up. This makes test isolation harder:
786 setting an environment variable I<after> constructing a lazy object will affect the
787 values it returns, which is not the case with an eager object.
788  
789 =item 4. File system state may change between construction and first use.
790  
791 Because lazy mode defers all I/O, the files that are read are those that exist at the
792 moment of first access, not at the moment C<new()> is called. If a config file is
793 written, deleted, or replaced between those two points (for example, by another
794 process or test fixture), the object will silently use the new state. An eager object
795 is immune to this race.
796  
797 =item 5. Errors from format parsers appear at accessor call sites.
798  
799 Malformed YAML, JSON, XML, or INI files emit a C<carp> warning and are skipped during
800 loading. In eager mode those warnings appear near the program's startup. In lazy mode
801 they appear during the first accessor call, which can make it look as though a routine
802 in your business logic is generating configuration warnings.
803  
804 =back
805  
806 B<When to use lazy loading:> It is most useful when a C<Config::Abstraction> object is
807 created speculatively at module-load time and may never be accessed (for example, in a
808 web framework where the config object is built for every request but some request paths
809 never read it). Avoid it when startup correctness is important, when you rely on
810 C<new()> returning C<undef> to detect missing configuration, or when you use schema
811 validation and need errors to point at the construction site.
812  
813 =back
814  
815 If just one argument is given, it is assumed to be the name of a file.
816  
817 =head3 API SPECIFICATION
818  
819 =head4 Input
820  
821 A hash or hashref of the options above, or a single SCALAR (a file name).
822 All are optional.
823  
824 allow_includes -- BOOLEAN -- follow the include key (default 0)
825 include_key -- SCALAR -- name of the include key (default 'include')
826 include_dirs -- SCALAR | ARRAYREF -- extra directories includes may read
827 include_max_depth -- INTEGER -- deepest include nesting (default 10)
828 interpolate -- BOOLEAN -- expand ${...} references (default 0)
829 interpolate_strict -- BOOLEAN -- croak on an unresolved reference (default 1)
830  
831 =head4 Output
832  
833 Config::Abstraction object, or undef when no configuration was found and
834 lazy is not set.
835  
836 =head3 MESSAGES
837  
838 croaks encryption_key_file does not exist
839 croaks invalid environment name
840 croaks an include outside the permitted directories, a circular include,
841 or includes nested more than include_max_depth deep
842 croaks an unresolved, circular or non-scalar ${...} reference (when
843 interpolate_strict is true)
844 carps an include that is missing, unreadable or not a configuration hash
845 carps a configuration file that cannot be parsed
846  
847 =cut
848  
849 sub new
850 931 ▶{
Subroutine new: called CC=33 SCAR=35.9
Pod documented
851 931 my $class = shift;
852 931 my $params;
853  
854 931 ▶ if(scalar(@_) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ == 1) { } 4 927 931
855 # Just one parameter - the name of a file
856 4 $params = Params::Get::get_params('file', \@_);
857 } else {
858 927 ▶ $params = Params::Get::get_params(undef, \@_) || {};
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
9252
MC/DC100%1/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
859 }
860  
861 931 ▶ $params->{'config_dirs'} //= $params->{'path'}; # Compatibility with Config::Auto
Condition100%3/3
$params->{"config_dirs"} //= $params->{"path"}
l!l&&r!l&&!r
898429
MC/DC100%2/2
$params->{"config_dirs"} //= $params->{"path"}
$params->{"config_dirs"} $params->{"path"}
Truth table100%3/3
A //= B
A= $params->{"config_dirs"}B= $params->{"path"}
ABresult
1X1
011
000
862  
863 931 ▶ $params->{config_dirs} = [ $ENV{CONFIG_DIR} ] if(defined($ENV{CONFIG_DIR}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{"CONFIG_DIR"} 4 927 931
864  
865 931 ▶ $params->{'config_file'} //= $params->{'file'} if($params->{'file'});
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"file"} 10 921 931
Condition66%2/3
$params->{"config_file"} //= $params->{"file"}
l!l&&r!l&&!r
280
MC/DC0%0/2
$params->{"config_file"} //= $params->{"file"}
$params->{"config_file"} $params->{"file"}
Truth table66%2/3
A //= B
A= $params->{"config_file"}B= $params->{"file"}
ABresult
1X1
011
000
866  
867 931 ▶ if(!defined($params->{'config_dirs'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $params->{"config_dirs"}) 25 906 931
868 25 ▶ if($params->{'config_file'} && File::Spec->file_name_is_absolute($params->{'config_file'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{'config_file'} and 'File::Spec'->file_name_is_absolute($params->{'config_file'})) { } 11 14 25
Condition100%3/3
$params->{"config_file"} and "File::Spec"->file_name_is_absolute($params->{"config_file"})
!ll&&!rl&&r
13111
MC/DC100%2/2
$params->{"config_file"} and "File::Spec"->file_name_is_absolute($params->{"config_file"})
$params->{"config_file"} "File::Spec"->file_name_is_absolute($params->{"config_file"})
Truth table100%3/3
A and B
A= $params->{"config_file"}B= "File::Spec"->file_name_is_absolute($params->{"config_file"})
ABresult
0X0
100
111
869 11 $params->{'config_dirs'} = [''];
870 } else {
871 # Set up the default value for config_dirs
872 14 ▶ if($^O ne 'MSWin32') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O ne 'MSWin32') { } 14 0 14
873 14 $params->{'config_dirs'} = [ '/etc', '/usr/local/etc' ];
874 } else {
875 0 $params->{'config_dirs'} = [''];
876 }
877 14 ▶ if($ENV{'HOME'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ENV{'HOME'}) { } 10 4 14
elsif ($ENV{'DOCUMENT_ROOT'}) { } 2 2 4
878 10 push @{$params->{'config_dirs'}},
879 File::Spec->catdir($ENV{'HOME'}, '.conf'),
880 File::Spec->catdir($ENV{'HOME'}, '.config'),
881 10 File::Spec->catdir($ENV{'HOME'}, 'conf'),
882 } elsif($ENV{'DOCUMENT_ROOT'}) {
883 2 push @{$params->{'config_dirs'}},
884 File::Spec->catdir($ENV{'DOCUMENT_ROOT'}, File::Spec->updir(), 'conf'),
885 File::Spec->catdir($ENV{'DOCUMENT_ROOT'}, 'conf'),
886 2 File::Spec->catdir($ENV{'DOCUMENT_ROOT'}, 'config');
887 }
888 14 ▶ if(my $dir = $ENV{'CONFIG_DIR'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dir = $ENV{'CONFIG_DIR'}) { } 0 14 14
889 0 push @{$params->{'config_dirs'}}, $dir;
890 } else {
891 14 push @{$params->{'config_dirs'}}, 'conf', 'config';
892 }
893 }
894 }
895  
896 my $self = bless {
897 sep_char => '.',
898 931 ▶ %{$params->{defaults} ? $params->{defaults} : $params},
Branch: 1 branch
BranchTrueFalseTotal
$params->{'defaults'} ? : 5 926 931
Condition100%2/2
$params->{'env_prefix'} || 'APP_'
l!l
174757
MC/DC100%1/1
$params->{'env_prefix'} || 'APP_'
$params->{'env_prefix'}
Truth table100%2/2
A
A= $params->{'env_prefix'}
Aresult
11
00
899 931 env_prefix => $params->{env_prefix} || 'APP_',
900 config => {},
901 }, $class;
902  
903 # Cache the compiled sep_char regex once so get() and exists() do not
904 # recompile it on every key lookup.
905 931 $self->{'_sep_re'} = qr/\Q$self->{'sep_char'}\E/;
906  
907 931 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 18 913 931
908 18 ▶ if(!Scalar::Util::blessed($logger)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($logger)) 4 14 18
909 # Don't call $self->_load_driver('Log::Abstraction') as it can make a call to logger, which is yet to be set up
910 4 eval "require Log::Abstraction";
911 4 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 4 0 4
912 4 carp(ref($self), ": Log::Abstraction failed to load: $@, disabling logging");
913 4 ▶ if(ref($logger) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $logger eq "ARRAY") 3 1 4
914 3 push @{$logger}, "Log::Abstraction failed to load: $@, disabling logging";
915 }
916 4 $self->{'logger'} = undef; # disable: unblessed ref would fatal on method calls
917 } else {
918 0 Log::Abstraction->import();
919 0 $self->{'logger'} = Log::Abstraction->new($logger);
920 0 ▶ if($params->{'level'} && $self->{'logger'}->can('level')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"level"} and $self->{"logger"}->can("level")) 0 0 0
Condition0%0/3
$params->{"level"} and $self->{"logger"}->can("level")
!ll&&!rl&&r
000
MC/DC0%0/2
$params->{"level"} and $self->{"logger"}->can("level")
$params->{"level"} $self->{"logger"}->can("level")
Truth table0%0/3
A and B
A= $params->{"level"}B= $self->{"logger"}->can("level")
ABresult
0X0
100
111
921 0 $self->{'logger'}->level($params->{'level'});
922 }
923 }
924 }
925 }
926 # Fail early when an explicitly-specified key file is missing rather than
927 # silently falling back to unencrypted operation (env-var key files are optional).
928 931 ▶ if(defined $self->{'encryption_key_file'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"encryption_key_file"}) 4 927 931
929 4 my $kf = $self->{'encryption_key_file'};
930 4 ▶ Carp::croak(ref($self) . ": encryption_key_file '$kf' does not exist") unless -f $kf;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $kf 1 3 4
931 }
932  
933 930 ▶ if($self->{'lazy'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"lazy"}) 46 884 930
934 # Defer all source scanning to the first accessor call.
935 # Stash validators/checker/schema for later (after _load_config runs).
936 46 ▶ $self->{'_lazy_schema'} = delete $self->{'schema'} if $self->{'schema'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"schema"} 2 44 46
937 46 ▶ $self->{'_lazy_validators'} = delete $self->{'validators'} if $self->{'validators'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"validators"} 3 43 46
938 46 ▶ $self->{'_lazy_checker'} = delete $self->{'checker'} if $self->{'checker'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"checker"} 0 46 46
939 46 return $self;
940 }
941  
942 884 $self->_load_config();
943  
944 850 ▶ if(my $schema = $params->{'schema'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $schema = $params->{"schema"}) 10 840 850
945 10 $self->{'config'} = Params::Validate::Strict::validate_strict(schema => $schema, input => $self->{'config'});
946 }
947 846 ▶ if(my $validators = $params->{'validators'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $validators = $params->{"validators"}) 66 780 846
948 66 $self->_run_validators($validators);
949 }
950 815 ▶ if(my $checker = $params->{'checker'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $checker = $params->{"checker"}) 2 813 815
951 2 $self->_run_checker($checker);
952 }
953  
954 815 ▶ if(defined($self->{'config'}) && scalar(keys %{$self->{'config'}})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"config"} and scalar keys %{$$self{"config"};}) 793 22 815
Condition50%1/2
defined $self->{"config"} and scalar keys %{$$self{"config"};}
!ll
0815
MC/DC0%0/1
defined $self->{"config"} and scalar keys %{$$self{"config"};}
defined $self->{"config"}
Truth table50%1/2
A
A= defined $self->{"config"}
Aresult
00
11
955 793 return $self;
956 }
957 22 return undef;
958 }
959  
960 # Trigger deferred loading when the object was constructed with lazy => 1.
961 # Safe to call unconditionally: it is a no-op once loading has completed.
962 sub _ensure_loaded
963 1017 ▶{
Subroutine _ensure_loaded: called CC=5 SCAR=16.2
964 1017 my $self = shift;
965 1017 ▶ return unless $self->{'lazy'}; # fast-path: not a lazy object
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lazy"} 975 42 1017
966 42 delete $self->{'lazy'}; # prevent re-entry on recursive calls
967 42 $self->_load_config();
968 41 ▶ if(my $schema = delete $self->{'_lazy_schema'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $schema = delete $self->{"_lazy_schema"}) 1 40 41
969 1 $self->{'config'} = Params::Validate::Strict::validate_strict(schema => $schema, input => $self->{'config'});
970 }
971 40 ▶ if(my $validators = delete $self->{'_lazy_validators'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $validators = delete $self->{"_lazy_validators"}) 3 37 40
972 3 $self->_run_validators($validators);
973 }
974 38 ▶ if(my $checker = delete $self->{'_lazy_checker'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $checker = delete $self->{"_lazy_checker"}) 0 38 38
975 0 $self->_run_checker($checker);
976 }
977 }
978  
979 # Resolve the active deployment environment name.
980 # Checked in order: 'environment' constructor option, {prefix}ENV env var,
981 # PLACK_ENV, NODE_ENV. Returns undef when none is set.
982 # The value must match /^[A-Za-z0-9_\-]+$/ or a croak is raised.
983 sub _get_environment
984 937 ▶{
Subroutine _get_environment: called CC=8 SCAR=20.8
985 937 my $self = shift;
986  
987 937 my $env;
988  
989 937 ▶ if(defined($self->{'environment'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'environment'}) { } 48 889 937
990 48 $env = $self->{'environment'};
991 } else {
992 889 ▶ my $prefix = $self->{'env_prefix'} // 'APP_';
Condition50%1/2
$self->{"env_prefix"} // "APP_"
l!l
8890
MC/DC0%0/1
$self->{"env_prefix"} // "APP_"
$self->{"env_prefix"}
Truth table50%1/2
A
A= $self->{"env_prefix"}
Aresult
11
00
993 $env = $ENV{$prefix . 'ENV'}
994 // $ENV{'PLACK_ENV'}
995 889 ▶ // $ENV{'NODE_ENV'};
Condition100%6/6
($ENV{$prefix . 'ENV'} // $ENV{"PLACK_ENV"}) // $ENV{"NODE_ENV"}
l!l&&r!l&&!r
103876
$ENV{$prefix . 'ENV'} // $ENV{"PLACK_ENV"}
l!l&&r!l&&!r
46879
MC/DC100%3/3
($ENV{$prefix . 'ENV'} // $ENV{"PLACK_ENV"}) // $ENV{"NODE_ENV"}
$ENV{$prefix . 'ENV'} $ENV{"PLACK_ENV"} $ENV{"NODE_ENV"}
Truth table100%4/4
A // B // C
A= $ENV{$prefix . 'ENV'}B= $ENV{"PLACK_ENV"}C= $ENV{"NODE_ENV"}
ABCresult
1XX1
01X1
0011
0000
996 }
997  
998 937 ▶ return undef unless defined $env;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $env 876 61 937
999 61 ▶ return undef if $env eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $env eq "" 2 59 61
1000  
1001 59 ▶ unless($env =~ /^[A-Za-z0-9_-]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($env =~ /^[A-Za-z0-9_-]+$/) 10 49 59
1002 10 Carp::croak(ref($self) . ": invalid environment name '$env': must contain only alphanumerics, hyphens, or underscores");
1003 }
1004  
1005 49 return $env;
1006 }
1007  
1008 # _sanitize_yaml_values: Recursively replace CODE and GLOB refs with undef.
1009 # YAML::XS can produce CODE refs from !!perl/code tags regardless of DisableCode.
1010 # Applying this after LoadFile prevents executable references from reaching callers.
1011 sub _sanitize_yaml_values
1012 796 ▶{
Subroutine _sanitize_yaml_values: called CC=5 SCAR=16.1
1013 796 my ($self, $val) = @_;
1014 796 my $r = ref($val);
1015 796 ▶ return undef if $r eq 'CODE' || $r eq 'GLOB';
Branch: 1 branch
BranchTrueFalseTotal
if $r eq "CODE" or $r eq "GLOB" 3 793 796
Condition66%2/3
$r eq "CODE" or $r eq "GLOB"
l!l&&r!l&&!r
30793
MC/DC50%1/2
$r eq "CODE" or $r eq "GLOB"
$r eq "CODE" $r eq "GLOB"
Truth table66%2/3
A or B
A= $r eq "CODE"B= $r eq "GLOB"
ABresult
1X1
011
000
1016 793 ▶ if($r eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "HASH") 404 389 793
1017 404 return { map { $_ => $self->_sanitize_yaml_values($val->{$_}) } keys %$val };
1018 }
1019 389 ▶ if($r eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "ARRAY") 10 379 389
1020 10 return [ map { $self->_sanitize_yaml_values($_) } @$val ];
1021 }
1022 379 return $val;
1023 }
1024  
1025 # Resolve the AES-256 encryption key from constructor option, env vars, or key file.
1026 # Returns 32 raw bytes, or undef when no key is configured.
1027 sub _get_encryption_key
1028 947 ▶{
Subroutine _get_encryption_key: called CC=13 SCAR=26.2
1029 947 my $self = shift;
1030  
1031 947 my $raw = $self->{'encryption_key'};
1032  
1033 947 ▶ if(!defined($raw)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $raw) 856 91 947
1034 856 ▶ my $prefix = $self->{'env_prefix'} // 'APP_';
Condition50%1/2
$self->{"env_prefix"} // "APP_"
l!l
8560
MC/DC0%0/1
$self->{"env_prefix"} // "APP_"
$self->{"env_prefix"}
Truth table50%1/2
A
A= $self->{"env_prefix"}
Aresult
11
00
1035 856 ▶ $raw = $ENV{$prefix . 'ENCRYPTION_KEY'} // $ENV{'ENCRYPTION_KEY'};
Condition100%3/3
$ENV{$prefix . 'ENCRYPTION_KEY'} // $ENV{"ENCRYPTION_KEY"}
l!l&&r!l&&!r
27847
MC/DC100%2/2
$ENV{$prefix . 'ENCRYPTION_KEY'} // $ENV{"ENCRYPTION_KEY"}
$ENV{$prefix . 'ENCRYPTION_KEY'} $ENV{"ENCRYPTION_KEY"}
Truth table100%3/3
A // B
A= $ENV{$prefix . 'ENCRYPTION_KEY'}B= $ENV{"ENCRYPTION_KEY"}
ABresult
1X1
011
000
1036 }
1037  
1038 947 ▶ if(!defined($raw)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $raw) 847 100 947
1039 847 ▶ my $prefix = $self->{'env_prefix'} // 'APP_';
Condition50%1/2
$self->{"env_prefix"} // "APP_"
l!l
8470
MC/DC0%0/1
$self->{"env_prefix"} // "APP_"
$self->{"env_prefix"}
Truth table50%1/2
A
A= $self->{"env_prefix"}
Aresult
11
00
1040 my $kf = $self->{'encryption_key_file'}
1041 // $ENV{$prefix . 'ENCRYPTION_KEY_FILE'}
1042 847 ▶ // $ENV{'ENCRYPTION_KEY_FILE'};
Condition66%4/6
($self->{"encryption_key_file"} // $ENV{$prefix . 'ENCRYPTION_KEY_FILE'}) // $ENV{"ENCRYPTION_KEY_FILE"}
l!l&&r!l&&!r
50842
$self->{"encryption_key_file"} // $ENV{$prefix . 'ENCRYPTION_KEY_FILE'}
l!l&&r!l&&!r
50842
MC/DC33%1/3
($self->{"encryption_key_file"} // $ENV{$prefix . 'ENCRYPTION_KEY_FILE'}) // $ENV{"ENCRYPTION_KEY_FILE"}
$self->{"encryption_key_file"} $ENV{$prefix . 'ENCRYPTION_KEY_FILE'} $ENV{"ENCRYPTION_KEY_FILE"}
Truth table50%2/4
A // B // C
A= $self->{"encryption_key_file"}B= $ENV{$prefix . 'ENCRYPTION_KEY_FILE'}C= $ENV{"ENCRYPTION_KEY_FILE"}
ABCresult
1XX1
01X1
0011
0000
1043 847 ▶ if(defined($kf) && -f $kf) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $kf and -f $kf) 5 842 847
Condition66%2/3
defined $kf and -f $kf
!ll&&!rl&&r
84205
MC/DC50%1/2
defined $kf and -f $kf
defined $kf -f $kf
Truth table66%2/3
A and B
A= defined $kfB= -f $kf
ABresult
0X0
100
111
1044 5 ▶ open my $fh, '<', $kf
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $kf or Carp::croak(ref($self) . ": cannot open encryption_key_file '${kf}': $!") 5 0 5
1045 or Carp::croak(ref($self) . ": cannot open encryption_key_file '$kf': $!");
1046 5 $raw = <$fh>;
1047 5 close $fh;
1048 5 ▶ chomp $raw if defined $raw;
Branch: 1 branch
BranchTrueFalseTotal
if defined $raw 5 0 5
1049 }
1050 }
1051  
1052 947 ▶ return undef unless defined $raw;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 842 105 947
1053 105 return $self->_decode_encryption_key($raw);
1054 }
1055  
1056 # Accept a key as 32 raw bytes, 64 hex chars, or 43-44 base64/base64url chars.
1057 # Returns 32 raw bytes or croaks.
1058 sub _decode_encryption_key
1059 112 ▶{
Subroutine _decode_encryption_key: called CC=7 SCAR=19.5
1060 112 my ($self, $raw) = @_;
1061  
1062 112 ▶ return $raw if length($raw) == $_AES_KEY_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if length $raw == $_AES_KEY_SIZE 50 62 112
1063  
1064 62 ▶ if(length($raw) == $_HEX_KEY_LEN && $raw =~ /^[0-9A-Fa-f]{$_HEX_KEY_LEN}$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $raw == $_HEX_KEY_LEN and $raw =~ /^[0-9A-Fa-f]{$_HEX_KEY_LEN}$/) 50 12 62
Condition100%3/3
length $raw == $_HEX_KEY_LEN and $raw =~ /^[0-9A-Fa-f]{$_HEX_KEY_LEN}$/
!ll&&!rl&&r
11150
MC/DC100%2/2
length $raw == $_HEX_KEY_LEN and $raw =~ /^[0-9A-Fa-f]{$_HEX_KEY_LEN}$/
length $raw == $_HEX_KEY_LEN $raw =~ /^[0-9A-Fa-f]{$_HEX_KEY_LEN}$/
Truth table100%3/3
A and B
A= length $raw == $_HEX_KEY_LENB= $raw =~ /^[0-9A-Fa-f]{$_HEX_KEY_LEN}$/
ABresult
0X0
100
111
1065 50 return pack('H*', $raw);
1066 }
1067  
1068 12 ▶ if(length($raw) >= $_B64_KEY_MIN && length($raw) <= $_B64_KEY_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $raw >= $_B64_KEY_MIN and length $raw <= $_B64_KEY_MAX) 6 6 12
Condition100%3/3
length $raw >= $_B64_KEY_MIN and length $raw <= $_B64_KEY_MAX
!ll&&!rl&&r
426
MC/DC100%2/2
length $raw >= $_B64_KEY_MIN and length $raw <= $_B64_KEY_MAX
length $raw >= $_B64_KEY_MIN length $raw <= $_B64_KEY_MAX
Truth table100%3/3
A and B
A= length $raw >= $_B64_KEY_MINB= length $raw <= $_B64_KEY_MAX
ABresult
0X0
100
111
1069 6 require MIME::Base64;
1070 6 (my $b64 = $raw) =~ tr/-_/+\//; # base64url to base64
1071 6 $b64 .= '=' x ((4 - length($b64) % 4) % 4);
1072 6 my $bytes = MIME::Base64::decode_base64($b64);
1073 6 ▶ return $bytes if length($bytes) == $_AES_KEY_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
if length $bytes == $_AES_KEY_SIZE 6 0 6
1074 }
1075  
1076 6 Carp::croak(ref($self) . ': encryption_key must be ' . $_AES_KEY_SIZE . ' raw bytes, ' . $_HEX_KEY_LEN . ' hex chars, or ' . $_B64_KEY_MAX . ' base64 chars (got length ' . length($raw) . ')');
1077 }
1078  
1079 # Recursively walk $href and decrypt any leaf value matching ENC[...].
1080 # $seen guards against circular references (possible when Hash::Merge
1081 # no-clone mode is active and sub-hashes are shared across the merge tree).
1082 sub _decrypt_config_values
1083 68 ▶{
Subroutine _decrypt_config_values: called CC=14 SCAR=26.9
1084 68 my ($self, $href, $key, $seen) = @_;
1085 68 ▶ $seen //= {};
Condition100%2/2
$seen //= {}
l!l
761
MC/DC100%1/1
$seen //= {}
$seen
Truth table100%2/2
A
A= $seen
Aresult
11
00
1086 68 ▶ return if $seen->{Scalar::Util::refaddr($href)}++;
Branch: 1 branch
BranchTrueFalseTotal
if $$seen{builtin::refaddr($href)}++ 1 67 68
1087  
1088 67 for my $k (keys %{$href}) {
1089 49 ▶ next if $k eq 'config_path';
Branch: 1 branch
BranchTrueFalseTotal
if $k eq "config_path" 2 47 49
1090 47 my $v = $href->{$k};
1091 47 ▶ if(ref($v) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $v eq 'HASH') { } 7 40 47
elsif (ref $v eq 'ARRAY') { } 2 38 40
elsif (not ref $v and defined $v and $v =~ /^ENC\[/) { } 21 17 38
1092 7 $self->_decrypt_config_values($v, $key, $seen);
1093 } elsif(ref($v) eq 'ARRAY') {
1094 2 for my $i (0..$#{$v}) {
1095 4 ▶ if(!ref($v->[$i]) && defined($v->[$i]) && $v->[$i] =~ /^ENC\[/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $v->[$i] and defined $v->[$i] and $v->[$i] =~ /^ENC\[/) 2 2 4
Condition50%3/6
not ref $v->[$i] and defined $v->[$i] and $v->[$i] =~ /^ENC\[/
!ll&&!rl&&r
022
not ref $v->[$i] and defined $v->[$i]
!ll&&!rl&&r
004
MC/DC33%1/3
not ref $v->[$i] and defined $v->[$i] and $v->[$i] =~ /^ENC\[/
not ref $v->[$i] defined $v->[$i] $v->[$i] =~ /^ENC\[/
Truth table50%2/4
not(A) and B and C
A= not ref $v->[$i]B= defined $v->[$i]C= $v->[$i] =~ /^ENC\[/
ABCresult
0XX0
10X0
1100
1111
1096 2 $v->[$i] = $self->_decrypt_enc_value($v->[$i], $key);
1097 }
1098 }
1099 ▶ } elsif(!ref($v) && defined($v) && $v =~ /^ENC\[/) {
Condition50%3/6
not ref $v and defined $v and $v =~ /^ENC\[/
!ll&&!rl&&r
01721
not ref $v and defined $v
!ll&&!rl&&r
0038
MC/DC33%1/3
not ref $v and defined $v and $v =~ /^ENC\[/
not ref $v defined $v $v =~ /^ENC\[/
Truth table50%2/4
not(A) and B and C
A= not ref $vB= defined $vC= $v =~ /^ENC\[/
ABCresult
0XX0
10X0
1100
1111
1100 21 $href->{$k} = $self->_decrypt_enc_value($v, $key);
1101 }
1102 }
1103 }
1104  
1105 # Decrypt a single ENC[AES256GCM,<base64url>] token.
1106 # Returns the plaintext string or croaks on failure.
1107 sub _decrypt_enc_value
1108 28 ▶{
Subroutine _decrypt_enc_value: called CC=7 SCAR=19.5
1109 28 my ($self, $token, $key) = @_;
1110  
1111 28 ▶ unless($token =~ /^
Branch: 1 branch
BranchTrueFalseTotal
unless ($token =~ /^ ENC\[ ([A-Za-z0-9]+) # algorithm name (e.g. AES256GCM) , ([A-Za-z0-9_-]+) # base64url payload (RFC 4648 section 5 alphabet) \] $/x) 2 26 28
1112 ENC\[
1113 ([A-Za-z0-9]+) # algorithm name (e.g. AES256GCM)
1114 ,
1115 ([A-Za-z0-9_-]+) # base64url payload (RFC 4648 section 5 alphabet)
1116 \]
1117 $/x) {
1118 2 Carp::croak(ref($self) . ": malformed ENC token: $token");
1119 }
1120 26 my ($algo, $b64) = ($1, $2);
1121  
1122 26 ▶ unless(lc($algo) eq 'aes256gcm') {
Branch: 1 branch
BranchTrueFalseTotal
unless (lc $algo eq "aes256gcm") 2 24 26
1123 2 Carp::croak(ref($self) . ": unsupported encryption algorithm '$algo' in ENC token");
1124 }
1125  
1126 # Decode and validate payload length before requiring CryptX: a structurally
1127 # invalid token should be rejected regardless of whether the crypto library
1128 # is installed. MIME::Base64 is a core module and always available.
1129 24 require MIME::Base64;
1130 24 my $raw = MIME::Base64::decode_base64url($b64);
1131  
1132 24 ▶ if(length($raw) < $_ENC_PAYLOAD_MIN) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $raw < $_ENC_PAYLOAD_MIN) 2 22 24
1133 2 Carp::croak(ref($self) . ": ENC token payload is too short to be valid");
1134 }
1135  
1136 22 ▶ unless($self->_load_driver('Crypt::AuthEnc::GCM')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_load_driver("Crypt::AuthEnc::GCM")) 1 21 22
1137 1 Carp::croak(ref($self) . ': CryptX (Crypt::AuthEnc::GCM) is required to decrypt ENC[] values; install it with: cpanm CryptX');
1138 }
1139  
1140 21 my $nonce = substr($raw, 0, $_AES_NONCE_SIZE);
1141 21 my $tag = substr($raw, -$_AES_TAG_SIZE);
1142 21 my $ct = substr($raw, $_AES_NONCE_SIZE, length($raw) - $_ENC_PAYLOAD_MIN);
1143  
1144 21 my $gcm = Crypt::AuthEnc::GCM->new('AES', $key);
1145 21 $gcm->iv_add($nonce);
1146 21 $gcm->adata_add(''); # end the IV phase; see encrypt_value()
1147 21 my $pt = $gcm->decrypt_add($ct);
1148  
1149 21 my $ok = eval { $gcm->decrypt_done($tag) };
1150 21 ▶ unless($ok && !$@) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok and not $@) 4 17 21
Condition66%2/3
$ok and not $@
!ll&&!rl&&r
4017
MC/DC50%1/2
$ok and not $@
$ok not $@
Truth table66%2/3
A and not(B)
A= $okB= not $@
ABresult
0X0
100
111
1151 4 Carp::croak(ref($self) . ": decryption failed (wrong key or tampered data)");
1152 }
1153  
1154 17 return $pt;
1155 }
1156  
1157 # Apply the validators hash supplied as a constructor option.
1158 # Each key is a dotted config key; each value is a coderef, regex, type string, or spec hashref.
1159 sub _run_validators
1160 69 ▶{
Subroutine _run_validators: called CC=10 SCAR=23.0
1161 69 my ($self, $validators) = @_;
1162  
1163 69 for my $key (sort keys %{$validators}) {
1164 71 my $spec = $validators->{$key};
1165 71 my $value = $self->get($key);
1166  
1167 71 ▶ if(ref($spec) eq 'CODE') {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $spec eq 'CODE') { } 9 62 71
elsif (ref $spec eq 'Regexp') { } 9 53 62
elsif (ref $spec eq 'HASH') { } 15 38 53
elsif (not ref $spec) { } 36 2 38
1168 9 ▶ unless($spec->($value)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$spec($value)) 4 5 9
1169 4 Carp::croak(ref($self) . ": validation failed for '$key': custom validator returned false");
1170 }
1171 } elsif(ref($spec) eq 'Regexp') {
1172 9 ▶ unless(defined($value) && $value =~ $spec) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value and $value =~ /$spec/) 5 4 9
Condition100%3/3
defined $value and $value =~ /$spec/
!ll&&!rl&&r
144
MC/DC100%2/2
defined $value and $value =~ /$spec/
defined $value $value =~ /$spec/
Truth table100%3/3
A and B
A= defined $valueB= $value =~ /$spec/
ABresult
0X0
100
111
1173 5 ▶ Carp::croak(ref($self) . ": '$key' value " .
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 4 1 5
1174 (defined($value) ? "'$value'" : '(undef)') . " does not match required pattern");
1175 }
1176 } elsif(ref($spec) eq 'HASH') {
1177 15 $self->_validate_value_spec($key, $value, $spec);
1178 } elsif(!ref($spec)) {
1179 36 _validate_type($key, $value, $spec);
1180 } else {
1181 2 Carp::croak(ref($self) . ": invalid validator for '$key': must be a type string, regex, coderef, or hashref");
1182 }
1183 }
1184 }
1185  
1186 # Apply a hashref spec (type / pattern / min / max / required) to a single value.
1187 sub _validate_value_spec
1188 15 ▶{
Subroutine _validate_value_spec: called CC=15 SCAR=27.6
1189 15 my ($self, $key, $value, $spec) = @_;
1190  
1191 15 ▶ if($spec->{'required'} && (!$self->exists($key) || !defined($value))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"required"} and not $self->exists($key) && defined $value) 4 11 15
Condition50%3/6
$spec->{"required"} and not $self->exists($key) && defined $value
!ll&&!rl&&r
1104
$self->exists($key) && defined $value
!ll&&!rl&&r
400
MC/DC33%1/3
$spec->{"required"} and not $self->exists($key) && defined $value
$spec->{"required"} $self->exists($key) defined $value
Truth table50%2/4
A and not(B && C)
A= $spec->{"required"}B= $self->exists($key)C= defined $value
ABCresult
0XX0
1110
10X1
1101
1192 4 Carp::croak(ref($self) . ": required key '$key' is missing or undefined");
1193 }
1194 11 ▶ if(my $type = $spec->{'type'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $spec->{"type"}) 7 4 11
1195 7 _validate_type($key, $value, $type);
1196 }
1197 11 ▶ if(my $pattern = $spec->{'pattern'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pattern = $spec->{"pattern"}) 2 9 11
1198 2 ▶ unless(defined($value) && $value =~ $pattern) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value and $value =~ /$pattern/) 1 1 2
Condition66%2/3
defined $value and $value =~ /$pattern/
!ll&&!rl&&r
011
MC/DC50%1/2
defined $value and $value =~ /$pattern/
defined $value $value =~ /$pattern/
Truth table66%2/3
A and B
A= defined $valueB= $value =~ /$pattern/
ABresult
0X0
100
111
1199 1 ▶ Carp::croak(ref($self) . ": '$key' value " .
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 1 0 1
1200 (defined($value) ? "'$value'" : '(undef)') . " does not match required pattern");
1201 }
1202 }
1203 10 ▶ if(defined(my $min = $spec->{'min'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $min = $spec->{"min"})) 7 3 10
1204 7 ▶ Carp::croak(ref($self) . ": '$key' value '$value' is less than minimum $min")
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value < $min 3 4 7
Condition66%2/3
defined $value and $value < $min
!ll&&!rl&&r
043
MC/DC50%1/2
defined $value and $value < $min
defined $value $value < $min
Truth table66%2/3
A and B
A= defined $valueB= $value < $min
ABresult
0X0
100
111
1205 if defined($value) && $value < $min;
1206 }
1207 7 ▶ if(defined(my $max = $spec->{'max'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $max = $spec->{"max"})) 6 1 7
1208 6 ▶ Carp::croak(ref($self) . ": '$key' value '$value' exceeds maximum $max")
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value > $max 2 4 6
Condition66%2/3
defined $value and $value > $max
!ll&&!rl&&r
042
MC/DC50%1/2
defined $value and $value > $max
defined $value $value > $max
Truth table66%2/3
A and B
A= defined $valueB= $value > $max
ABresult
0X0
100
111
1209 if defined($value) && $value > $max;
1210 }
1211 }
1212  
1213 # Validate a single value against a named type.
1214 # Not a method - takes (key, value, type_string).
1215 sub _validate_type
1216 79 ▶{
Subroutine _validate_type: called CC=21 SCAR=30.4
1217 79 my ($key, $value, $type) = @_;
1218 79 my $ltype = lc($type);
1219  
1220 79 ▶ if($ltype eq 'integer') {
Branch: 6 branches
BranchTrueFalseTotal
if ($ltype eq 'integer') { } 27 52 79
elsif ($ltype eq 'number' or $ltype eq 'float') { } 10 42 52
elsif ($ltype eq 'boolean') { } 24 18 42
elsif ($ltype eq 'string') { } 6 12 18
elsif ($ltype eq 'array') { } 6 6 12
elsif ($ltype eq 'hash') { } 4 2 6
1221 27 ▶ Carp::croak("Config::Abstraction: '$key' must be an integer (got " .
Branch: 2 branches
BranchTrueFalseTotal
unless defined $value and $value =~ /^-?[0-9]+$/ 11 16 27
defined $value ? : 9 2 11
Condition100%3/3
defined $value and $value =~ /^-?[0-9]+$/
!ll&&!rl&&r
2916
MC/DC100%2/2
defined $value and $value =~ /^-?[0-9]+$/
defined $value $value =~ /^-?[0-9]+$/
Truth table100%3/3
A and B
A= defined $valueB= $value =~ /^-?[0-9]+$/
ABresult
0X0
100
111
1222 (defined $value ? "'$value'" : 'undef') . ')')
1223 unless defined($value) && $value =~ /^-?[0-9]+$/;
1224 ▶ } elsif($ltype eq 'number' || $ltype eq 'float') {
Condition100%3/3
$ltype eq "number" or $ltype eq "float"
l!l&&r!l&&!r
8242
MC/DC100%2/2
$ltype eq "number" or $ltype eq "float"
$ltype eq "number" $ltype eq "float"
Truth table100%3/3
A or B
A= $ltype eq "number"B= $ltype eq "float"
ABresult
1X1
011
000
1225 10 ▶ Carp::croak("Config::Abstraction: '$key' must be a number (got " .
Branch: 2 branches
BranchTrueFalseTotal
unless defined $value and &Scalar::Util::looks_like_number($value) 2 8 10
defined $value ? : 1 1 2
Condition100%3/3
defined $value and &Scalar::Util::looks_like_number($value)
!ll&&!rl&&r
118
MC/DC100%2/2
defined $value and &Scalar::Util::looks_like_number($value)
defined $value &Scalar::Util::looks_like_number($value)
Truth table100%3/3
A and B
A= defined $valueB= &Scalar::Util::looks_like_number($value)
ABresult
0X0
100
111
1226 (defined $value ? "'$value'" : 'undef') . ')')
1227 unless defined($value) && Scalar::Util::looks_like_number($value);
1228 } elsif($ltype eq 'boolean') {
1229 24 ▶ Carp::croak("Config::Abstraction: '$key' must be a boolean (0/1/true/false/yes/no), got " .
Branch: 2 branches
BranchTrueFalseTotal
unless defined $value and $value =~ /^(?:1|0|true|false|yes|no)$/i 4 20 24
defined $value ? : 3 1 4
Condition100%3/3
defined $value and $value =~ /^(?:1|0|true|false|yes|no)$/i
!ll&&!rl&&r
1320
MC/DC100%2/2
defined $value and $value =~ /^(?:1|0|true|false|yes|no)$/i
defined $value $value =~ /^(?:1|0|true|false|yes|no)$/i
Truth table100%3/3
A and B
A= defined $valueB= $value =~ /^(?:1|0|true|false|yes|no)$/i
ABresult
0X0
100
111
1230 (defined $value ? "'$value'" : 'undef'))
1231 unless defined($value) && $value =~ /^(?:1|0|true|false|yes|no)$/i;
1232 } elsif($ltype eq 'string') {
1233 6 ▶ Carp::croak("Config::Abstraction: '$key' must be a defined string (got undef)")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value 2 4 6
Condition66%2/3
defined $value and not ref $value
!ll&&!rl&&r
204
MC/DC50%1/2
defined $value and not ref $value
defined $value not ref $value
Truth table66%2/3
A and not(B)
A= defined $valueB= not ref $value
ABresult
0X0
100
111
1234 unless defined($value) && !ref($value);
1235 } elsif($ltype eq 'array') {
1236 6 ▶ Carp::croak("Config::Abstraction: '$key' must be an array reference")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 3 3 6
1237 unless ref($value) eq 'ARRAY';
1238 } elsif($ltype eq 'hash') {
1239 4 ▶ Carp::croak("Config::Abstraction: '$key' must be a hash reference")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 1 3 4
1240 unless ref($value) eq 'HASH';
1241 } else {
1242 2 Carp::croak("Config::Abstraction: unknown type '$type' in validators for '$key'");
1243 }
1244 }
1245  
1246 # Invoke Config::Checker with the merged config and caller-supplied prototype.
1247 # prototype may be a YAML string or a hashref.
1248 sub _run_checker
1249 3 ▶{
Subroutine _run_checker: called CC=4 SCAR=21.7
1250 3 my ($self, $prototype) = @_;
1251  
1252 3 ▶ unless($self->_load_driver('Config::Checker')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_load_driver("Config::Checker")) 3 0 3
1253 3 Carp::carp(ref($self) . ': Config::Checker not available; skipping checker validation');
1254 3 return;
1255 }
1256  
1257 # config_checker_source() returns Perl source text (a sub { ... } literal)
1258 # that must be eval'd so it can import into our namespace.
1259 0 my $checker = eval Config::Checker::config_checker_source(); ## no critic (ProhibitStringyEval)
1260 0 ▶ Carp::croak(ref($self) . ": failed to compile Config::Checker: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
1261  
1262 0 eval { $checker->($self->{'config'}, $prototype) };
1263 0 ▶ Carp::croak(ref($self) . ": checker validation failed: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
1264 }
1265  
1266 # Determine if a value is a plain, unblessed, non-reference scalar
1267 # safe to use in regex/string operations.
1268 # Args: value to test
1269 # Returns: 1 if plain scalar, 0 otherwise
1270 sub _is_plain_scalar
1271 71 ▶{
Subroutine _is_plain_scalar: called CC=4 SCAR=13.9
1272 71 my $val = $_[0];
1273  
1274 71 ▶ return 0 if !defined($val);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 1 70 71
1275 70 ▶ return 0 if Scalar::Util::blessed($val);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($val) 1 69 70
1276 69 ▶ return 0 if ref($val);
Branch: 1 branch
BranchTrueFalseTotal
if ref $val 5 64 69
1277 64 return 1;
1278 }
1279  
1280 # Recursively flatten a nested hashref to dotted keys (always uses '.' as separator).
1281 # Skips the meta-key 'config_path'. Used by explain_sources() and source tracking.
1282 # $seen guards against circular references (e.g. those possible when
1283 # Hash::Merge::set_clone_behavior(0) is active).
1284 #
1285 # _flatten_into writes into a caller-supplied hashref accumulator so that
1286 # each leaf key is written exactly once -- O(N) total writes vs the previous
1287 # O(N^2) pattern of %flat = (%flat, _flatten_keys(...)) at each recursion level.
1288 sub _flatten_into
1289 1897 ▶{
Subroutine _flatten_into: called CC=7 SCAR=19.5
1290 1897 my ($acc, $hash, $prefix, $seen) = @_;
1291 1897 ▶ return unless ref($hash) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hash eq "HASH" 0 1897 1897
1292 1897 my $addr = Scalar::Util::refaddr($hash);
1293 1897 ▶ return if $seen->{$addr}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$addr}++ 5 1892 1897
1294 1892 for my $k (keys %$hash) {
1295 3963 ▶ next if $k eq 'config_path';
Branch: 1 branch
BranchTrueFalseTotal
if $k eq "config_path" 14 3949 3963
1296 3949 ▶ my $full = length($prefix) ? "$prefix.$k" : $k;
Branch: 1 branch
BranchTrueFalseTotal
length $prefix ? : 1250 2699 3949
1297 3949 ▶ if(ref($hash->{$k}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $hash->{$k} eq 'HASH') { } 783 3166 3949
1298 783 _flatten_into($acc, $hash->{$k}, $full, $seen);
1299 } else {
1300 3166 $acc->{$full} = $hash->{$k};
1301 }
1302 }
1303 }
1304  
1305 sub _flatten_keys
1306 1114 ▶{
Subroutine _flatten_keys: called CC=3 SCAR=11.0
1307 1114 my ($hash, $prefix, $seen) = @_;
1308 1114 my %flat;
1309 1114 ▶ _flatten_into(\%flat, $hash, $prefix // '', $seen // {});
Condition75%3/4
$prefix // ""
l!l
11113
$seen // {}
l!l
01114
MC/DC100%1/1
$prefix // ""
$prefix
MC/DC0%0/1
$seen // {}
$seen
Truth table100%2/2
A
A= $prefix
Aresult
11
00
Truth table50%1/2
A
A= $seen
Aresult
11
00
1310 1114 return %flat;
1311 }
1312  
1313 sub _load_config
1314 927 ▶{
Subroutine _load_config: called CC=157 SCAR=58.0
1315 927 ▶ if(!UNIVERSAL::isa((caller)[0], __PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)) 2 925 927
1316 2 Carp::croak('Illegal Operation: This method can only be called by a subclass');
1317 }
1318  
1319 925 my $self = shift;
1320  
1321 # Disable Hash::Merge cloning for the duration of this method.
1322 # Storable::dclone (used when clone=1) cannot handle coderefs or blessed
1323 # objects that may appear in the 'data' argument; sharing references is
1324 # safe here because %merged is a fresh, method-local accumulator.
1325 925 my $saved_clone = Hash::Merge::get_clone_behavior();
1326 925 Hash::Merge::set_clone_behavior(0);
1327  
1328 925 my %merged;
1329  
1330 925 ▶ if($self->{'data'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"data"}) 718 207 925
1331 # The data argument given to 'new' contains defaults that this routine will override
1332 718 ▶ if(ref($self->{'data'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{'data'} eq 'HASH') { } 715 3 718
1333 715 %merged = %{$self->{'data'}};
1334 715 push @{$self->{'_source_records'}}, {
1335 type => 'data',
1336 label => 'constructor data argument',
1337 715 flat_data => { _flatten_keys($self->{'data'}) },
1338 };
1339 } else {
1340 3 Carp::carp(ref($self) . ': data argument must be a hashref; ignoring non-hashref value');
1341 }
1342 }
1343  
1344 925 my $logger = $self->{'logger'};
1345 925 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 14 911 925
1346 14 $logger->trace(ref($self), ' ', __LINE__, ': Entered _load_config');
1347 }
1348  
1349 925 my $environment = $self->_get_environment();
1350 915 my @_formats = qw(yaml yml json xml ini toml conf);
1351 my @_file_list = (
1352 6405 ▶ (map { "base.$_" } @_formats),
Branch: 1 branch
BranchTrueFalseTotal
$environment ? : 39 876 915
1353 273 ($environment ? (map { "base.$environment.$_" } @_formats) : ()),
1354 6405 ▶ (map { "local.$_" } @_formats),
Branch: 1 branch
BranchTrueFalseTotal
$environment ? : 39 876 915
1355 915 ($environment ? (map { "local.$environment.$_" } @_formats) : ()),
1356 );
1357  
1358 915 my @dirs = @{$self->{'config_dirs'}};
1359 915 ▶ if($self->{'config_file'} && (scalar(@dirs) > 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"config_file"} and scalar @dirs > 1) 3 912 915
Condition100%3/3
$self->{"config_file"} and scalar @dirs > 1
!ll&&!rl&&r
846663
MC/DC100%2/2
$self->{"config_file"} and scalar @dirs > 1
$self->{"config_file"} scalar @dirs > 1
Truth table100%3/3
A and B
A= $self->{"config_file"}B= scalar @dirs > 1
ABresult
0X0
100
111
1360 3 ▶ if(File::Spec->file_name_is_absolute($self->{'config_file'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ('File::Spec'->file_name_is_absolute($self->{'config_file'})) { } 1 2 3
1361 # Handle absolute paths
1362 1 @dirs = ('');
1363 } else {
1364 # Look in the current directory
1365 2 push @dirs, File::Spec->curdir();
1366 }
1367 }
1368 915 for my $dir (@dirs) {
1369 377 ▶ next if(!defined($dir));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir 1 376 377
1370  
1371 # Newcastle Connection: /../hostname/path means read from a remote host.
1372 # /../ is unreachable on any real filesystem, so this is unambiguous.
1373 # When the hostname resolves to the local machine (localhost, 127.0.0.1,
1374 # ::1, or the system hostname) the /../host/ wrapper is unwrapped and the
1375 # enclosed path is processed through the normal local pipeline instead.
1376 376 my $effective_dir = $dir;
1377 376 ▶ if(my ($host, $remote_dir) = $self->_parse_remote_dir($dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = $self->_parse_remote_dir($dir)) 5 371 376
1378 5 ▶ if($self->_is_local_host($host)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_local_host($host)) { } 4 1 5
1379 4 $effective_dir = $remote_dir;
1380 } else {
1381 1 $self->_load_remote_dir($host, $remote_dir, \%merged, \@_file_list);
1382 1 next;
1383 }
1384 }
1385  
1386 375 ▶ if(length($effective_dir) && !-d $effective_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $effective_dir and not -d $effective_dir) 43 332 375
Condition100%3/3
length $effective_dir and not -d $effective_dir
!ll&&!rl&&r
3529743
MC/DC100%2/2
length $effective_dir and not -d $effective_dir
length $effective_dir not -d $effective_dir
Truth table100%3/3
A and not(B)
A= length $effective_dirB= not -d $effective_dir
ABresult
0X0
100
111
1387 43 next;
1388 }
1389  
1390 332 for my $file (@_file_list) {
1391 4976 my $path = File::Spec->catfile($effective_dir, $file);
1392 4976 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 112 4864 4976
1393 112 $logger->debug(ref($self), ' ', __LINE__, ": Looking for configuration $path");
1394 }
1395 4976 ▶ next unless -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 4681 295 4976
1396 295 ▶ next unless -r $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $path 1 294 295
1397  
1398 294 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 4 290 294
1399 4 $logger->debug(ref($self), ' ', __LINE__, ": Loading data from $path");
1400 }
1401  
1402 294 my $data;
1403 # Only load config modules when they are needed
1404 294 ▶ if ($file =~ /\.ya?ml$/) {
Branch: 6 branches
BranchTrueFalseTotal
if ($file =~ /\.ya?ml$/) { } 219 75 294
elsif ($file =~ /\.json$/) { } 15 60 75
elsif ($file =~ /\.xml$/) { } 22 38 60
elsif ($file =~ /\.ini$/) { } 18 20 38
elsif ($file =~ /\.toml$/) { } 10 10 20
elsif ($file =~ /\.conf$/) { } 10 0 10
1405 219 $self->_load_driver('YAML::XS', ['LoadFile']);
1406 219 $data = eval { LoadFile($path) };
1407 219 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 7 212 219
1408 7 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) { } 1 6 7
1409 1 $logger->notice("Failed to load YAML from $path: $@");
1410 } else {
1411 6 Carp::carp("Failed to load YAML from $path: $@");
1412 }
1413 7 next;
1414 }
1415 212 ▶ $data = $self->_sanitize_yaml_values($data) if defined($data) && ref($data);
Branch: 1 branch
BranchTrueFalseTotal
if defined $data and ref $data 208 4 212
Condition100%3/3
defined $data and ref $data
!ll&&!rl&&r
22208
MC/DC100%2/2
defined $data and ref $data
defined $data ref $data
Truth table100%3/3
A and B
A= defined $dataB= ref $data
ABresult
0X0
100
111
1416 } elsif ($file =~ /\.json$/) {
1417 15 $data = eval { decode_json(read_file($path)) };
1418 15 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 13 15
1419 2 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) { } 0 2 2
1420 0 $logger->notice("Failed to load JSON from $path: $@");
1421 } else {
1422 2 Carp::carp("Failed to load JSON from $path: $@");
1423 }
1424 2 next;
1425 }
1426 } elsif($file =~ /\.xml$/) {
1427 22 my $rc;
1428 22 ▶ if($self->_load_driver('XML::Simple', ['XMLin'])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_load_driver("XML::Simple", ["XMLin"])) 0 22 22
1429 0 my $xml_raw = eval { read_file($path) };
1430 0 ▶ if(defined($xml_raw) && $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $xml_raw and $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) { } 0 0 0
elsif (defined $xml_raw) { } 0 0 0
Condition0%0/3
defined $xml_raw and $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
!ll&&!rl&&r
000
MC/DC0%0/2
defined $xml_raw and $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
defined $xml_raw $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
Truth table0%0/3
A and B
A= defined $xml_rawB= $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
ABresult
0X0
100
111
1431 0 Carp::carp(ref($self) . ": skipping $path: XML external entity declarations not permitted");
1432 } elsif(defined($xml_raw)) {
1433 0 eval { $rc = XMLin(\$xml_raw, ForceArray => 0, KeyAttr => []) };
1434 0 ▶ if($@) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 0 0 0
elsif ($rc) { } 0 0 0
1435 0 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) { } 0 0 0
1436 0 $logger->notice("Failed to load XML from $path: $@");
1437 } else {
1438 0 Carp::carp("Failed to load XML from $path: $@");
1439 }
1440 0 undef $rc;
1441 } elsif($rc) {
1442 0 $data = $rc;
1443 }
1444 }
1445 }
1446 22 ▶ if((!defined($rc)) && $self->_load_driver('XML::PP')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $rc and $self->_load_driver("XML::PP")) 21 1 22
Condition66%2/3
not defined $rc and $self->_load_driver("XML::PP")
!ll&&!rl&&r
0121
MC/DC50%1/2
not defined $rc and $self->_load_driver("XML::PP")
not defined $rc $self->_load_driver("XML::PP")
Truth table66%2/3
not(A) and B
A= not defined $rcB= $self->_load_driver("XML::PP")
ABresult
0X0
100
111
1447 21 my $xml_pp = XML::PP->new();
1448 21 $data = read_file($path);
1449 21 ▶ if(my $tree = $xml_pp->parse(\$data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tree = $xml_pp->parse(\$data)) 20 1 21
1450 20 ▶ if($data = $xml_pp->collapse_structure($tree)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data = $xml_pp->collapse_structure($tree)) 20 0 20
1451 20 $self->{'type'} = 'XML';
1452 20 ▶ if($data->{'config'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{"config"}) 16 4 20
1453 16 $data = $data->{'config'};
1454 }
1455 }
1456 }
1457 }
1458 } elsif ($file =~ /\.ini$/) {
1459 18 $self->_load_driver('Config::IniFiles');
1460 18 ▶ if(my $ini = Config::IniFiles->new(-file => $path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ini = 'Config::IniFiles'->new('-file', $path)) { } 15 3 18
1461 $data = { map {
1462 15 my $section = $_;
1463 17 $section => { map { $_ => $ini->val($section, $_) } $ini->Parameters($section) }
1464 } $ini->Sections() };
1465 } else {
1466 3 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) { } 0 3 3
1467 0 $logger->notice("Failed to load INI from $path: $@");
1468 } else {
1469 3 Carp::carp("Failed to load INI from $path: $@");
1470 }
1471 }
1472 } elsif ($file =~ /\.toml$/) {
1473 10 ▶ if($self->_load_driver('TOML::Tiny', ['from_toml'])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_load_driver("TOML::Tiny", ["from_toml"])) 9 1 10
1474 # scalar() forces read_file into scalar context; without it
1475 # read_file returns a list of lines and from_toml (no prototype)
1476 # only sees the first line.
1477 9 my ($toml_data, $toml_err) = from_toml(scalar(read_file($path)));
1478 9 ▶ if($toml_err) {
Branch: 2 branches
BranchTrueFalseTotal
if ($toml_err) { } 1 8 9
elsif (ref $toml_data eq 'HASH' and scalar keys %$toml_data) { } 8 0 8
1479 1 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) { } 0 1 1
1480 0 $logger->notice("Failed to load TOML from $path: $toml_err");
1481 } else {
1482 1 Carp::carp("Failed to load TOML from $path: $toml_err");
1483 }
1484 ▶ } elsif(ref($toml_data) eq 'HASH' && scalar(keys %$toml_data)) {
Condition50%1/2
ref $toml_data eq "HASH" and scalar keys %$toml_data
!ll
08
MC/DC0%0/1
ref $toml_data eq "HASH" and scalar keys %$toml_data
ref $toml_data eq "HASH"
Truth table50%1/2
A
A= ref $toml_data eq "HASH"
Aresult
00
11
1485 8 $data = $toml_data;
1486 }
1487 }
1488 } elsif ($file =~ /\.conf$/) {
1489 10 $data = $self->_load_config_general($path);
1490 }
1491 285 ▶ if($data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data) 274 11 285
1492 274 ▶ if(!ref($data)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $data) 3 271 274
1493 3 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 1 2 3
1494 1 $logger->debug(ref($self), ' ', __LINE__, ": ignoring data from $path ($data)");
1495 }
1496 3 next;
1497 }
1498 271 ▶ if(ref($data) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH") 4 267 271
1499 4 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 1 3 4
1500 1 $logger->debug(ref($self), ' ', __LINE__, ": ignoring data from $path (not a hashref)");
1501 }
1502 4 next;
1503 }
1504 267 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 1 266 267
1505 1 $logger->debug(ref($self), ' ', __LINE__, ": Loaded data from $path");
1506 }
1507 267 my ($full, $inc_paths);
1508 267 ($data, $full, $inc_paths) = $self->_process_includes($data, $path);
1509 261 push @{$self->{'_source_records'}}, {
1510 type => 'file',
1511 label => $path,
1512 flat_data => { _flatten_keys($data) },
1513 };
1514 261 %merged = %{ merge( $full, \%merged ) };
1515 261 push @{$merged{'config_path'}}, $path, @{$inc_paths};
1516 }
1517 }
1518  
1519 # Put $self->{config_file} through all parsers, ignoring all errors, then merge that in
1520 326 ▶ if(!$self->{'script_name'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"script_name"}) 309 17 326
1521 309 ▶ require File::Basename && File::Basename->import() unless File::Basename->can('basename');
Branch: 1 branch
BranchTrueFalseTotal
unless "File::Basename"->can("basename") 0 309 309
Condition16%1/6
'File::Basename'->can('basename') || require File::Basename && 'File::Basename'->import
l!l&&r!l&&!r
30900
require File::Basename and "File::Basename"->import
!ll&&!rl&&r
000
MC/DC0%0/3
'File::Basename'->can('basename') || require File::Basename && 'File::Basename'->import
'File::Basename'->can('basename') require File::Basename "File::Basename"->import
Truth table0%0/4
A || B and C
A= 'File::Basename'->can('basename')B= require File::BasenameC= "File::Basename"->import
ABCresult
1XX1
0111
00X0
0100
1522  
1523 # Determine script name
1524 309 ▶ $self->{'script_name'} = File::Basename::basename($ENV{'SCRIPT_NAME'} || $0);
Condition66%2/3
$ENV{'SCRIPT_NAME'} || $0
l!l&&r!l&&!r
23070
MC/DC0%0/2
$ENV{'SCRIPT_NAME'} || $0
$ENV{'SCRIPT_NAME'} $0
Truth table66%2/3
A || B
A= $ENV{'SCRIPT_NAME'}B= $0
ABresult
1X1
011
000
1525 }
1526  
1527 326 my $script_name = $self->{'script_name'};
1528 326 for my $config_file ('default', $script_name, "$script_name.cfg", "$script_name.conf", "$script_name.config", $self->{'config_file'}, @{$self->{'config_files'}}) {
1529 1970 ▶ next unless defined($config_file);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $config_file 255 1715 1970
1530 1715 ▶ my $path = length($effective_dir) ? File::Spec->catfile($effective_dir, $config_file) : $config_file;
Branch: 1 branch
BranchTrueFalseTotal
length $effective_dir ? : 1505 210 1715
1531 1715 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 44 1671 1715
1532 44 $logger->debug(ref($self), ' ', __LINE__, ": Looking for configuration $path");
1533 }
1534 1715 ▶ if((-f $path) && (-r $path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $path and -r $path) 78 1637 1715
Condition100%3/3
-f $path and -r $path
!ll&&!rl&&r
1636178
MC/DC100%2/2
-f $path and -r $path
-f $path -r $path
Truth table100%3/3
A and B
A= -f $pathB= -r $path
ABresult
0X0
100
111
1535 # Never read the running script as its own configuration. Its
1536 # name is on the list above, and the Config::Auto fallback below
1537 # would eval it as Perl, running the program again inside
1538 # itself. Comparing real paths catches every way of reaching
1539 # it - CONFIG_DIR set to the script's own directory, a symlink,
1540 # a relative path - where comparing names in the current
1541 # directory only caught one.
1542 78 ▶ if(defined($_RUNNING_SCRIPT) && (my $real_path = Cwd::abs_path($path))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_RUNNING_SCRIPT and my $real_path = Cwd::abs_path($path)) 78 0 78
Condition33%1/3
defined $_RUNNING_SCRIPT and my $real_path = Cwd::abs_path($path)
!ll&&!rl&&r
0078
MC/DC0%0/2
defined $_RUNNING_SCRIPT and my $real_path = Cwd::abs_path($path)
defined $_RUNNING_SCRIPT my $real_path = Cwd::abs_path($path)
Truth table33%1/3
A and B
A= defined $_RUNNING_SCRIPTB= my $real_path = Cwd::abs_path($path)
ABresult
0X0
100
111
1543 78 ▶ if($real_path eq $_RUNNING_SCRIPT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($real_path eq $_RUNNING_SCRIPT) 2 76 78
1544 2 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 0 2 2
1545 0 $logger->debug(ref($self), ' ', __LINE__, ": Skipping $path: it is the running script");
1546 }
1547 2 next;
1548 }
1549 }
1550 76 my $data = read_file($path);
1551 # A file that starts with #! is a program, not configuration,
1552 # whatever it is called and wherever it is: for example a copy
1553 # of the script. It must never reach the Perl parsers below.
1554 76 ▶ if($data =~ /\A#!/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data =~ /\A#!/) 1 75 76
1555 1 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 0 1 1
1556 0 $logger->debug(ref($self), ' ', __LINE__, ": Skipping $path: it is a program (starts with #!)");
1557 }
1558 1 next;
1559 }
1560 75 my $raw_content = $data;
1561 75 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 4 71 75
1562 4 $logger->debug(ref($self), ' ', __LINE__, ": Loading data from $path");
1563 }
1564 75 eval {
1565 75 ▶ if(($data =~ /^\s*<\?xml/) || ($data =~ /<\/[^>]+>/)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($data =~ /^\s*<\?xml/ or $data =~ m[</[^>]+>]) { } 14 61 75
elsif ($data =~ / \{ # opening brace .+ # key material; dot matches newlines because of the s modifier : # colon separator . # one value character \} # closing brace /sx) { } 5 56 61
Condition100%3/3
$data =~ /^\s*<\?xml/ or $data =~ m[</[^>]+>]
l!l&&r!l&&!r
10461
MC/DC100%2/2
$data =~ /^\s*<\?xml/ or $data =~ m[</[^>]+>]
$data =~ /^\s*<\?xml/ $data =~ m[</[^>]+>]
Truth table100%3/3
A or B
A= $data =~ /^\s*<\?xml/B= $data =~ m[</[^>]+>]
ABresult
1X1
011
000
1566 14 ▶ if($self->_load_driver('XML::Simple', ['XMLin'])) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_load_driver('XML::Simple', ['XMLin'])) { } 0 14 14
elsif ($self->_load_driver('XML::PP')) { } 14 0 14
1567 0 ▶ if($data =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) { } 0 0 0
1568 0 Carp::carp(ref($self) . ": skipping $path: XML external entity declarations not permitted");
1569 0 undef $data;
1570 } else {
1571 0 my $xml_data = eval { XMLin(\$data, ForceArray => 0, KeyAttr => []) };
1572 0 my $xml_err = $@;
1573 0 ▶ if($xml_data) {
Branch: 2 branches
BranchTrueFalseTotal
if ($xml_data) { } 0 0 0
elsif ($xml_err) { } 0 0 0
1574 0 $data = $xml_data;
1575 0 $self->{'type'} = 'XML';
1576 } elsif($xml_err) {
1577 # Apache-style <block>...</block> looks like XML. Real XML, which
1578 # starts with a declaration, is never second-guessed.
1579 0 ▶ my $general = ($data !~ /^\s*<\?xml/) ? $self->_load_config_general($path, $data) : undef;
Branch: 1 branch
BranchTrueFalseTotal
!($data =~ /^\s*<\?xml/) ? : 0 0 0
1580 0 ▶ die $xml_err unless($general);
Branch: 1 branch
BranchTrueFalseTotal
unless $general 0 0 0
1581 0 $data = $general;
1582 0 $self->{'type'} = 'Config::General';
1583 }
1584 }
1585 } elsif($self->_load_driver('XML::PP')) {
1586 14 my $xml_pp = XML::PP->new();
1587 14 ▶ if(my $tree = $xml_pp->parse(\$data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tree = $xml_pp->parse(\$data)) 13 1 14
1588 13 ▶ if($data = $xml_pp->collapse_structure($tree)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data = $xml_pp->collapse_structure($tree)) 13 0 13
1589 13 $self->{'type'} = 'XML';
1590 13 ▶ if($data->{'config'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{"config"}) 9 4 13
1591 9 $data = $data->{'config'};
1592 }
1593 }
1594 }
1595 }
1596 } elsif($data =~ /
1597 \{ # opening brace
1598 .+ # key material; dot matches newlines because of the s modifier
1599 : # colon separator
1600 . # one value character
1601 \} # closing brace
1602 /xs) {
1603 5 $self->_load_driver('JSON::Parse');
1604 # CPanel::JSON is very noisy, so be careful before attempting to use it
1605 5 my $is_json;
1606 5 eval { $is_json = JSON::Parse::parse_json($data) };
1607 5 ▶ if($is_json) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_json) { } 4 1 5
1608 4 eval { $data = decode_json($data) };
1609 4 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 3 4
1610 1 undef $data;
1611 }
1612 } else {
1613 1 undef $data;
1614 }
1615 5 ▶ if($data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data) 3 2 5
1616 3 $self->{'type'} = 'JSON';
1617 }
1618 } else {
1619 56 undef $data;
1620 }
1621 75 ▶ if(!$data && $raw_content !~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($data or $raw_content =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) 57 18 75
Condition100%3/3
$data or $raw_content =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
l!l&&r!l&&!r
17157
MC/DC100%2/2
$data or $raw_content =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
$data $raw_content =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
Truth table100%3/3
A or B
A= $dataB= $raw_content =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
ABresult
1X1
011
000
1622 57 $self->_load_driver('YAML::XS', ['LoadFile']);
1623 57 ▶ if((eval { $data = LoadFile($path) }) && (ref($data) eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { $data = LoadFile($path) } } and ref $data eq "HASH") 42 15 57
Condition100%3/3
eval { do { $data = LoadFile($path) } } and ref $data eq "HASH"
!ll&&!rl&&r
8742
MC/DC100%2/2
eval { do { $data = LoadFile($path) } } and ref $data eq "HASH"
eval { do { $data = LoadFile($path) } } ref $data eq "HASH"
Truth table100%3/3
A and B
A= eval { do { $data = LoadFile($path) } }B= ref $data eq "HASH"
ABresult
0X0
100
111
1624 42 $data = $self->_sanitize_yaml_values($data);
1625 # Could be colon file, could be YAML, whichever it is break the configuration fields
1626 # foreach my($k, $v) (%{$data}) {
1627 42 foreach my $k (keys %{$data}) {
1628 66 my $v = $data->{$k};
1629 66 ▶ if(!defined($v)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v) 2 64 66
1630 # e.g. a simple line
1631 # foo:
1632 # with nothing under it
1633 2 $data->{$k} = undef;
1634 2 next;
1635 }
1636 # Do not inspect or modify coderefs, blessed objects, or any reference
1637 64 ▶ next unless _is_plain_scalar($v);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_plain_scalar($v) 2 62 64
1638  
1639 62 ▶ next if($v =~ /^"[^"]+"$/); # Single-quoted field - skip comma-splitting
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /^"[^"]+"$/ 1 61 62
1640 61 ▶ if($v =~ /,/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /,/) 5 56 61
1641 5 my @vals = split(/\s*,\s*/, $v);
1642 5 delete $data->{$k};
1643 5 foreach my $val (@vals) {
1644 11 ▶ if($val =~ /([^=]+)=(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($val =~ /([^=]+)=(.+)/) { } 8 3 11
1645 8 $data->{$k}{$1} = $2;
1646 } else {
1647 3 $data->{$k}{$val} = 1;
1648 }
1649 }
1650 }
1651 }
1652 42 ▶ if($data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data) 42 0 42
1653 42 $self->{'type'} = 'YAML';
1654 }
1655 }
1656 57 ▶ if((!$data) || (ref($data) ne 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $data or ref $data ne "HASH") 15 42 57
Condition100%3/3
not $data or ref $data ne "HASH"
l!l&&r!l&&!r
8742
MC/DC100%2/2
not $data or ref $data ne "HASH"
not $data ref $data ne "HASH"
Truth table100%3/3
not(A) or B
A= not $dataB= ref $data ne "HASH"
ABresult
1X1
011
000
1657 15 ▶ if($self->_load_driver('TOML::Tiny', ['from_toml'])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_load_driver("TOML::Tiny", ["from_toml"])) 15 0 15
1658 # scalar() forces read_file into scalar context; without it
1659 # read_file returns a list of lines and from_toml (no prototype)
1660 # only sees the first line.
1661 15 my ($toml_data, $toml_err) = eval { from_toml(scalar(read_file($path))) };
1662 15 ▶ if(!$toml_err && ref($toml_data) eq 'HASH' && scalar(keys %$toml_data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $toml_err and ref $toml_data eq "HASH" and scalar keys %$toml_data) 1 14 15
Condition80%4/5
not $toml_err and ref $toml_data eq "HASH" and scalar keys %$toml_data
!ll
123
not $toml_err and ref $toml_data eq "HASH"
!ll&&!rl&&r
1203
MC/DC50%1/2
not $toml_err and ref $toml_data eq "HASH" and scalar keys %$toml_data
not $toml_err ref $toml_data eq "HASH"
Truth table66%2/3
not(A) and B
A= not $toml_errB= ref $toml_data eq "HASH"
ABresult
0X0
100
111
1663 1 $data = $toml_data;
1664 1 $self->{'type'} = 'TOML';
1665 }
1666 }
1667 }
1668 57 ▶ if((!$data) || (ref($data) ne 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $data or ref $data ne "HASH") 14 43 57
Condition100%3/3
not $data or ref $data ne "HASH"
l!l&&r!l&&!r
7743
MC/DC100%2/2
not $data or ref $data ne "HASH"
not $data ref $data ne "HASH"
Truth table100%3/3
not(A) or B
A= not $dataB= ref $data ne "HASH"
ABresult
1X1
011
000
1669 14 $self->_load_driver('Config::IniFiles');
1670 14 ▶ if(my $ini = Config::IniFiles->new(-file => $path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ini = "Config::IniFiles"->new("-file", $path)) 4 10 14
1671 $data = { map {
1672 4 my $section = $_;
1673 5 $section => { map { $_ => $ini->val($section, $_) } $ini->Parameters($section) }
1674 } $ini->Sections() };
1675 4 ▶ if($data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data) 4 0 4
1676 4 $self->{'type'} = 'INI';
1677 }
1678 }
1679 14 ▶ if((!$data) || (ref($data) ne 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $data or ref $data ne "HASH") 10 4 14
Condition100%3/3
not $data or ref $data ne "HASH"
l!l&&r!l&&!r
374
MC/DC100%2/2
not $data or ref $data ne "HASH"
not $data ref $data ne "HASH"
Truth table100%3/3
not(A) or B
A= not $dataB= ref $data ne "HASH"
ABresult
1X1
011
000
1680 # Maybe XML without the leading XML header
1681 10 ▶ if($self->_load_driver('XML::Simple', ['XMLin'])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_load_driver("XML::Simple", ["XMLin"])) 0 10 10
1682 0 my $xml_raw = eval { read_file($path) };
1683 0 ▶ if(defined($xml_raw) && $xml_raw !~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $xml_raw and not $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) 0 0 0
Condition0%0/3
defined $xml_raw and not $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
!ll&&!rl&&r
000
MC/DC0%0/2
defined $xml_raw and not $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
defined $xml_raw not $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
Truth table0%0/3
A and not(B)
A= defined $xml_rawB= not $xml_raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i
ABresult
0X0
100
111
1684 0 eval { $data = XMLin(\$xml_raw, ForceArray => 0, KeyAttr => []) };
1685 }
1686 }
1687 10 ▶ if((!$data) || (ref($data) ne 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $data or ref $data ne "HASH") 10 0 10
Condition66%2/3
not $data or ref $data ne "HASH"
l!l&&r!l&&!r
370
MC/DC0%0/2
not $data or ref $data ne "HASH"
not $data ref $data ne "HASH"
Truth table66%2/3
not(A) or B
A= not $dataB= ref $data ne "HASH"
ABresult
1X1
011
000
1688 10 ▶ if($self->_load_driver('Config::Abstract')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_load_driver("Config::Abstract")) 0 10 10
1689 # Handle RT#164587
1690 0 open my $oldSTDERR, '>&STDERR';
1691 0 close STDERR;
1692 0 eval { $data = Config::Abstract->new($path) };
1693 0 my $err = $@;
1694 0 open STDERR, '>&', $oldSTDERR;
1695 0 ▶ if($err) {
Branch: 2 branches
BranchTrueFalseTotal
if ($err) { } 0 0 0
elsif ($data) { } 0 0 0
1696 0 undef $data;
1697 } elsif($data) {
1698 0 $data = $data->get_all_settings();
1699 0 ▶ if(scalar(keys %{$data}) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$data;} == 0) 0 0 0
1700 0 undef $data;
1701 }
1702 }
1703 0 $self->{'type'} = 'Perl';
1704 }
1705 }
1706 10 ▶ if((!$data) || (ref($data) ne 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $data or ref $data ne "HASH") 10 0 10
Condition66%2/3
not $data or ref $data ne "HASH"
l!l&&r!l&&!r
370
MC/DC0%0/2
not $data or ref $data ne "HASH"
not $data ref $data ne "HASH"
Truth table66%2/3
not(A) or B
A= not $dataB= ref $data ne "HASH"
ABresult
1X1
011
000
1707 10 $self->_load_driver('Config::Auto');
1708 # Config::Auto dies on content it mistakes for XML, which would skip the
1709 # Config::General attempt below; keep the error and raise it only if
1710 # nothing else reads the file.
1711 10 my $auto_err;
1712 10 eval {
1713 10 my $ca = Config::Auto->new(source => $path);
1714 10 ▶ if($data = $ca->parse()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data = $ca->parse) 5 2 7
1715 5 $self->{'type'} = $ca->format();
1716 }
1717 };
1718 10 $auto_err = $@;
1719 10 ▶ if((!$data) || (ref($data) ne 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $data or ref $data ne "HASH") 5 5 10
Condition100%3/3
not $data or ref $data ne "HASH"
l!l&&r!l&&!r
325
MC/DC100%2/2
not $data or ref $data ne "HASH"
not $data ref $data ne "HASH"
Truth table100%3/3
not(A) or B
A= not $dataB= ref $data ne "HASH"
ABresult
1X1
011
000
1720 # Last resort: Apache-style configuration
1721 5 ▶ if($data = $self->_load_config_general($path, $raw_content)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data = $self->_load_config_general($path, $raw_content)) 3 2 5
1722 3 $self->{'type'} = 'Config::General';
1723 3 undef $auto_err;
1724 }
1725 }
1726 10 ▶ die $auto_err if($auto_err);
Branch: 1 branch
BranchTrueFalseTotal
if $auto_err 0 10 10
1727 }
1728 }
1729 }
1730 }
1731 };
1732 75 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 4 71 75
1733 4 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 4 4
1734 0 $logger->warn(ref($self), ' ', __LINE__, ": $@");
1735 0 undef $data;
1736 } else {
1737 4 $logger->debug(ref($self), ' ', __LINE__, ': Loaded data from', $self->{'type'}, "file $path");
1738 }
1739 }
1740 75 my ($full, $inc_paths) = ($data, []);
1741 75 ▶ if($data && ref($data) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($data and ref $data eq "HASH") 71 4 75
Condition100%3/3
$data and ref $data eq "HASH"
!ll&&!rl&&r
3171
MC/DC100%2/2
$data and ref $data eq "HASH"
$data ref $data eq "HASH"
Truth table100%3/3
A and B
A= $dataB= ref $data eq "HASH"
ABresult
0X0
100
111
1742 71 ($data, $full, $inc_paths) = $self->_process_includes($data, $path);
1743 71 push @{$self->{'_source_records'}}, {
1744 type => 'file',
1745 label => $path,
1746 flat_data => { _flatten_keys($data) },
1747 };
1748 }
1749 75 ▶ if(scalar(keys %merged)) {
Branch: 3 branches
BranchTrueFalseTotal
if (scalar keys %merged) { } 24 51 75
elsif ($full and ref $full eq 'HASH') { } 48 3 51
elsif (not $@ and $logger) { } 1 2 3
1750 24 ▶ if($full) {
Branch: 1 branch
BranchTrueFalseTotal
if ($full) 23 1 24
1751 23 %merged = %{ merge($full, \%merged) };
1752 }
1753 ▶ } elsif($full && (ref($full) eq 'HASH')) {
Condition100%3/3
$full and ref $full eq "HASH"
!ll&&!rl&&r
2148
MC/DC100%2/2
$full and ref $full eq "HASH"
$full ref $full eq "HASH"
Truth table100%3/3
A and B
A= $fullB= ref $full eq "HASH"
ABresult
0X0
100
111
1754 48 %merged = %{$full};
1755 ▶ } elsif((!$@) && $logger) {
Condition66%2/3
not $@ and $logger
!ll&&!rl&&r
021
MC/DC50%1/2
not $@ and $logger
not $@ $logger
Truth table66%2/3
not(A) and B
A= not $@B= $logger
ABresult
0X0
100
111
1756 1 $logger->debug(ref($self), ' ', __LINE__, ': No configuration file loaded');
1757 }
1758  
1759 75 push @{$merged{'config_path'}}, $path, @{$inc_paths};
1760 }
1761 }
1762 }
1763  
1764 # Merge ENV vars
1765 909 my $prefix = $self->{env_prefix};
1766 909 $prefix =~ s/__$//;
1767 909 $prefix =~ s/_$//;
1768 909 $prefix =~ s/::$//;
1769 909 for my $key (keys %ENV) {
1770 29892 ▶ next unless $key =~ /^\Q$self->{env_prefix}\E(.*)$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $key =~ /^\Q$self->{"env_prefix"}\E(.*)$/i 29822 70 29892
1771 70 my $path = lc($1);
1772 70 ▶ if($path =~ /__/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /__/) { } 45 25 70
1773 45 my @parts = split /__/, $path;
1774 45 my $ref = \%merged;
1775 45 ▶ $ref = ($ref->{$_} //= {}) for @parts[0..$#parts-1];
Condition100%2/2
$ref->{$_} //= {}
l!l
389
MC/DC100%1/1
$ref->{$_} //= {}
$ref->{$_}
Truth table100%2/2
A
A= $ref->{$_}
Aresult
11
00
1776 45 $ref->{ $parts[-1] } = $ENV{$key};
1777 45 push @{$self->{'_source_records'}}, {
1778 type => 'env',
1779 label => $key,
1780 45 flat_data => { join('.', @parts) => $ENV{$key} },
1781 };
1782 } else {
1783 25 $merged{$prefix}->{$path} = $ENV{$key};
1784 25 push @{$self->{'_source_records'}}, {
1785 type => 'env',
1786 label => $key,
1787 25 flat_data => { "$prefix.$path" => $ENV{$key} },
1788 };
1789 }
1790 }
1791  
1792 # Merge command line options
1793 909 foreach my $arg(@ARGV) {
1794 35 ▶ next unless($arg =~ /=/);
Branch: 1 branch
BranchTrueFalseTotal
unless $arg =~ /=/ 7 28 35
1795 28 my ($key, $value) = split(/=/, $arg, 2);
1796 28 ▶ next unless $key =~ /^--\Q$self->{env_prefix}\E(.*)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $key =~ /^--\Q$self->{"env_prefix"}\E(.*)$/ 4 24 28
1797  
1798 24 my $path = lc($1);
1799 24 my @parts = split(/__/, $path);
1800 24 ▶ if(scalar(@parts) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @parts > 0) 24 0 24
1801 24 my $ref = \%merged;
1802 24 ▶ if(scalar(@parts) > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @parts > 1) 13 11 24
1803 13 ▶ $ref = ($ref->{$_} //= {}) for @parts[0..$#parts-1];
Condition100%2/2
$ref->{$_} //= {}
l!l
131
MC/DC100%1/1
$ref->{$_} //= {}
$ref->{$_}
Truth table100%2/2
A
A= $ref->{$_}
Aresult
11
00
1804 }
1805 24 $ref->{$parts[-1]} = $value;
1806 24 push @{$self->{'_source_records'}}, {
1807 type => 'argv',
1808 label => $arg,
1809 flat_data => { join('.', @parts) => $value },
1810 };
1811 }
1812 }
1813  
1814 909 ▶ if($self->{'interpolate'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"interpolate"}) 23 886 909
1815 23 %merged = %{ $self->_interpolate_tree(\%merged) };
1816 }
1817  
1818 901 ▶ if($self->{'flatten'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'flatten'}) { } 32 869 901
1819 32 $self->_load_driver('Hash::Flatten', ['flatten']);
1820 } else {
1821 869 $self->_load_driver('Hash::Flatten', ['unflatten']);
1822 }
1823 # $self->{config} = $self->{flatten} ? flatten(\%merged) : unflatten(\%merged);
1824 # Don't unflatten because of RT#166761
1825 901 ▶ $self->{config} = $self->{flatten} ? flatten(\%merged) : \%merged;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'flatten'} ? : 32 869 901
1826  
1827 901 Hash::Merge::set_clone_behavior($saved_clone);
1828  
1829 901 ▶ if(my $enc_key = $self->_get_encryption_key()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $enc_key = $self->_get_encryption_key) 59 838 897
1830 59 $self->_decrypt_config_values($self->{'config'}, $enc_key);
1831 }
1832 }
1833  
1834 =head2 get(key)
1835  
1836 Retrieve a configuration value using dotted key notation (e.g.,
1837 C<'database.user'>). Returns C<undef> if the key doesn't exist or if
1838 C<key> is C<undef>.
1839  
1840 =head3 EXAMPLE
1841  
1842 my $cfg = Config::Abstraction->new(
1843 data => { database => { host => 'localhost', port => 5432 } },
1844 config_dirs => [],
1845 );
1846  
1847 my $host = $cfg->get('database.host'); # 'localhost'
1848 my $port = $cfg->get('database.port'); # 5432
1849 my $miss = $cfg->get('database.user'); # undef -- key absent
1850  
1851 =head3 API SPECIFICATION
1852  
1853 =head4 Input
1854  
1855 key -- SCALAR -- dotted key path (e.g. 'database.host').
1856 C<undef> is allowed and returns C<undef> silently.
1857  
1858 =head4 Output
1859  
1860 SCALAR or reference -- the value stored under C<key>, or C<undef> if absent.
1861  
1862 =head3 MESSAGES
1863  
1864 (none) -- missing keys return undef, no warning is raised.
1865  
1866 =head3 PSEUDOCODE
1867  
1868 if key is undef: return undef
1869 call _ensure_loaded
1870 if flatten mode: return config[key] (direct lookup)
1871 parts = split sep_char from key
1872 ref = config hashref
1873 for each part:
1874 if ref is not a HASH: return undef
1875 if part not in ref: return undef
1876 ref = ref[part]
1877 return ref
1878  
1879 =cut
1880  
1881 sub get
1882 708 ▶{
Subroutine get: called CC=13 SCAR=27.1
Pod documented
1883 708 my ($self, $key) = @_;
1884  
1885 708 ▶ return undef unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 5 703 708
1886  
1887 703 $self->_ensure_loaded();
1888  
1889 699 ▶ if($self->{flatten}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"flatten"}) 19 680 699
1890 19 return $self->{config}{$key};
1891 }
1892 680 my $ref = $self->{'config'};
1893 680 for my $part (split $self->{'_sep_re'}, $key) {
1894 872 ▶ return undef unless ref $ref eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ref eq "HASH" 4 868 872
1895 868 ▶ return unless exists $ref->{$part};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $ref->{$part} 33 835 868
1896 835 $ref = $ref->{$part};
1897 }
1898 643 ▶ if((defined($ref) && (ref($ref) eq 'HASH') && !$self->{'no_fixate'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ref and ref $ref eq "HASH" and not $self->{"no_fixate"}) 35 608 643
Condition100%6/6
defined $ref and ref $ref eq "HASH" and not $self->{"no_fixate"}
!ll&&!rl&&r
605335
defined $ref and ref $ref eq "HASH"
!ll&&!rl&&r
1459138
MC/DC100%3/3
defined $ref and ref $ref eq "HASH" and not $self->{"no_fixate"}
defined $ref ref $ref eq "HASH" not $self->{"no_fixate"}
Truth table100%4/4
A and B and not(C)
A= defined $refB= ref $ref eq "HASH"C= not $self->{"no_fixate"}
ABCresult
0XX0
10X0
1100
1111
1899 35 ▶ if($self->_load_data_reuse()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_load_data_reuse) 0 35 35
1900 0 ▶ if(ref($ref) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $ref eq 'HASH') { } 0 0 0
elsif (ref $ref eq 'ARRAY') { } 0 0 0
1901 0 ▶ if(!tied %$ref) {
Branch: 1 branch
BranchTrueFalseTotal
unless (tied %$ref) 0 0 0
1902 # Pass the hashref directly (not dereferenced) so fixate receives
1903 # a named scalar it can make read-only without flattening the hash
1904 # FIXME:
1905 # What works on MacOS doesn't work
1906 # on Linux and vice versa.
1907 # Something is wrong.
1908 # Data::Reuse::fixate(%{$ref}) if scalar(keys %{$ref});
1909 # Data::Reuse::fixate($ref) if scalar(keys %{$ref});
1910 }
1911 } elsif(ref($ref) eq 'ARRAY') {
1912 # RT#171980
1913 # Data::Reuse::fixate(@{$ref});
1914 }
1915 }
1916 }
1917 643 return $ref;
1918 }
1919  
1920 sub _load_data_reuse
1921 43 ▶{
Subroutine _load_data_reuse: called CC=5 SCAR=16.5
1922 43 my $self = $_[0];
1923  
1924 # Skip fixation entirely if caller has opted out
1925 43 ▶ return 0 if($self->{'no_fixate'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"no_fixate"} 3 40 43
1926  
1927 # Return cached result to avoid repeated require attempts
1928 40 ▶ return 1 if($self->{reuse_loaded});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"reuse_loaded"} 1 39 40
1929 39 ▶ return 0 if($self->{reuse_failed});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"reuse_failed"} 12 27 39
1930  
1931 27 eval {
1932 27 require Data::Reuse;
1933 0 Data::Reuse->import();
1934 };
1935 27 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 27 0 27
1936 # Cache the failure so we do not attempt to load again
1937 27 $self->{reuse_failed} = 1;
1938 27 return 0;
1939 }
1940 0 $self->{reuse_loaded} = 1;
1941 0 return 1;
1942 }
1943  
1944 =head2 exists(key)
1945  
1946 Test whether a configuration key is present, using dotted key notation
1947 (e.g., C<'database.user'>). Returns C<1> when the key exists (even if its
1948 value is C<undef>), C<0> otherwise. Returns C<0> when C<key> is C<undef>.
1949  
1950 =head3 EXAMPLE
1951  
1952 my $cfg = Config::Abstraction->new(
1953 data => { timeout => undef, retries => 3 },
1954 config_dirs => [],
1955 );
1956  
1957 $cfg->exists('timeout'); # 1 -- key present even though value is undef
1958 $cfg->exists('retries'); # 1
1959 $cfg->exists('missing'); # 0
1960 $cfg->exists(undef); # 0
1961  
1962 =head3 API SPECIFICATION
1963  
1964 =head4 Input
1965  
1966 key -- SCALAR -- dotted key path. C<undef> returns C<0>.
1967  
1968 =head4 Output
1969  
1970 boolean
1971  
1972 =head3 MESSAGES
1973  
1974 (none)
1975  
1976 =cut
1977  
1978 sub exists
1979 56 ▶{
Subroutine exists: called CC=7 SCAR=19.5
Pod documented
1980 56 my ($self, $key) = @_;
1981  
1982 56 ▶ return 0 unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 3 53 56
1983  
1984 53 $self->_ensure_loaded();
1985  
1986 53 ▶ if($self->{flatten}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"flatten"}) 10 43 53
1987 10 ▶ return exists($self->{config}{$key}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $self->{'config'}{$key} ? : 5 5 10
1988 }
1989 43 my $ref = $self->{'config'};
1990 43 for my $part (split $self->{'_sep_re'}, $key) {
1991 55 ▶ return 0 unless ref $ref eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ref eq "HASH" 3 52 55
1992 52 ▶ return 0 if(!exists($ref->{$part}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $ref->{$part} 14 38 52
1993 38 $ref = $ref->{$part};
1994 }
1995 26 return 1;
1996 }
1997  
1998 =head2 all()
1999  
2000 Returns the entire merged configuration as a hashref, or C<undef> when no
2001 configuration data was found. When C<flatten =E<gt> 1> was given to the
2002 constructor the keys are dotted strings (e.g. C<'database.host'>); otherwise
2003 the hash is nested.
2004  
2005 The special key C<config_path> within the returned hashref is an arrayref
2006 listing every file that was loaded, in load order.
2007  
2008 =head3 EXAMPLE
2009  
2010 my $cfg = Config::Abstraction->new(
2011 data => { host => 'localhost', port => 5432 },
2012 config_dirs => [],
2013 );
2014  
2015 my $all = $cfg->all();
2016 # { host => 'localhost', port => 5432, config_path => [] }
2017  
2018 =head3 API SPECIFICATION
2019  
2020 =head4 Input
2021  
2022 (none)
2023  
2024 =head4 Output
2025  
2026 HASHREF -- the full merged config (includes C<config_path> key).
2027 undef -- when the merged config is empty and no data was supplied.
2028  
2029 =head3 MESSAGES
2030  
2031 (none) -- returns undef silently when empty.
2032  
2033 =cut
2034  
2035 sub all
2036 89 ▶{
Subroutine all: called CC=3 SCAR=11.0
Pod documented
2037 89 my $self = shift;
2038  
2039 89 $self->_ensure_loaded();
2040  
2041 89 ▶ return if(!$self->{config});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"config"} 1 88 89
2042  
2043 # This is good for debugging, but not much more and it breaks inheritance, so disabled
2044 # if($self->_load_data_reuse()) {
2045 # Data::Reuse::fixate($self->{config});
2046 # }
2047  
2048 88 ▶ return(scalar(keys %{$self->{'config'}})) ? $self->{'config'} : undef;
Branch: 1 branch
BranchTrueFalseTotal
scalar keys %{$$self{'config'};} ? : 86 2 88
2049 }
2050  
2051 =head2 explain_sources()
2052  
2053 Returns a hashref describing where each configuration key came from and in
2054 what order the sources that set it were applied.
2055  
2056 Each key of the returned hashref is a dotted key name (e.g. C<'database.user'>).
2057 The corresponding value is a hashref with two fields:
2058  
2059 =over 4
2060  
2061 =item * C<value>
2062  
2063 The final merged value for that key after all sources have been applied.
2064  
2065 =item * C<sources>
2066  
2067 An arrayref of hashrefs, ordered from lowest to highest precedence (i.e. the
2068 last element is always the winning source). Each entry has:
2069  
2070 =over 4
2071  
2072 =item * C<type> -- one of C<'data'>, C<'file'>, C<'env'>, or C<'argv'>
2073  
2074 =item * C<label> -- a human-readable identifier: a file path, an environment
2075 variable name (e.g. C<'APP_DATABASE__USER'>), a CLI argument string, or
2076 C<'constructor data argument'>
2077  
2078 =item * C<value> -- what this source set the key to (may differ from C<value>
2079 at the top level if a later source overrode it)
2080  
2081 =back
2082  
2083 =back
2084  
2085 Keys set by exactly one source have a single-element C<sources> list.
2086 Keys whose value was never overridden will show the same C<value> in both the
2087 top-level field and the sole C<sources> entry.
2088  
2089 =head3 USAGE EXAMPLE
2090  
2091 use Config::Abstraction;
2092  
2093 local $ENV{APP_HOST} = 'prod.example.com';
2094  
2095 my $cfg = Config::Abstraction->new(
2096 data => { host => 'localhost', port => 5432 },
2097 config_dirs => ['/etc/myapp'],
2098 );
2099  
2100 use Data::Dumper;
2101 print Dumper( $cfg->explain_sources() );
2102 # {
2103 # 'host' => {
2104 # value => 'prod.example.com',
2105 # sources => [
2106 # { type => 'data', label => 'constructor data argument', value => 'localhost' },
2107 # { type => 'env', label => 'APP_HOST', value => 'prod.example.com' },
2108 # ],
2109 # },
2110 # 'port' => {
2111 # value => 5432,
2112 # sources => [
2113 # { type => 'data', label => 'constructor data argument', value => 5432 },
2114 # ],
2115 # },
2116 # }
2117  
2118 =head3 API SPECIFICATION
2119  
2120 =head4 Input
2121  
2122 None (instance method; takes no arguments beyond C<$self>).
2123  
2124 =head4 Output
2125  
2126 HASHREF where each key is a dotted config key and each value is:
2127  
2128 {
2129 value => SCALAR,
2130 sources => [
2131 {
2132 type => 'data'|'file'|'env'|'argv',
2133 label => SCALAR,
2134 value => SCALAR,
2135 },
2136 ...
2137 ],
2138 }
2139  
2140 =cut
2141  
2142 sub explain_sources
2143 40 ▶{
Subroutine explain_sources: called CC=5 SCAR=16.1
Pod documented
2144 40 my $self = shift;
2145  
2146 40 $self->_ensure_loaded();
2147  
2148 40 my %final_flat = _flatten_keys($self->{'config'});
2149 40 my %result;
2150  
2151 40 for my $key (keys %final_flat) {
2152 85 my @key_sources;
2153 85 ▶ for my $layer (@{$self->{'_source_records'} // []}) {
Condition50%1/2
$self->{"_source_records"} // []
l!l
850
MC/DC0%0/1
$self->{"_source_records"} // []
$self->{"_source_records"}
Truth table50%1/2
A
A= $self->{"_source_records"}
Aresult
11
00
2154 109 ▶ if(exists $layer->{'flat_data'}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $layer->{"flat_data"}{$key}) 101 8 109
2155 push @key_sources, {
2156 type => $layer->{'type'},
2157 label => $layer->{'label'},
2158 101 value => $layer->{'flat_data'}{$key},
2159 };
2160 }
2161 }
2162 $result{$key} = {
2163 85 value => $final_flat{$key},
2164 sources => \@key_sources,
2165 };
2166 }
2167 40 return \%result;
2168 }
2169  
2170 # ---------------------------------------------------------------------------
2171 # _value_from_type -- scan _source_records for the last record of the given
2172 # type that provided a value for $key. Source records always use '.' as the
2173 # key separator regardless of sep_char, so we normalise $key before the lookup.
2174 #
2175 # Returns ($found, $value): $found is true when the source type contributed to
2176 # the key, letting callers distinguish "source set key to undef" from "source
2177 # never set it".
2178 # ---------------------------------------------------------------------------
2179 sub _value_from_type
2180 57 ▶{
Subroutine _value_from_type: called CC=7 SCAR=19.5
2181 57 my ($self, $type, $key) = @_;
2182  
2183 57 ▶ return (0, undef) unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 3 54 57
2184  
2185 54 $self->_ensure_loaded();
2186  
2187 54 my $sep = $self->{'sep_char'};
2188 54 ▶ my $flat_key = ($sep eq '.') ? $key : join('.', split /\Q$sep\E/, $key);
Branch: 1 branch
BranchTrueFalseTotal
$sep eq '.' ? : 52 2 54
2189  
2190 54 my ($found, $val);
2191 54 ▶ for my $layer (@{$self->{'_source_records'} // []}) {
Condition50%1/2
$self->{"_source_records"} // []
l!l
540
MC/DC0%0/1
$self->{"_source_records"} // []
$self->{"_source_records"}
Truth table50%1/2
A
A= $self->{"_source_records"}
Aresult
11
00
2192 93 ▶ next unless $layer->{'type'} eq $type;
Branch: 1 branch
BranchTrueFalseTotal
unless $layer->{"type"} eq $type 58 35 93
2193 35 ▶ if(exists $layer->{'flat_data'}{$flat_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $layer->{"flat_data"}{$flat_key}) 28 7 35
2194 28 $found = 1;
2195 28 $val = $layer->{'flat_data'}{$flat_key};
2196 }
2197 }
2198 54 return ($found, $val);
2199 }
2200  
2201 =head2 prefer_env(key)
2202  
2203 Return the value that an environment variable provided for C<key>, bypassing
2204 any later sources (e.g. CLI arguments) that may have overridden it.
2205 Falls back to the normal merged value from C<get(key)> when no environment
2206 variable contributed to C<key>.
2207  
2208 =head3 EXAMPLE
2209  
2210 local $ENV{APP_DATABASE__HOST} = 'env-host';
2211 my $host = $cfg->prefer_env('database.host');
2212 # Returns 'env-host' even if --APP_DATABASE__HOST=cli-host was also passed.
2213  
2214 =head3 API SPECIFICATION
2215  
2216 =head4 Input
2217  
2218 key -- SCALAR -- dotted key path.
2219  
2220 =head4 Output
2221  
2222 SCALAR -- the env-layer value, or C<get(key)> when no env var set it.
2223  
2224 =cut
2225  
2226 sub prefer_env
2227 15 ▶{
Subroutine prefer_env: called CC=2 SCAR=6.9
Pod documented
2228 15 my ($self, $key) = @_;
2229 15 my ($found, $val) = $self->_value_from_type('env', $key);
2230 15 ▶ return $found ? $val : $self->get($key);
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 7 8 15
2231 }
2232  
2233 =head2 prefer_file(key)
2234  
2235 Return the value that a configuration file provided for C<key>, bypassing
2236 environment variables and CLI arguments that may have overridden it.
2237 Falls back to the normal merged value from C<get(key)> when no file
2238 contributed to C<key>.
2239  
2240 =head3 EXAMPLE
2241  
2242 my $host = $cfg->prefer_file('database.host');
2243 # Returns the file-sourced value even if APP_DATABASE__HOST is set.
2244  
2245 =head3 API SPECIFICATION
2246  
2247 =head4 Input
2248  
2249 key -- SCALAR -- dotted key path.
2250  
2251 =head4 Output
2252  
2253 SCALAR -- the file-layer value, or C<get(key)> when no file set it.
2254  
2255 =cut
2256  
2257 sub prefer_file
2258 11 ▶{
Subroutine prefer_file: called CC=2 SCAR=6.9
Pod documented
2259 11 my ($self, $key) = @_;
2260 11 my ($found, $val) = $self->_value_from_type('file', $key);
2261 11 ▶ return $found ? $val : $self->get($key);
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 5 6 11
2262 }
2263  
2264 =head2 prefer_data(key)
2265  
2266 Return the value that the C<data> constructor argument provided for C<key>,
2267 bypassing files, environment variables, and CLI arguments that may have
2268 overridden it.
2269 Falls back to the normal merged value from C<get(key)> when C<data> did not
2270 contribute to C<key>.
2271  
2272 =head3 EXAMPLE
2273  
2274 my $cfg = Config::Abstraction->new(
2275 data => { timeout => 30 },
2276 config_dirs => ['/etc/myapp'],
2277 );
2278 my $t = $cfg->prefer_data('timeout'); # always 30, regardless of files/env
2279  
2280 =head3 API SPECIFICATION
2281  
2282 =head4 Input
2283  
2284 key -- SCALAR -- dotted key path.
2285  
2286 =head4 Output
2287  
2288 SCALAR -- the data-layer value, or C<get(key)> when C<data> did not set it.
2289  
2290 =cut
2291  
2292 sub prefer_data
2293 15 ▶{
Subroutine prefer_data: called CC=2 SCAR=6.9
Pod documented
2294 15 my ($self, $key) = @_;
2295 15 my ($found, $val) = $self->_value_from_type('data', $key);
2296 15 ▶ return $found ? $val : $self->get($key);
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 8 7 15
2297 }
2298  
2299 =head2 prefer_argv(key)
2300  
2301 Return the value that a CLI argument provided for C<key>.
2302 Falls back to the normal merged value from C<get(key)> when no CLI argument
2303 contributed to C<key>.
2304  
2305 Because CLI arguments are the highest-precedence source, this method is
2306 primarily useful for writing self-documenting code or for detecting whether
2307 a key was explicitly supplied on the command line.
2308  
2309 =head3 EXAMPLE
2310  
2311 my $level = $cfg->prefer_argv('log.level');
2312 # Equivalent to $cfg->get('log.level') unless you specifically need to
2313 # confirm the value came from @ARGV.
2314  
2315 =head3 API SPECIFICATION
2316  
2317 =head4 Input
2318  
2319 key -- SCALAR -- dotted key path.
2320  
2321 =head4 Output
2322  
2323 SCALAR -- the argv-layer value, or C<get(key)> when no CLI arg set it.
2324  
2325 =cut
2326  
2327 sub prefer_argv
2328 12 ▶{
Subroutine prefer_argv: called CC=2 SCAR=6.9
Pod documented
2329 12 my ($self, $key) = @_;
2330 12 my ($found, $val) = $self->_value_from_type('argv', $key);
2331 12 ▶ return $found ? $val : $self->get($key);
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 5 7 12
2332 }
2333  
2334 =head2 encrypt_value($plaintext)
2335  
2336 Encrypt a plaintext string using the configured AES-256-GCM key and return an
2337 C<ENC[AES256GCM,...]> token suitable for storing in a configuration file.
2338  
2339 Each call generates a fresh random nonce, so the same plaintext produces a
2340 different token every time. The token is authenticated (GCM tag); any
2341 modification causes decryption to croak.
2342  
2343 Requires L<CryptX> (C<Crypt::AuthEnc::GCM>, C<Crypt::PRNG>).
2344  
2345 =head3 EXAMPLE
2346  
2347 # Generate a token to paste into base.yaml:
2348 my $cfg = Config::Abstraction->new(
2349 encryption_key => $hex_key,
2350 config_dirs => [],
2351 lazy => 1,
2352 );
2353 my $token = $cfg->encrypt_value('s3cr3t_password');
2354 # ENC[AES256GCM,QkJCQkJCQkJCQkJCO6Gfb0o5jwqB1R...]
2355  
2356 # Or use config-dump from the command line:
2357 # config-dump --encrypt-value 's3cr3t_password' --encryption-key $KEY
2358  
2359 =head3 API SPECIFICATION
2360  
2361 =head4 Input
2362  
2363 plaintext -- SCALAR -- the string to encrypt. May be empty.
2364  
2365 =head4 Output
2366  
2367 SCALAR -- the ENC[AES256GCM,...] token (always a printable ASCII string).
2368  
2369 =head3 MESSAGES
2370  
2371 "<class>: no encryption key configured ..." -- croak when no key is available.
2372 "<class>: CryptX (Crypt::AuthEnc::GCM) is required ..." -- croak when CryptX absent.
2373  
2374 =head3 PSEUDOCODE
2375  
2376 call _ensure_loaded
2377 key = _get_encryption_key() -- croak if undef
2378 load Crypt::AuthEnc::GCM and Crypt::PRNG -- croak if absent
2379 nonce = 12 random bytes
2380 gcm = new GCM('AES', key)
2381 gcm.iv_add(nonce)
2382 gcm.adata_add('') -- ends the IV phase (required by CryptX < 0.049)
2383 ciphertext = gcm.encrypt_add(plaintext)
2384 tag = gcm.encrypt_done()
2385 return "ENC[AES256GCM," + base64url(nonce + ciphertext + tag) + "]"
2386  
2387 =cut
2388  
2389 sub encrypt_value
2390 37 ▶{
Subroutine encrypt_value: called CC=4 SCAR=13.9
Pod documented
2391 37 my ($self, $plaintext) = @_;
2392  
2393 37 $self->_ensure_loaded();
2394  
2395 37 ▶ my $key = $self->_get_encryption_key()
Branch: 1 branch
BranchTrueFalseTotal
my $key = $self->_get_encryption_key or Carp::croak(ref($self) . ': no encryption key configured (set encryption_key, encryption_key_file, or ENCRYPTION_KEY env var)') 34 3 37
2396 or Carp::croak(ref($self) . ': no encryption key configured (set encryption_key, encryption_key_file, or ENCRYPTION_KEY env var)');
2397  
2398 34 ▶ unless($self->_load_driver('Crypt::AuthEnc::GCM')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_load_driver("Crypt::AuthEnc::GCM")) 2 32 34
2399 2 Carp::croak(ref($self) . ': CryptX (Crypt::AuthEnc::GCM) is required; install it with: cpanm CryptX');
2400 }
2401 32 ▶ unless($self->_load_driver('Crypt::PRNG', ['random_bytes'])) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_load_driver("Crypt::PRNG", ["random_bytes"])) 1 31 32
2402 1 Carp::croak(ref($self) . ': CryptX (Crypt::PRNG) is required; install it with: cpanm CryptX');
2403 }
2404  
2405 31 require MIME::Base64;
2406  
2407 31 my $nonce = random_bytes($_AES_NONCE_SIZE);
2408 31 my $gcm = Crypt::AuthEnc::GCM->new('AES', $key);
2409 31 $gcm->iv_add($nonce);
2410 # Empty AAD explicitly ends the IV phase. CryptX < 0.049 does not do this
2411 # implicitly, so encrypt_add() straight after iv_add() fails there with
2412 # "Invalid argument provided". The output is identical on newer CryptX.
2413 31 $gcm->adata_add('');
2414 31 my $ct = $gcm->encrypt_add($plaintext);
2415 31 my $tag = $gcm->encrypt_done();
2416  
2417 31 return 'ENC[AES256GCM,' . MIME::Base64::encode_base64url($nonce . $ct . $tag, '') . ']';
2418 }
2419  
2420 =head2 merge_defaults
2421  
2422 Merge the configuration hash into the given hash.
2423  
2424 package MyPackage;
2425 use Params::Get;
2426 use Config::Abstraction;
2427  
2428 sub new
2429 {
2430 my $class = shift;
2431  
2432 my $params = Params::Get::get_params(undef, \@_) || {};
2433  
2434 if(my $config = Config::Abstraction->new(env_prefix => "${class}::")) {
2435 $params = $config->merge_defaults(defaults => $params, merge => 1, section => $class);
2436 }
2437  
2438 return bless $params, $class;
2439 }
2440  
2441 Options:
2442  
2443 =over 4
2444  
2445 =item * merge
2446  
2447 Usually,
2448 what's in the object will overwrite what's in the defaults hash,
2449 if given,
2450 the result will be a combination of the hashes.
2451  
2452 =item * section
2453  
2454 Merge in that section from the configuration file.
2455  
2456 =item * deep
2457  
2458 Try harder to merge all configurations from the global section of the configuration file.
2459  
2460 =back
2461  
2462 =cut
2463  
2464 sub merge_defaults
2465 39 ▶{
Subroutine merge_defaults: called CC=8 SCAR=20.8
Pod documented
2466 39 my $self = shift;
2467 39 my $config = $self->all();
2468  
2469 39 ▶ return $config if(scalar(@_) == 0);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ == 0 3 36 39
2470  
2471 36 my $params = Params::Get::get_params('defaults', @_);
2472 36 my $defaults = $params->{'defaults'};
2473 36 ▶ return $config if(!defined($defaults));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $defaults 6 30 36
2474 30 my $section = $params->{'section'};
2475  
2476 # Work on a shallow copy so we never mutate $self->{'config'} directly.
2477 # Without this, 'delete $config->{global}' below would permanently alter
2478 # the live internal hash on every call.
2479 30 my %config_copy = %{$config};
2480 30 $config = \%config_copy;
2481  
2482 # Save and restore Hash::Merge's clone behaviour so we don't leak the
2483 # no-clone global state into unrelated merge() calls (e.g. inside
2484 # _load_config when a new object is constructed after this method runs).
2485 30 my $saved_clone = Hash::Merge::get_clone_behavior();
2486 30 Hash::Merge::set_clone_behavior(0);
2487  
2488 30 ▶ if(exists $config->{'global'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $config->{"global"}) 10 20 30
2489 10 ▶ if($params->{'deep'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{'deep'}) { } 3 7 10
2490 3 $defaults = merge($config->{'global'}, $defaults);
2491 } else {
2492 7 $defaults = { %{$defaults}, %{$config->{'global'}} };
2493 }
2494 10 delete $config->{'global'};
2495 }
2496 30 ▶ if($section && exists $config->{$section}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($section and exists $config->{$section}) 7 23 30
Condition100%3/3
$section and exists $config->{$section}
!ll&&!rl&&r
2217
MC/DC100%2/2
$section and exists $config->{$section}
$section exists $config->{$section}
Truth table100%3/3
A and B
A= $sectionB= exists $config->{$section}
ABresult
0X0
100
111
2497 7 $config = $config->{$section};
2498 }
2499 30 my $result;
2500 30 ▶ if($params->{'merge'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{'merge'}) { } 7 23 30
2501 7 $result = merge($config, $defaults);
2502 } else {
2503 23 $result = { %{$defaults}, %{$config} };
2504 }
2505 29 Hash::Merge::set_clone_behavior($saved_clone);
2506 29 return $result;
2507 }
2508  
2509 # Helper routine to load a driver.
2510 # NOTE: Log::Abstraction must NOT be loaded via this method - it is
2511 # bootstrapped directly in new() to avoid a circular initialisation
2512 # dependency where _load_driver would attempt to log via an as-yet
2513 # uninitialised logger.
2514 sub _load_driver
2515 1514 ▶{
Subroutine _load_driver: called CC=6 SCAR=17.9
2516 1514 my($self, $driver, $imports) = @_;
2517  
2518 1514 ▶ return 1 if($self->{'loaded'}{$driver});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"loaded"}{$driver} 93 1421 1514
2519 1421 ▶ return 0 if($self->{'failed'}{$driver});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"failed"}{$driver} 11 1410 1421
2520  
2521 1410 eval "require $driver";
2522 1410 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 70 1340 1410
2523 70 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 7 63 70
2524 7 $logger->warn(ref($self), ": $driver failed to load: $@");
2525 }
2526 70 $self->{'failed'}{$driver} = 1;
2527 70 return;
2528 }
2529 1340 ▶ $driver->import(@{ $imports // [] });
Condition100%2/2
$imports // []
l!l
1193147
MC/DC100%1/1
$imports // []
$imports
Truth table100%2/2
A
A= $imports
Aresult
11
00
2530 1340 $self->{'loaded'}{$driver} = 1;
2531 1340 return 1;
2532 }
2533  
2534 # Parse an Apache-style configuration with Config::General. Returns a hashref
2535 # or undef (driver absent, unreadable, rejected or empty). Config::General's
2536 # own <<include>> directive is never honoured: it would read any file the
2537 # process can read, outside the allowlist that _process_includes enforces, so
2538 # a file that uses it is skipped. The 'include' key (see allow_includes) is the
2539 # supported way to include files. Config::General's variable interpolation is
2540 # switched off in favour of this module's own (see the interpolate option).
2541 sub _load_config_general
2542 15 ▶{
Subroutine _load_config_general: called CC=9 SCAR=24.0
2543 15 my ($self, $path, $content) = @_;
2544  
2545 15 ▶ return undef unless $self->_load_driver('Config::General');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_load_driver("Config::General") 1 14 15
2546  
2547 14 ▶ $content //= eval { scalar(read_file($path)) };
Condition66%2/3
$content //= eval { do { scalar read_file($path) } }
l!l&&r!l&&!r
590
MC/DC0%0/2
$content //= eval { do { scalar read_file($path) } }
$content eval { do { scalar read_file($path) } }
Truth table66%2/3
A //= B
A= $contentB= eval { do { scalar read_file($path) } }
ABresult
1X1
011
000
2548 14 ▶ return undef unless defined($content);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 14 14
2549 14 ▶ return undef if $content =~ /\A#!/;
Branch: 1 branch
BranchTrueFalseTotal
if $content =~ /\A#!/ 0 14 14
2550  
2551 14 ▶ if($content =~ /^\s*<<\s*include\b/mi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content =~ /^\s*<<\s*include\b/im) 1 13 14
2552 1 Carp::carp(ref($self) . ": skipping $path: Config::General <<include>> directives are not permitted; use the 'include' key with allow_includes");
2553 1 return undef;
2554 }
2555  
2556 13 my %conf = eval {
2557 13 Config::General->new(
2558 -String => $content,
2559 -InterPolateVars => 0,
2560 -InterPolateEnv => 0,
2561 -UseApacheInclude => 0,
2562 -IncludeGlob => 0,
2563 )->getall();
2564 };
2565 13 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 13 13
2566 0 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{'logger'}) { } 0 0 0
2567 0 $logger->notice("Failed to load Config::General data from $path: $@");
2568 } else {
2569 0 Carp::carp("Failed to load Config::General data from $path: $@");
2570 }
2571 0 return undef;
2572 }
2573  
2574 13 ▶ return scalar(keys %conf) ? \%conf : undef;
Branch: 1 branch
BranchTrueFalseTotal
scalar keys %conf ? : 10 3 13
2575 }
2576  
2577 # Parse one file chosen by its extension, for use by the include mechanism.
2578 # Files with an unrecognised extension are tried as JSON, YAML, TOML, then
2579 # Config::General. Returns a hashref or undef; never dies.
2580 sub _parse_file
2581 25 ▶{
Subroutine _parse_file: called CC=38 SCAR=52.0
2582 25 my ($self, $path) = @_;
2583  
2584 25 my $raw = eval { scalar(read_file($path)) };
2585 25 ▶ return undef unless defined($raw);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 0 25 25
2586 # A program is never configuration
2587 25 ▶ return undef if $raw =~ /\A#!/;
Branch: 1 branch
BranchTrueFalseTotal
if $raw =~ /\A#!/ 1 24 25
2588  
2589 24 my $logger = $self->{'logger'};
2590 0 ▶ my $fail = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2591 0 my ($what, $err) = @_;
2592 0 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) { } 0 0 0
2593 0 $logger->notice("Failed to load $what from $path: $err");
2594 } else {
2595 0 Carp::carp("Failed to load $what from $path: $err");
2596 }
2597 0 return undef;
2598 24 };
2599 24 my $xxe = qr/<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i;
2600  
2601 24 my $data;
2602 24 ▶ if($path =~ /\.ya?ml$/i) {
Branch: 6 branches
BranchTrueFalseTotal
if ($path =~ /\.ya?ml$/i) { } 17 7 24
elsif ($path =~ /\.json$/i) { } 3 4 7
elsif ($path =~ /\.xml$/i) { } 0 4 4
elsif ($path =~ /\.ini$/i) { } 1 3 4
elsif ($path =~ /\.toml$/i) { } 1 2 3
elsif ($path =~ /\.(?:conf|cnf)$/i) { } 0 2 2
2603 17 ▶ $self->_load_driver('YAML::XS', ['Load']) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->_load_driver("YAML::XS", ["Load"]) or return undef 17 0 17
2604 17 $data = eval { YAML::XS::Load($raw) };
2605 17 ▶ return $fail->('YAML', $@) if($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 17 17
2606 17 ▶ $data = $self->_sanitize_yaml_values($data) if ref($data);
Branch: 1 branch
BranchTrueFalseTotal
if ref $data 17 0 17
2607 } elsif($path =~ /\.json$/i) {
2608 3 $data = eval { decode_json($raw) };
2609 3 ▶ return $fail->('JSON', $@) if($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 3 3
2610 } elsif($path =~ /\.xml$/i) {
2611 0 ▶ if($raw =~ $xxe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ /$xxe/) 0 0 0
2612 0 Carp::carp(ref($self) . ": skipping $path: XML external entity declarations not permitted");
2613 0 return undef;
2614 }
2615 0 ▶ if($self->_load_driver('XML::Simple', ['XMLin'])) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_load_driver('XML::Simple', ['XMLin'])) { } 0 0 0
elsif ($self->_load_driver('XML::PP')) { } 0 0 0
2616 0 $data = eval { XMLin(\$raw, ForceArray => 0, KeyAttr => []) };
2617 0 ▶ return $fail->('XML', $@) if($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
2618 } elsif($self->_load_driver('XML::PP')) {
2619 0 my $xml_pp = XML::PP->new();
2620 0 ▶ if(my $tree = eval { $xml_pp->parse(\$raw) }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tree = eval { do { $xml_pp->parse(\$raw) } }) 0 0 0
2621 0 $data = $xml_pp->collapse_structure($tree);
2622 0 ▶ $data = $data->{'config'} if(ref($data) eq 'HASH' && $data->{'config'});
Branch: 1 branch
BranchTrueFalseTotal
if ref $data eq "HASH" and $data->{"config"} 0 0 0
Condition0%0/3
ref $data eq "HASH" and $data->{"config"}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $data eq "HASH" and $data->{"config"}
ref $data eq "HASH" $data->{"config"}
Truth table0%0/3
A and B
A= ref $data eq "HASH"B= $data->{"config"}
ABresult
0X0
100
111
2623 }
2624 }
2625 } elsif($path =~ /\.ini$/i) {
2626 1 ▶ $self->_load_driver('Config::IniFiles') or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->_load_driver("Config::IniFiles") or return undef 1 0 1
2627 1 ▶ if(my $ini = Config::IniFiles->new(-file => $path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ini = 'Config::IniFiles'->new('-file', $path)) { } 1 0 1
2628 $data = { map {
2629 1 my $section = $_;
2630 1 $section => { map { $_ => $ini->val($section, $_) } $ini->Parameters($section) }
2631 } $ini->Sections() };
2632 } else {
2633 0 ▶ my @errors = do { no warnings "once"; @Config::IniFiles::errors };
Subroutine BEGIN: called CC=1 SCAR=0.6
2634 0 return $fail->('INI', join(q{; }, @errors));
2635 }
2636 } elsif($path =~ /\.toml$/i) {
2637 1 ▶ $self->_load_driver('TOML::Tiny', ['from_toml']) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->_load_driver("TOML::Tiny", ["from_toml"]) or return undef 1 0 1
2638 1 my ($toml, $err) = from_toml($raw);
2639 1 ▶ return $fail->('TOML', $err) if($err);
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 1 1
2640 1 $data = $toml;
2641 } elsif($path =~ /\.(?:conf|cnf)$/i) {
2642 0 $data = $self->_load_config_general($path, $raw);
2643 } else {
2644 2 ▶ if($raw =~ /^\s*\{/ && $self->_load_driver('JSON::Parse')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ /^\s*\{/ and $self->_load_driver("JSON::Parse")) 1 1 2
Condition66%2/3
$raw =~ /^\s*\{/ and $self->_load_driver("JSON::Parse")
!ll&&!rl&&r
101
MC/DC50%1/2
$raw =~ /^\s*\{/ and $self->_load_driver("JSON::Parse")
$raw =~ /^\s*\{/ $self->_load_driver("JSON::Parse")
Truth table66%2/3
A and B
A= $raw =~ /^\s*\{/B= $self->_load_driver("JSON::Parse")
ABresult
0X0
100
111
2645 1 my $is_json = eval { JSON::Parse::parse_json($raw) };
2646 1 ▶ $data = eval { decode_json($raw) } if($is_json);
Branch: 1 branch
BranchTrueFalseTotal
if $is_json 1 0 1
2647 }
2648 2 ▶ if(ref($data) ne 'HASH' && $raw !~ $xxe && $self->_load_driver('YAML::XS', ['Load'])) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH" and not $raw =~ /$xxe/ and $self->_load_driver("YAML::XS", ["Load"])) 1 1 2
Condition66%4/6
ref $data ne "HASH" and not $raw =~ /$xxe/ and $self->_load_driver("YAML::XS", ["Load"])
!ll&&!rl&&r
101
ref $data ne "HASH" and not $raw =~ /$xxe/
!ll&&!rl&&r
101
MC/DC33%1/3
ref $data ne "HASH" and not $raw =~ /$xxe/ and $self->_load_driver("YAML::XS", ["Load"])
ref $data ne "HASH" not $raw =~ /$xxe/ $self->_load_driver("YAML::XS", ["Load"])
Truth table50%2/4
A and not(B) and C
A= ref $data ne "HASH"B= not $raw =~ /$xxe/C= $self->_load_driver("YAML::XS", ["Load"])
ABCresult
0XX0
10X0
1100
1111
2649 1 $data = eval { YAML::XS::Load($raw) };
2650 1 ▶ $data = $self->_sanitize_yaml_values($data) if ref($data);
Branch: 1 branch
BranchTrueFalseTotal
if ref $data 1 0 1
2651 }
2652 2 ▶ if(ref($data) ne 'HASH' && $self->_load_driver('TOML::Tiny', ['from_toml'])) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH" and $self->_load_driver("TOML::Tiny", ["from_toml"])) 0 2 2
Condition33%1/3
ref $data ne "HASH" and $self->_load_driver("TOML::Tiny", ["from_toml"])
!ll&&!rl&&r
200
MC/DC0%0/2
ref $data ne "HASH" and $self->_load_driver("TOML::Tiny", ["from_toml"])
ref $data ne "HASH" $self->_load_driver("TOML::Tiny", ["from_toml"])
Truth table33%1/3
A and B
A= ref $data ne "HASH"B= $self->_load_driver("TOML::Tiny", ["from_toml"])
ABresult
0X0
100
111
2653 0 my ($toml, $err) = eval { from_toml($raw) };
2654 0 ▶ $data = $toml if(!$err && ref($toml) eq 'HASH' && scalar(keys %{$toml}));
Branch: 1 branch
BranchTrueFalseTotal
if not $err and ref $toml eq "HASH" and scalar keys %{$toml;} 0 0 0
Condition0%0/5
not $err and ref $toml eq "HASH" and scalar keys %{$toml;}
!ll
00
not $err and ref $toml eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
not $err and ref $toml eq "HASH" and scalar keys %{$toml;}
not $err ref $toml eq "HASH"
Truth table0%0/3
not(A) and B
A= not $errB= ref $toml eq "HASH"
ABresult
0X0
100
111
2655 }
2656 2 ▶ if(ref($data) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH") 0 2 2
2657 0 $data = $self->_load_config_general($path, $raw);
2658 }
2659 }
2660  
2661 24 ▶ return (ref($data) eq 'HASH') ? $data : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 23 1 24
2662 }
2663  
2664 # True when the (already resolved) path lies within one of the root directories.
2665 sub _path_within
2666 30 ▶{
Subroutine _path_within: called CC=4 SCAR=13.9
2667 30 my ($path, $roots) = @_;
2668  
2669 30 foreach my $root (@{$roots}) {
2670 31 (my $r = $root) =~ s{[/\\]+$}{};
2671 31 ▶ return 1 if($path eq $r || index($path, "$r/") == 0);
Branch: 1 branch
BranchTrueFalseTotal
if $path eq $r or index($path, "$r/") == 0 27 4 31
Condition66%2/3
$path eq $r or index($path, "$r/") == 0
l!l&&r!l&&!r
0274
MC/DC50%1/2
$path eq $r or index($path, "$r/") == 0
$path eq $r index($path, "$r/") == 0
Truth table66%2/3
A or B
A= $path eq $rB= index($path, "$r/") == 0
ABresult
1X1
011
000
2672 }
2673 3 return 0;
2674 }
2675  
2676 # Expand the include key of a freshly parsed file.
2677 #
2678 # Returns ($own, $full, \@included_paths):
2679 # $own the file's own data, without the include key
2680 # $full $own merged over everything it includes (the file wins over its
2681 # includes; of several includes the later one wins), ready to be merged
2682 # into the configuration in place of the file's data
2683 # the paths of the files included (recursively), in the order they were read
2684 #
2685 # A no-op returning ($data, $data, []) unless allow_includes is set. Included
2686 # files must lie within the directory of the file that started the include
2687 # chain, or within one of the include_dirs; anything else croaks, as does a
2688 # circular include or a chain deeper than include_max_depth. A missing include
2689 # is skipped with a warning, as a malformed config file is.
2690 sub _process_includes
2691 361 ▶{
Subroutine _process_includes: called CC=30 SCAR=34.8
2692 361 my ($self, $data, $path, $stack, $roots) = @_;
2693  
2694 361 ▶ return ($data, $data, []) unless($self->{'allow_includes'} && ref($data) eq 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"allow_includes"} and ref $data eq "HASH" 317 44 361
Condition66%2/3
$self->{"allow_includes"} and ref $data eq "HASH"
!ll&&!rl&&r
317044
MC/DC50%1/2
$self->{"allow_includes"} and ref $data eq "HASH"
$self->{"allow_includes"} ref $data eq "HASH"
Truth table66%2/3
A and B
A= $self->{"allow_includes"}B= ref $data eq "HASH"
ABresult
0X0
100
111
2695  
2696 44 ▶ my $key = $self->{'include_key'} // 'include';
Condition100%2/2
$self->{"include_key"} // "include"
l!l
341
MC/DC100%1/1
$self->{"include_key"} // "include"
$self->{"include_key"}
Truth table100%2/2
A
A= $self->{"include_key"}
Aresult
11
00
2697 44 ▶ return ($data, $data, []) unless(exists($data->{$key}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $data->{$key} 16 28 44
2698  
2699 28 my %own = %{$data};
2700 28 my $spec = delete $own{$key};
2701  
2702 28 ▶ my $real = Cwd::abs_path($path) // $path;
Condition33%1/3
Cwd::abs_path($path) // $path
l!l&&r!l&&!r
2800
MC/DC0%0/2
Cwd::abs_path($path) // $path
Cwd::abs_path($path) $path
Truth table33%1/3
A // B
A= Cwd::abs_path($path)B= $path
ABresult
1X1
011
000
2703 28 my $dir = File::Basename::dirname($real);
2704  
2705 28 ▶ if(!$stack) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($stack) 21 7 28
2706 21 $stack = [ $real ];
2707 1 ▶ my @extra = ref($self->{'include_dirs'}) eq 'ARRAY' ? @{$self->{'include_dirs'}}
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'include_dirs'} ? : 0 20 20
2708 21 ▶ : defined($self->{'include_dirs'}) ? ($self->{'include_dirs'}) : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'include_dirs'} eq 'ARRAY' ? : 1 20 21
2709 21 ▶ $roots = [ $dir, grep { defined } map { Cwd::abs_path($_) } grep { defined && length } @extra ];
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
001
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
2710 }
2711  
2712 28 ▶ my $max_depth = $self->{'include_max_depth'} // 10;
Condition100%2/2
$self->{"include_max_depth"} // 10
l!l
325
MC/DC100%1/1
$self->{"include_max_depth"} // 10
$self->{"include_max_depth"}
Truth table100%2/2
A
A= $self->{"include_max_depth"}
Aresult
11
00
2713 28 ▶ if(scalar(@{$stack}) > $max_depth) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$stack;} > $max_depth) 1 27 28
2714 1 Carp::croak(ref($self) . ": includes nested more than $max_depth deep at $path");
2715 }
2716  
2717 27 my (%acc, @paths);
2718 27 ▶ foreach my $inc (ref($spec) eq 'ARRAY' ? @{$spec} : ($spec)) {
Branch: 1 branch
BranchTrueFalseTotal
ref $spec eq 'ARRAY' ? : 4 23 27
2719 32 ▶ next unless defined($inc);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $inc 0 32 32
2720 32 ▶ if(ref($inc) || !length($inc)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $inc or not length $inc) 1 31 32
Condition66%2/3
ref $inc or not length $inc
l!l&&r!l&&!r
1031
MC/DC50%1/2
ref $inc or not length $inc
ref $inc not length $inc
Truth table66%2/3
A or not(B)
A= ref $incB= not length $inc
ABresult
1X1
011
000
2721 1 Carp::carp(ref($self) . ": ignoring invalid '$key' entry in $path");
2722 1 next;
2723 }
2724  
2725 31 ▶ my $target = File::Spec->file_name_is_absolute($inc) ? $inc : File::Spec->catfile($dir, $inc);
Branch: 1 branch
BranchTrueFalseTotal
'File::Spec'->file_name_is_absolute($inc) ? : 2 29 31
2726 31 my @targets = ($target);
2727 31 ▶ if($target =~ /[*?\[{]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($target =~ /[*?\[{]/) 2 29 31
2728 2 require File::Glob;
2729 2 @targets = sort(File::Glob::bsd_glob($target));
2730 }
2731  
2732 31 foreach my $t (@targets) {
2733 31 my $tr = Cwd::abs_path($t);
2734 31 ▶ if(!defined($tr) || !-f $tr) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $tr and -f $tr) 1 30 31
Condition66%2/3
defined $tr and -f $tr
!ll&&!rl&&r
0130
MC/DC50%1/2
defined $tr and -f $tr
defined $tr -f $tr
Truth table66%2/3
A and B
A= defined $trB= -f $tr
ABresult
0X0
100
111
2735 1 ▶ Carp::carp(ref($self) . ": $key '$inc' in $path not found") if($t eq $target);
Branch: 1 branch
BranchTrueFalseTotal
if $t eq $target 1 0 1
2736 1 next;
2737 }
2738 30 ▶ if(!_path_within($tr, $roots)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_path_within($tr, $roots)) 3 27 30
2739 3 Carp::croak(ref($self) . ": $key '$inc' in $path resolves to $tr, which is outside the permitted directories");
2740 }
2741 27 ▶ if(grep { $_ eq $tr } @{$stack}) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_ eq $tr;} @{$stack;}) 2 25 27
2742 2 Carp::croak(ref($self) . ": circular $key of $tr from $path");
2743 }
2744 25 ▶ if(defined($_RUNNING_SCRIPT) && $tr eq $_RUNNING_SCRIPT) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_RUNNING_SCRIPT and $tr eq $_RUNNING_SCRIPT) 0 25 25
Condition33%1/3
defined $_RUNNING_SCRIPT and $tr eq $_RUNNING_SCRIPT
!ll&&!rl&&r
0250
MC/DC0%0/2
defined $_RUNNING_SCRIPT and $tr eq $_RUNNING_SCRIPT
defined $_RUNNING_SCRIPT $tr eq $_RUNNING_SCRIPT
Truth table33%1/3
A and B
A= defined $_RUNNING_SCRIPTB= $tr eq $_RUNNING_SCRIPT
ABresult
0X0
100
111
2745 0 next;
2746 }
2747 25 ▶ if(!-r $tr) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-r $tr) 0 25 25
2748 0 Carp::carp(ref($self) . ": $key '$inc' in $path is not readable");
2749 0 next;
2750 }
2751  
2752 25 my $inc_data = $self->_parse_file($tr);
2753 25 ▶ if(ref($inc_data) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $inc_data ne "HASH") 2 23 25
2754 2 Carp::carp(ref($self) . ": $key '$inc' in $path did not contain a configuration hash");
2755 2 next;
2756 }
2757  
2758 23 my ($inc_own, $inc_full, $inc_paths) = $self->_process_includes($inc_data, $tr, [ @{$stack}, $tr ], $roots);
2759 19 push @{$self->{'_source_records'}}, {
2760 type => 'file',
2761 label => $tr,
2762 flat_data => { _flatten_keys($inc_own) },
2763 };
2764 19 %acc = %{ merge($inc_full, \%acc) };
2765 19 push @paths, $tr, @{$inc_paths};
2766 }
2767 }
2768  
2769 18 ▶ return (\%own, scalar(keys %acc) ? merge(\%own, \%acc) : \%own, \@paths);
Branch: 1 branch
BranchTrueFalseTotal
scalar keys %acc ? : 15 3 18
2770 }
2771  
2772 # Expand ${...} references in every string value of the merged configuration
2773 # and return the result as a new tree; the input, which can share structure with
2774 # the caller's data argument, is left untouched.
2775 #
2776 # ${a.b} the value of config key a.b
2777 # ${env:NAME} the environment variable NAME
2778 # ${a.b:-default} as above, but default when it is missing or undef
2779 # $$ a literal dollar sign
2780 #
2781 # Values that are ENC[...] tokens are left alone. A reference to a missing key,
2782 # a circular reference, or a reference to a non-scalar croaks, unless
2783 # interpolate_strict is set to a false value, in which case the reference is
2784 # left as written.
2785 sub _interpolate_tree
2786 23 ▶{
Subroutine _interpolate_tree: called CC=2 SCAR=6.9
2787 23 my ($self, $root) = @_;
2788  
2789 23 ▶ my $strict = $self->{'interpolate_strict'} // 1;
Condition100%2/2
$self->{"interpolate_strict"} // 1
l!l
122
MC/DC100%1/1
$self->{"interpolate_strict"} // 1
$self->{"interpolate_strict"}
Truth table100%2/2
A
A= $self->{"interpolate_strict"}
Aresult
11
00
2790 23 my (%memo, %busy, $expand, $lookup);
2791  
2792 32 ▶ $lookup = sub {
Subroutine __ANON__: called CC=11 SCAR=24.0
2793 32 my ($name, $where) = @_;
2794  
2795 32 ▶ return @{$memo{$name}} if($memo{$name});
Branch: 1 branch
BranchTrueFalseTotal
if $memo{$name} 5 27 32
2796  
2797 27 my $node = $root;
2798 27 my ($found, $value);
2799 27 ▶ if(exists($root->{$name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $root->{$name}) { } 16 11 27
2800 16 ($found, $value) = (1, $root->{$name});
2801 } else {
2802 11 foreach my $part (split /\./, $name, -1) {
2803 17 ▶ if(ref($node) eq 'HASH' && exists($node->{$part})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq 'HASH' and exists $node->{$part}) { } 12 5 17
Condition66%2/3
ref $node eq "HASH" and exists $node->{$part}
!ll&&!rl&&r
0512
MC/DC50%1/2
ref $node eq "HASH" and exists $node->{$part}
ref $node eq "HASH" exists $node->{$part}
Truth table66%2/3
A and B
A= ref $node eq "HASH"B= exists $node->{$part}
ABresult
0X0
100
111
2804 12 $node = $node->{$part};
2805 12 $found = 1;
2806 } else {
2807 5 $found = 0;
2808 5 last;
2809 }
2810 }
2811 11 ▶ $value = $node if($found);
Branch: 1 branch
BranchTrueFalseTotal
if $found 6 5 11
2812 }
2813 27 ▶ return (0) unless($found && defined($value));
Branch: 1 branch
BranchTrueFalseTotal
unless $found and defined $value 6 21 27
Condition100%3/3
$found and defined $value
!ll&&!rl&&r
5121
MC/DC100%2/2
$found and defined $value
$found defined $value
Truth table100%3/3
A and B
A= $foundB= defined $value
ABresult
0X0
100
111
2814  
2815 21 ▶ if(ref($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value) 1 20 21
2816 1 Carp::croak(ref($self) . ": \${$name} in $where refers to a non-scalar value");
2817 }
2818 20 ▶ if($busy{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($busy{$name}) 2 18 20
2819 2 Carp::croak(ref($self) . ": circular reference to \${$name} in $where");
2820 }
2821 18 local $busy{$name} = 1;
2822 18 my $resolved = $expand->($value, $name);
2823 15 $memo{$name} = [ 1, $resolved ];
2824 15 return (1, $resolved);
2825 23 };
2826  
2827 71 ▶ $expand = sub {
Subroutine __ANON__: called CC=12 SCAR=24.9
2828 71 my ($str, $where) = @_;
2829  
2830 71 ▶ return $str if(!defined($str) || ref($str) || $str !~ /\$/ || $str =~ /^ENC\[/);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $str or ref $str or not $str =~ /\$/ or $str =~ /^ENC\[/ 34 37 71
Condition66%6/9
not defined $str or ref $str or not $str =~ /\$/ or $str =~ /^ENC\[/
l!l&&r!l&&!r
33137
not defined $str or ref $str or not $str =~ /\$/
l!l&&r!l&&!r
03338
not defined $str or ref $str
l!l&&r!l&&!r
0071
MC/DC50%2/4
not defined $str or ref $str or not $str =~ /\$/ or $str =~ /^ENC\[/
not defined $str ref $str not $str =~ /\$/ $str =~ /^ENC\[/
Truth table60%3/5
not(A) or B or not(C) or D
A= not defined $strB= ref $strC= not $str =~ /\$/D= $str =~ /^ENC\[/
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2831  
2832 37 $str =~ s{ \$\$ | \$\{ ([^{}]*) \} }{
2833 40 my $spec = $1;
2834 40 my $whole = $&;
2835 40 ▶ if(!defined($spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $spec) { } 2 38 40
2836 2 '$';
2837 } else {
2838 38 my ($name, $default) = $spec =~ /^(.*?)(?::-(.*))?$/s;
2839 38 $name =~ s/^\s+|\s+$//g;
2840 38 ▶ Carp::croak(ref($self) . ": empty \${} reference in $where") unless length($name);
Branch: 1 branch
BranchTrueFalseTotal
unless length $name 1 37 38
2841  
2842 37 my ($ok, $val);
2843 37 ▶ if($name =~ /^env:(.+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^env:(.+)$/i) { } 5 32 37
2844 5 my $var = $1;
2845 5 ▶ ($ok, $val) = defined($ENV{$var}) ? (1, $ENV{$var}) : (0);
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{$var} ? : 3 2 5
2846 } else {
2847 32 ($ok, $val) = $lookup->($name, $where);
2848 }
2849 31 ▶ if($ok) {
Branch: 3 branches
BranchTrueFalseTotal
if ($ok) { } 23 8 31
elsif (defined $default) { } 3 5 8
elsif ($strict) { } 4 1 5
2850 23 $val;
2851 } elsif(defined($default)) {
2852 3 $default;
2853 } elsif($strict) {
2854 4 Carp::croak(ref($self) . ": \${$name} in $where is not defined");
2855 } else {
2856 1 $whole;
2857 }
2858 }
2859 }gex;
2860 26 return $str;
2861 23 };
2862  
2863 23 my $seen = {};
2864 23 my $walk;
2865 88 ▶ $walk = sub {
Subroutine __ANON__: called CC=10 SCAR=23.0
2866 88 my ($node, $prefix) = @_;
2867  
2868 88 my $r = ref($node);
2869 88 ▶ if($r eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "HASH") 33 55 88
2870 33 my $addr = Scalar::Util::refaddr($node);
2871 33 ▶ return $node if($seen->{$addr}++);
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$addr}++ 0 33 33
2872 33 my %new;
2873 33 foreach my $k (keys %{$node}) {
2874 65 ▶ if($prefix eq '' && $k eq 'config_path') {
Branch: 1 branch
BranchTrueFalseTotal
if ($prefix eq "" and $k eq "config_path") 3 62 65
Condition100%3/3
$prefix eq "" and $k eq "config_path"
!ll&&!rl&&r
11513
MC/DC100%2/2
$prefix eq "" and $k eq "config_path"
$prefix eq "" $k eq "config_path"
Truth table100%3/3
A and B
A= $prefix eq ""B= $k eq "config_path"
ABresult
0X0
100
111
2875 3 $new{$k} = $node->{$k};
2876 3 next;
2877 }
2878 62 ▶ $new{$k} = $walk->($node->{$k}, length($prefix) ? "$prefix.$k" : $k);
Branch: 1 branch
BranchTrueFalseTotal
length $prefix ? : 11 51 62
2879 }
2880 25 delete $seen->{$addr};
2881 25 return \%new;
2882 }
2883 55 ▶ if($r eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "ARRAY") 1 54 55
2884 1 my $addr = Scalar::Util::refaddr($node);
2885 1 ▶ return $node if($seen->{$addr}++);
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$addr}++ 0 1 1
2886 1 my $i = 0;
2887 1 my @new = map { $walk->($_, "$prefix\[" . $i++ . ']') } @{$node};
2888 1 delete $seen->{$addr};
2889 1 return \@new;
2890 }
2891 54 ▶ return $node if($r); # code refs, objects: not ours to rewrite
Branch: 1 branch
BranchTrueFalseTotal
if $r 1 53 54
2892 53 return $expand->($node, $prefix);
2893 23 };
2894  
2895 23 return $walk->($root, '');
2896 }
2897  
2898 =head2 Remote configuration directories (Newcastle Connection)
2899  
2900 Any entry in C<config_dirs> whose path begins with C</../> is treated as a
2901 remote specification rather than a local directory:
2902  
2903 /../hostname/path/to/dir
2904  
2905 The hostname and directory are extracted, and the same standard files searched
2906 locally (C<base.yaml>, C<local.yaml>, C<base.json>, etc.) are fetched from
2907 the remote machine via L<File::Slurp::Remote> over SSH.
2908  
2909 When the hostname resolves to the local machine -- C<localhost>, C<127.0.0.1>,
2910 C<::1>, or the value returned by C<Sys::Hostname::hostname()> (checked as
2911 both fully-qualified and short form, case-insensitively) -- the C</../host/>
2912 wrapper is silently unwrapped and the enclosed path is processed through the
2913 normal local file pipeline instead. No SSH connection is made. This means a
2914 configuration written for a shared remote host degrades gracefully when run on
2915 that host itself:
2916  
2917 # On any other machine: fetches /etc/myapp over SSH
2918 # On cfg-server itself: reads /etc/myapp from disk directly
2919 config_dirs => ['/../cfg-server/etc/myapp']
2920  
2921 Remote directories participate in the normal merge pipeline and can be freely
2922 mixed with local ones:
2923  
2924 my $cfg = Config::Abstraction->new(
2925 config_dirs => [
2926 '/etc/myapp', # local
2927 '/../deploy@cfg-server/etc/myapp', # remote via SSH (local on cfg-server)
2928 ],
2929 );
2930  
2931 SSH authentication is handled by the system SSH client.
2932 No extra constructor options are required; use your SSH agent or
2933 C<~/.ssh/config> for host-specific settings.
2934  
2935 L<File::Slurp::Remote> must be installed for remote directories to work.
2936 If it is absent the directory is silently skipped and a warning is emitted.
2937  
2938 =head3 Why C</../> (the Newcastle Connection convention)
2939  
2940 Several syntaxes were considered for marking a C<config_dirs> entry as remote.
2941 Each alternative was rejected for a concrete reason:
2942  
2943 =over 4
2944  
2945 =item C<hostname/path> -- ambiguous
2946  
2947 Indistinguishable from a relative local directory named C<hostname>.
2948 The module cannot tell at parse time whether C<myserver/etc> is a two-level
2949 local path or a remote specification.
2950  
2951 =item C<hostname:/path> -- collides with Windows drive letters
2952  
2953 The C<X:\> drive-letter convention on Windows uses exactly the same
2954 C<letter:> prefix. A single-letter hostname would be misidentified as a
2955 drive, and path-normalisation code on Windows would mangle it.
2956  
2957 =item C<file://hostname/path> -- wrong semantics
2958  
2959 RFC 8089 defines C<file://> as a reference to a B<local> file.
2960 C<file:///etc/passwd> (three slashes, empty host) is the canonical local form;
2961 C<file://hostname/path> is reserved for the host component but is explicitly
2962 discouraged for general use and is not understood by most tooling as meaning
2963 SSH.
2964  
2965 =item C<ssh://hostname/path> -- requires URI parsing
2966  
2967 Introduces a dependency on URI parsing (or a bespoke prefix check) and
2968 implies a specific transport. C<File::Slurp::Remote> already abstracts
2969 the transport; encoding C<ssh://> in the path would be misleading if a future
2970 version of that module supports other transports such as C<rsync://>.
2971  
2972 =item C</../hostname/path> -- the Newcastle Connection
2973  
2974 The Newcastle Connection (Brownbridge, Dion, Elsworth, 1982) is a distributed
2975 Unix convention in which the token C</../> at the start of a pathname means
2976 "leave the local namespace and enter the named remote host".
2977 It works because C</../> B<cannot exist> as a real filesystem path:
2978 C<..> from the root directory resolves back to the root on every POSIX system,
2979 so C</../> always denotes the root itself, never a child of the root.
2980 No pathname-normalisation step, C<chdir>, or filesystem traversal will ever
2981 produce a path that legitimately begins with C</../>, which means the prefix
2982 is a permanent, collision-free sentinel that requires only a regex to detect.
2983  
2984 =back
2985  
2986 The Newcastle Connection prefix is therefore the only choice that is:
2987  
2988 =over 4
2989  
2990 =item * unambiguous on all platforms (POSIX and Windows)
2991  
2992 =item * impossible to produce accidentally from a real local path
2993  
2994 =item * detectable with a single C<m{^\Q/../\E}> regex, no URI parser needed
2995  
2996 =item * transport-neutral (the hostname is passed to whatever remote driver is installed)
2997  
2998 =back
2999  
3000 =head2 AUTOLOAD
3001  
3002 This module supports dynamic access to configuration keys via AUTOLOAD.
3003 Nested keys are accessible using the separator,
3004 so C<$config-E<gt>database_user()> resolves to C<< $config->{database}->{user} >>,
3005 when C<sep_char> is set to '_'.
3006  
3007 $config = Config::Abstraction->new(
3008 data => {
3009 database => {
3010 user => 'alice',
3011 pass => 'secret'
3012 },
3013 log_level => 'debug'
3014 },
3015 flatten => 1,
3016 sep_char => '_'
3017 );
3018  
3019 my $user = $config->database_user(); # returns 'alice'
3020  
3021 # or
3022 $user = $config->database()->{'user'}; # returns 'alice'
3023  
3024 # Attempting to call a nonexistent key
3025 my $foo = $config->nonexistent_key(); # dies with error
3026  
3027 =cut
3028  
3029 # ---------------------------------------------------------------------------
3030 # _parse_remote_dir -- detect Newcastle Connection style paths.
3031 #
3032 # Returns ($host, $dir) when $dir begins with /../, empty list otherwise.
3033 # The /../ prefix is syntactically impossible for a real local path so no
3034 # real directory entry is ever misidentified.
3035 # ---------------------------------------------------------------------------
3036 sub _parse_remote_dir
3037 387 ▶{
Subroutine _parse_remote_dir: called CC=4 SCAR=13.9
3038 387 my ($self, $dir) = @_;
3039  
3040 387 ▶ return unless defined($dir);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir 2 385 387
3041 385 ▶ return unless $dir =~ m{^\Q/../\E([^/]+)(/.+)?$};
Branch: 1 branch
BranchTrueFalseTotal
unless $dir =~ m[^\/\.\.\/([^/]+)(/.+)?$] 375 10 385
3042 10 ▶ return ($1, $2 // '/');
Condition100%2/2
$2 // "/"
l!l
73
MC/DC100%1/1
$2 // "/"
$2
Truth table100%2/2
A
A= $2
Aresult
11
00
3043 }
3044  
3045 # ---------------------------------------------------------------------------
3046 # _is_local_host -- true when $host refers to the machine running this code.
3047 #
3048 # Strips any user@ prefix first, then checks the four common ways a caller
3049 # might spell "here": the loopback name, the two loopback addresses, and the
3050 # system hostname (both fully-qualified and short). Comparison is
3051 # case-insensitive because hostnames are case-insensitive by RFC 1034.
3052 # ---------------------------------------------------------------------------
3053 sub _is_local_host
3054 20 ▶{
Subroutine _is_local_host: called CC=9 SCAR=22.0
3055 20 my ($self, $host) = @_;
3056  
3057 20 ▶ return 0 unless defined($host) && length($host);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $host and length $host 2 18 20
Condition100%3/3
defined $host and length $host
!ll&&!rl&&r
1118
MC/DC100%2/2
defined $host and length $host
defined $host length $host
Truth table100%3/3
A and B
A= defined $hostB= length $host
ABresult
0X0
100
111
3058  
3059 18 (my $bare = $host) =~ s/^[^@]+@//; # strip optional user@ prefix
3060  
3061 18 ▶ return 1 if lc($bare) eq 'localhost';
Branch: 1 branch
BranchTrueFalseTotal
if lc $bare eq "localhost" 7 11 18
3062 11 ▶ return 1 if $bare eq '127.0.0.1';
Branch: 1 branch
BranchTrueFalseTotal
if $bare eq "127.0.0.1" 3 8 11
3063 8 ▶ return 1 if $bare eq '::1';
Branch: 1 branch
BranchTrueFalseTotal
if $bare eq "::1" 1 7 8
3064  
3065 # Cache the resolved hostname on the object so Sys::Hostname::hostname()
3066 # (a syscall) is only made once per Config::Abstraction instance.
3067 7 ▶ unless(defined $self->{'_cached_hostname'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"_cached_hostname"}) 3 4 7
3068 3 require Sys::Hostname;
3069 3 $self->{'_cached_hostname'} = lc(Sys::Hostname::hostname());
3070 3 ($self->{'_cached_short_hostname'} = $self->{'_cached_hostname'}) =~ s/\..*$//;
3071 }
3072 7 ▶ return 1 if lc($bare) eq $self->{'_cached_hostname'};
Branch: 1 branch
BranchTrueFalseTotal
if lc $bare eq $self->{"_cached_hostname"} 2 5 7
3073 5 ▶ return 1 if lc($bare) eq $self->{'_cached_short_hostname'};
Branch: 1 branch
BranchTrueFalseTotal
if lc $bare eq $self->{"_cached_short_hostname"} 1 4 5
3074  
3075 4 return 0;
3076 }
3077  
3078 # ---------------------------------------------------------------------------
3079 # _load_remote_dir -- fetch and merge standard config files from one remote
3080 # host/directory pair.
3081 #
3082 # Silently skips files that do not exist; warns (or logs) on parse errors.
3083 # Merges into %$merged_ref using the same Hash::Merge LEFT_PRECEDENT strategy
3084 # as the local pipeline, so remote values override earlier local values.
3085 # ---------------------------------------------------------------------------
3086 sub _load_remote_dir
3087 14 ▶{
Subroutine _load_remote_dir: called CC=12 SCAR=24.8
3088 14 ▶ if(!UNIVERSAL::isa((caller)[0], __PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)) 1 13 14
3089 1 Carp::croak('Illegal Operation: This method can only be called by a subclass');
3090 }
3091  
3092 13 my ($self, $host, $remote_dir, $merged_ref, $file_list) = @_;
3093 13 my $logger = $self->{'logger'};
3094  
3095 13 ▶ unless($self->_load_driver('File::Slurp::Remote')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_load_driver("File::Slurp::Remote")) 3 10 13
3096 3 my $msg = ref($self) . ": File::Slurp::Remote required for /../$host$remote_dir but is not installed";
3097 3 ▶ $logger ? $logger->warn($msg) : Carp::carp($msg);
Branch: 1 branch
BranchTrueFalseTotal
$logger ? : 1 2 3
3098 3 return;
3099 }
3100  
3101 # Use the same file list as the local pipeline (includes TOML and env-specific tiers).
3102 # Fall back to the legacy list if none was passed (e.g. from very old callers).
3103 10 ▶ my @files = $file_list ? @{$file_list}
Branch: 1 branch
BranchTrueFalseTotal
$file_list ? : 1 9 10
3104 : qw(base.yaml base.yml base.json base.xml base.ini base.toml
3105 local.yaml local.yml local.json local.xml local.ini local.toml);
3106  
3107 10 for my $file (@files) {
3108 113 my $remote_path = "/../$host$remote_dir/$file";
3109  
3110 113 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 48 65 113
3111 48 $logger->debug(ref($self), ' ', __LINE__, ": Looking for remote config $remote_path");
3112 }
3113  
3114 113 my $raw = $self->_slurp_remote($host, "$remote_dir/$file");
3115 113 ▶ next unless defined($raw);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 107 6 113
3116  
3117 6 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 3 3 6
3118 3 $logger->debug(ref($self), ' ', __LINE__, ": Loading remote config $remote_path");
3119 }
3120  
3121 6 my $data = $self->_parse_config_string($raw, $file, $remote_path);
3122 6 ▶ next unless defined($data);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 1 5 6
3123  
3124 5 ▶ if(ref($data) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH") 3 2 5
3125 3 my $msg = ref($self) . ": remote $remote_path did not yield a hash; skipping";
3126 3 ▶ $logger ? $logger->warn($msg) : Carp::carp($msg);
Branch: 1 branch
BranchTrueFalseTotal
$logger ? : 1 2 3
3127 3 next;
3128 }
3129  
3130 2 push @{$self->{'_source_records'}}, {
3131 type => 'file',
3132 label => $remote_path,
3133 flat_data => { _flatten_keys($data) },
3134 };
3135 2 %{$merged_ref} = %{ merge($data, $merged_ref) };
3136 2 push @{$merged_ref->{'config_path'}}, $remote_path;
3137 }
3138 }
3139  
3140 # ---------------------------------------------------------------------------
3141 # _slurp_remote -- read a single file from a remote host via SSH.
3142 #
3143 # Wraps File::Slurp::Remote::read_file; returns the raw string on success
3144 # or undef on any error (connection refused, file absent, permission denied).
3145 # Errors are logged at debug level so missing files are not noisy.
3146 # ---------------------------------------------------------------------------
3147 sub _slurp_remote
3148 15 ▶{
Subroutine _slurp_remote: called CC=3 SCAR=11.0
3149 15 my ($self, $host, $path) = @_;
3150 15 my $logger = $self->{'logger'};
3151  
3152 # NOTE: verify the calling convention of your installed File::Slurp::Remote.
3153 # Common forms: read_file("$host:$path") or read_file($host, $path).
3154 15 my $content = eval { File::Slurp::Remote::read_file($host, $path) };
3155  
3156 15 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 13 15
3157 2 ▶ if($logger) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logger) 1 1 2
3158 1 $logger->debug(ref($self), ' ', __LINE__, ": Could not read $path from $host: $@");
3159 }
3160 2 return undef;
3161 }
3162 13 return $content;
3163 }
3164  
3165 # ---------------------------------------------------------------------------
3166 # _parse_config_string -- parse a raw config string by extension.
3167 #
3168 # Mirrors the format-detection logic used for local files. INI content is
3169 # written to a File::Temp scratch file because Config::IniFiles requires a
3170 # real filesystem path; the temp file is removed as soon as parsing returns.
3171 #
3172 # Returns a hashref on success, undef on failure.
3173 # ---------------------------------------------------------------------------
3174 sub _parse_config_string
3175 19 ▶{
Subroutine _parse_config_string: called CC=17 SCAR=28.8
3176 19 ▶ if(!UNIVERSAL::isa((caller)[0], __PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (UNIVERSAL::isa((&CORE::GLOBAL::caller())[0], __PACKAGE__)) 1 18 19
3177 1 Carp::croak('Illegal Operation: This method can only be called by a subclass');
3178 }
3179  
3180 18 my ($self, $raw, $filename, $label) = @_;
3181 18 my $logger = $self->{'logger'};
3182 18 my $data;
3183  
3184 18 eval {
3185 18 ▶ if($filename =~ /\.ya?ml$/i) {
Branch: 4 branches
BranchTrueFalseTotal
if ($filename =~ /\.ya?ml$/i) { } 9 9 18
elsif ($filename =~ /\.json$/i) { } 1 8 9
elsif ($filename =~ /\.xml$/i) { } 5 3 8
elsif ($filename =~ /\.ini$/i) { } 2 1 3
3186 9 $self->_load_driver('YAML::XS', ['Load']);
3187 9 $data = YAML::XS::Load($raw);
3188 6 ▶ $data = $self->_sanitize_yaml_values($data) if defined($data) && ref($data);
Branch: 1 branch
BranchTrueFalseTotal
if defined $data and ref $data 6 0 6
Condition33%1/3
defined $data and ref $data
!ll&&!rl&&r
006
MC/DC0%0/2
defined $data and ref $data
defined $data ref $data
Truth table33%1/3
A and B
A= defined $dataB= ref $data
ABresult
0X0
100
111
3189  
3190 } elsif($filename =~ /\.json$/i) {
3191 1 $data = decode_json($raw);
3192  
3193 } elsif($filename =~ /\.xml$/i) {
3194 5 ▶ if($self->_load_driver('XML::Simple', ['XMLin'])) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_load_driver('XML::Simple', ['XMLin'])) { } 0 5 5
elsif ($self->_load_driver('XML::PP')) { } 5 0 5
3195 0 ▶ if($raw !~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($raw =~ /<!ENTITY\s+\w+\s+(?:SYSTEM|PUBLIC)\b/i) 0 0 0
3196 0 $data = XMLin(\$raw, ForceArray => 0, KeyAttr => []);
3197 }
3198 } elsif($self->_load_driver('XML::PP')) {
3199 5 my $pp = XML::PP->new();
3200 5 ▶ if(my $tree = $pp->parse(\$raw)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tree = $pp->parse(\$raw)) 4 1 5
3201 4 $data = $pp->collapse_structure($tree);
3202 4 ▶ $data = $data->{'config'} if ($data && $data->{'config'});
Branch: 1 branch
BranchTrueFalseTotal
if $data and $data->{"config"} 3 1 4
Condition66%2/3
$data and $data->{"config"}
!ll&&!rl&&r
013
MC/DC50%1/2
$data and $data->{"config"}
$data $data->{"config"}
Truth table66%2/3
A and B
A= $dataB= $data->{"config"}
ABresult
0X0
100
111
3203 }
3204 }
3205  
3206 } elsif($filename =~ /\.ini$/i) {
3207 2 $self->_load_driver('Config::IniFiles');
3208 2 require File::Temp;
3209 2 my $tmp = File::Temp->new(SUFFIX => '.ini', UNLINK => 1);
3210 2 print {$tmp} $raw;
3211 2 $tmp->flush();
3212 2 ▶ if(my $ini = Config::IniFiles->new(-file => $tmp->filename())) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ini = "Config::IniFiles"->new("-file", $tmp->filename)) 1 1 2
3213 $data = { map {
3214 1 my $section = $_;
3215 1 $section => { map { $_ => $ini->val($section, $_) } $ini->Parameters($section) }
3216 } $ini->Sections() };
3217 }
3218 }
3219 };
3220  
3221 18 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 3 15 18
3222 3 my $err = $@;
3223 3 my $msg = ref($self) . ": Failed to parse $label: $err";
3224 3 ▶ $logger ? $logger->warn($msg) : Carp::carp($msg);
Branch: 1 branch
BranchTrueFalseTotal
$logger ? : 2 1 3
3225 3 return undef;
3226 }
3227  
3228 15 return $data;
3229 }
3230  
3231 sub AUTOLOAD
3232 950 ▶{
Subroutine AUTOLOAD: called CC=9 SCAR=22.0
3233 950 our $AUTOLOAD;
3234  
3235 950 my $self = shift;
3236 950 my $key = $AUTOLOAD;
3237  
3238 950 $key =~ s/.*:://; # remove package name
3239 950 ▶ return if $key eq 'DESTROY';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "DESTROY" 910 40 950
3240  
3241 40 $self->_ensure_loaded();
3242  
3243 # my $val = $self->get($key);
3244 # return $val if(defined($val));
3245  
3246 # Always use the merged config, not the raw pre-merge $self->{data}.
3247 # Using $self->{data} here would bypass file and env overrides entirely.
3248 40 my $data = $self->{'config'};
3249 40 my $sep = $self->{'sep_char'};
3250  
3251 # When flattening is ON, Hash::Flatten stores keys with '.' as separator.
3252 # Convert the sep_char-separated AUTOLOAD key to the dotted form first,
3253 # then fall back to the raw key in case sep_char happens to be '.'.
3254 40 ▶ if($self->{flatten}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"flatten"}) 10 30 40
3255 10 ▶ my $dot_key = ($sep ne '.') ? do { (my $k = $key) =~ s/\Q$sep\E/./g; $k } : $key;
Branch: 1 branch
BranchTrueFalseTotal
$sep ne '.' ? : 10 0 10
3256 10 ▶ return $data->{$dot_key} if exists $data->{$dot_key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $data->{$dot_key} 8 2 10
3257 2 ▶ return $data->{$key} if exists $data->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $data->{$key} 1 1 2
3258 1 croak "No such config key '$key'";
3259 }
3260  
3261 # Nested (non-flat) mode: walk the config tree one part at a time.
3262 30 my $val = $data;
3263 30 foreach my $part (split /\Q$sep\E/, $key) {
3264 45 ▶ if((ref($val) eq 'HASH') && (exists $val->{$part})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq 'HASH' and exists $val->{$part}) { } 37 8 45
Condition100%3/3
ref $val eq "HASH" and exists $val->{$part}
!ll&&!rl&&r
1737
MC/DC100%2/2
ref $val eq "HASH" and exists $val->{$part}
ref $val eq "HASH" exists $val->{$part}
Truth table100%3/3
A and B
A= ref $val eq "HASH"B= exists $val->{$part}
ABresult
0X0
100
111
3265 37 $val = $val->{$part};
3266 } else {
3267 8 croak "No such config key '$key'";
3268 }
3269 }
3270 22 return $val;
3271 }
3272  
3273 22 1;
3274  
3275 =head1 ENCRYPTED VALUES
3276  
3277 Config::Abstraction supports transparent AES-256-GCM encryption of individual
3278 configuration values. This lets you store secrets (passwords, API keys, tokens)
3279 in config files without exposing them as plaintext, even when those files are
3280 committed to version control.
3281  
3282 =head2 Quick start
3283  
3284 B<Step 1 -- generate a key:>
3285  
3286 # 32 random bytes, encoded as 64 hex chars
3287 perl -e 'use Crypt::PRNG qw(random_bytes); use MIME::Base64 qw(encode_base64url);
3288 print encode_base64url(random_bytes(32)), "\n"'
3289  
3290 Store the result in an environment variable or a key file (outside version control):
3291  
3292 export ENCRYPTION_KEY=<the 44-char base64url output>
3293  
3294 B<Step 2 -- encrypt a secret value:>
3295  
3296 perl -MConfig::Abstraction -e '
3297 my $cfg = Config::Abstraction->new(data => {});
3298 print $cfg->encrypt_value("my_secret_password"), "\n";
3299 '
3300  
3301 This prints something like:
3302  
3303 ENC[AES256GCM,QkJCQkJCQkJCQkJCO6Gfb0o5...]
3304  
3305 B<Step 3 -- paste the token into your config file:>
3306  
3307 # config/base.yaml
3308 database:
3309 host: db.example.com
3310 user: myapp
3311 password: 'ENC[AES256GCM,QkJCQkJCQkJCQkJCO6Gfb0o5...]'
3312  
3313 B<Step 4 -- load and use normally:>
3314  
3315 my $cfg = Config::Abstraction->new(config_dirs => ['config']);
3316 # $cfg->get('database.password') returns 'my_secret_password' -- already decrypted
3317  
3318 =head2 Key configuration
3319  
3320 The encryption key is resolved in this order (first match wins):
3321  
3322 =over 4
3323  
3324 =item 1. C<encryption_key> constructor option (raw bytes, hex, or base64)
3325  
3326 =item 2. C<{env_prefix}ENCRYPTION_KEY> environment variable (default: C<APP_ENCRYPTION_KEY>)
3327  
3328 =item 3. C<ENCRYPTION_KEY> environment variable
3329  
3330 =item 4. File at C<encryption_key_file> constructor option
3331  
3332 =item 5. File at C<{env_prefix}ENCRYPTION_KEY_FILE> environment variable
3333  
3334 =item 6. File at C<ENCRYPTION_KEY_FILE> environment variable
3335  
3336 =back
3337  
3338 The key file should contain the key on its first line in any supported format.
3339 B<Never commit the key to version control.>
3340  
3341 =head2 Token format
3342  
3343 ENC[AES256GCM,<base64url(nonce || ciphertext || tag)>]
3344  
3345 =over 4
3346  
3347 =item * C<AES256GCM> -- AES-256 in GCM mode (authenticated encryption)
3348  
3349 =item * Nonce -- 12 random bytes (fresh per encryption, never reused)
3350  
3351 =item * GCM authentication tag -- 16 bytes; any modification causes decryption to croak
3352  
3353 =item * Base64url encoding -- URL-safe alphabet, no padding ambiguity
3354  
3355 =back
3356  
3357 =head2 Behaviour when no key is configured
3358  
3359 If no key is found, C<ENC[...]> tokens are left as literal strings. This means
3360 the feature is purely opt-in: existing deployments without a key configured are
3361 unaffected.
3362  
3363 =head2 Requirements
3364  
3365 L<CryptX> (C<Crypt::AuthEnc::GCM>, C<Crypt::PRNG>) must be installed:
3366  
3367 cpanm CryptX
3368  
3369 =head1 COMMON PITFALLS
3370  
3371 =head2 1. new() returns undef when no configuration is found
3372  
3373 C<new()> returns C<undef>, not a blessed object, when no configuration data is
3374 found and no C<data> argument was supplied. Every caller must check the return value.
3375  
3376 my $cfg = Config::Abstraction->new(config_dirs => ['/etc/myapp']);
3377 die "No configuration found" unless defined $cfg;
3378 my $host = $cfg->get('database.host'); # safe
3379  
3380 Forgetting the check leads to a cryptic "Can't call method on undef" error later,
3381 with a stack trace that points to C<get()> rather than to the missing config file.
3382  
3383 =head2 2. merge_defaults() requires a named argument, not a bare hashref
3384  
3385 # WRONG -- Params::Get fast-path returns the whole config unchanged
3386 my $merged = $cfg->merge_defaults(\%my_defaults);
3387  
3388 # RIGHT
3389 my $merged = $cfg->merge_defaults(defaults => \%my_defaults);
3390  
3391 With the first form, C<Params::Get> treats the single hashref as the entire
3392 parameter bag and returns the full config without merging anything.
3393  
3394 =head2 3. Shallow merge in merge_defaults() silently drops nested keys from defaults
3395  
3396 Without C<merge =E<gt> 1>, C<merge_defaults()> uses a plain Perl hash merge
3397 (C<{ %defaults, %config }>) at the top level. If the config contains a nested hash
3398 for a key, it entirely replaces the corresponding nested hash in your defaults - any
3399 keys that exist only in the defaults' nested hash are silently discarded.
3400  
3401 my $cfg = Config::Abstraction->new(
3402 data => { db => { host => 'localhost', port => 5432 } },
3403 config_dirs => [],
3404 );
3405  
3406 my $merged = $cfg->merge_defaults(defaults => { db => { user => 'guest' } });
3407 # $merged->{db}{user} is UNDEF -- the whole 'db' hash was replaced by the config's version
3408  
3409 # To combine nested keys from both sides, pass merge => 1:
3410 my $merged = $cfg->merge_defaults(defaults => { db => { user => 'guest' } }, merge => 1);
3411 # $merged->{db}{user} is 'guest', $merged->{db}{host} is 'localhost'
3412  
3413 =head2 4. undef from a higher-priority source permanently wins
3414  
3415 C<Hash::Merge> LEFT_PRECEDENT means that an explicit C<undef> (YAML C<~>) in a
3416 higher-priority source overrides a real value in a lower-priority source, including
3417 when the lower-priority value is defined.
3418  
3419 # base.yaml: timeout: 30
3420 # local.yaml: timeout: ~
3421  
3422 my $t = $cfg->get('timeout'); # undef -- local.yaml's null wins over base.yaml
3423  
3424 This is intentional: it lets a local config deliberately unset a value. If you
3425 want to detect whether a key was explicitly nulled versus simply absent, use
3426 C<explain_sources()> and inspect the C<sources> list.
3427  
3428 =head2 5. Double underscore vs. single underscore in environment variable names
3429  
3430 Single underscores are part of the key name; double underscores create a nesting level.
3431  
3432 APP_LOG_LEVEL=debug => key 'log_level' (single underscore, flat key)
3433 APP_DATABASE__HOST=db => key 'database.host' (double underscore, nested)
3434 APP_API__RATE_LIMIT=100 => key 'api.rate_limit' (double underscore + single)
3435  
3436 A common mistake is using single underscores expecting nested keys:
3437  
3438 APP_DATABASE_HOST=db # produces key 'database_host', NOT 'database.host'
3439  
3440 =head2 6. Using AUTOLOAD requires sep_char set to '_'
3441  
3442 AUTOLOAD translates method names to config keys using C<sep_char>. The default
3443 C<sep_char> is C<'.'>, but method names cannot contain dots. Set C<sep_char =E<gt> '_'>
3444 to use AUTOLOAD, and be aware that this makes single underscores into hierarchy separators.
3445  
3446 my $cfg = Config::Abstraction->new(
3447 data => { database => { host => 'localhost' } },
3448 sep_char => '_',
3449 config_dirs => [],
3450 );
3451 my $host = $cfg->database_host(); # works
3452 my $bad = $cfg->no_such_key(); # dies: No such config key 'no_such_key'
3453  
3454 =head2 7. Absolute config_file paths require an empty or omitted config_dirs
3455  
3456 On Unix, C<File::Spec-E<gt>catfile('/etc', '/absolute/path.yaml')> concatenates the
3457 two strings instead of letting the absolute path take over, producing a wrong path.
3458 When C<config_file> is an absolute path, either omit C<config_dirs> entirely
3459 (the constructor sets it to C<['']> automatically) or pass C<config_dirs =E<gt> ['']>
3460 explicitly.
3461  
3462 # WRONG on Unix -- produces '/etc/etc/myapp/app.yaml'
3463 Config::Abstraction->new(
3464 config_file => '/etc/myapp/app.yaml',
3465 config_dirs => ['/etc'],
3466 );
3467  
3468 # RIGHT
3469 Config::Abstraction->new( config_file => '/etc/myapp/app.yaml' );
3470  
3471 =head2 8. Tests must isolate from the developer's real config files
3472  
3473 A call to C<new()> without C<config_dirs> will scan C</etc>, C<~/.conf>,
3474 C<~/.config>, and other default locations and load any C<base.yaml> or
3475 C<local.yaml> it finds there. In a test suite this injects real host
3476 configuration into your test object, causing non-deterministic failures.
3477  
3478 Always pass C<config_dirs =E<gt> []> in tests that use only in-memory C<data>:
3479  
3480 my $cfg = Config::Abstraction->new(
3481 data => { key => 'value' },
3482 config_dirs => [], # do not scan the filesystem
3483 );
3484  
3485 =head2 9. lazy => 1 defers errors until the first accessor call
3486  
3487 With C<lazy =E<gt> 1>, C<new()> always returns a blessed object - it cannot return
3488 C<undef> for a missing config, and any schema validation errors surface at the first
3489 C<get()> or C<all()> call rather than at construction time. See the C<lazy>
3490 option documentation in L</new> for the full list of debugging implications.
3491  
3492 =head1 VERSION HISTORY
3493  
3494 Notable changes by release. Full details are in the C<Changes> file.
3495  
3496 =over 4
3497  
3498 =item * B<0.43> (unreleased)
3499  
3500 Includes (C<allow_includes>), variable interpolation (C<interpolate>) and
3501 Apache-style C<*.conf> files via the optional L<Config::General>.
3502  
3503 =item * B<0.40> (unreleased)
3504  
3505 TOML file support (C<*.toml>) via C<TOML::Tiny>; C<base.toml> and C<local.toml>
3506 are now discovered automatically alongside the YAML/JSON/XML/INI equivalents,
3507 and TOML is also tried in the all-parsers chain for extensionless C<config_file>
3508 entries.
3509 Lazy loading (C<lazy =E<gt> 1> constructor option) defers all source discovery
3510 and file I/O until the first accessor call.
3511 New C<explain_sources()> method returns a per-key audit trail showing every
3512 source that contributed to a value, in precedence order.
3513 New C<prefer_env()>, C<prefer_file()>, C<prefer_data()>, and C<prefer_argv()>
3514 shortcut methods return the value from a specific source layer without re-ordering.
3515 Fixed C<merge_defaults()> permanently mutating the internal config hash
3516 (now works on a shallow copy).
3517 Fixed C<Hash::Merge> clone-behaviour global state leaking between calls
3518 (C<get_clone_behavior()> is now saved and restored, preventing "Can't store CODE
3519 items" crashes when C<data> contains coderefs).
3520 Newcastle Connection remote configuration: C<config_dirs> entries beginning with
3521 C</../hostname/path> are fetched over SSH via L<File::Slurp::Remote>.
3522 Local-host entries (C</../localhost/>, C</../127.0.0.1/>, etc.) are short-circuited
3523 to a plain local read - no SSH connection is made.
3524  
3525 =item * B<0.39> (2026-05-24)
3526  
3527 Disabled C<Data::Reuse::fixate()> - behaviour differed between Linux and macOS
3528 in a way that could not be resolved portably.
3529  
3530 =item * B<0.38> (2026-05-20)
3531  
3532 Fixed corruption of coderefs and blessed objects passed via the C<data> argument
3533 (added C<_is_plain_scalar()> guard in the YAML value-munging loop).
3534 Fixed C<exists()> to return explicit C<0> rather than empty string in flat mode.
3535 Fixed C<Data::Reuse::fixate()> crash in C<get()>.
3536 Fixed circular initialisation crash when the C<logger> option is provided.
3537 Documented the C<defaults> argument to C<new()>.
3538  
3539 =item * B<0.36> (2025-10-15)
3540  
3541 Added C<exists()> method.
3542 Files that fail to parse now emit a warning and are skipped rather than aborting
3543 construction.
3544  
3545 =item * B<0.34> (2025-09-05)
3546  
3547 Added C<bin/config-dump> CLI tool.
3548 Schema validation via C<Params::Validate::Strict> (C<schema> option).
3549  
3550 =item * B<0.25> (2025-05-15)
3551  
3552 Added C<merge_defaults()> C<merge> option (recursive Hash::Merge merge).
3553  
3554 =item * B<0.20> (2025-05-06)
3555  
3556 Added C<merge_defaults()>.
3557  
3558 =item * B<0.19> (2025-05-06)
3559  
3560 The C<data> constructor argument now sets default values that are overridden by files.
3561  
3562 =item * B<0.13> (2025-04-22)
3563  
3564 Added C<data> option to C<new()>.
3565 Added AUTOLOAD support for method-style key access.
3566 Added C<sep_char> option.
3567  
3568 =item * B<0.06> (2025-04-09)
3569  
3570 C<config_path> key in C<all()> output lists the files actually loaded.
3571 Format drivers are now lazy-loaded (only C<require>d when a file of that format is
3572 found).
3573  
3574 =item * B<0.01> (2025-04-07)
3575  
3576 First release.
3577  
3578 =back
3579  
3580 =head1 LIMITATIONS
3581  
3582 =over 4
3583  
3584 =item * B<No separator escaping>
3585  
3586 The separator character (C<sep_char>, default C<.>) cannot be embedded in a key name.
3587 A key that literally contains a dot cannot be accessed via C<get()> when C<sep_char> is
3588 the default. Workaround: set C<sep_char> to a character not present in any key.
3589  
3590 =item * B<Data::Reuse fixation disabled>
3591  
3592 The C<Data::Reuse::fixate()> call inside C<get()> is currently a no-op because the
3593 behaviour of C<Crypt::Storable::dclone> differs between Linux and macOS in a way
3594 that cannot be resolved portably (RT#100461). Hash values returned by C<get()> are
3595 mutable references, not read-only copies.
3596  
3597 =item * B<Windows environment variable case sensitivity>
3598  
3599 On Windows, environment variable names are case-insensitive at the OS level but
3600 case-sensitive in C<%ENV> as seen by Perl. Overriding config keys via environment
3601 variables may silently fail if the case does not match exactly.
3602  
3603 =item * B<AUTOLOAD requires sep_char set to '_'>
3604  
3605 AUTOLOAD method dispatch converts underscores to key separators. If C<sep_char> is
3606 the default C<'.'>, AUTOLOAD cannot reach nested keys because Perl method names cannot
3607 contain dots.
3608  
3609 =item * B<Includes are checked, then read>
3610  
3611 The directory check on an included file resolves its path and reads it a moment
3612 later. Someone who can write to the configuration directory could swap the file
3613 for a symbolic link in between. Anyone with that access can already change the
3614 configuration, so this is not a privilege boundary, but do not rely on
3615 C<include_dirs> to confine a directory that untrusted users can write to.
3616  
3617 =item * B<Interpolation reaches values from every source>
3618  
3619 With C<interpolate>, a configuration value is expanded whichever source it came
3620 from, so an C<APP_> environment variable or command-line argument that
3621 contains C<${env:NAME}> will pull in that other variable. The text of a
3622 variable read through C<${env:NAME}> is inserted as it is, without being
3623 expanded again.
3624  
3625 =item * B<Remote directory TOML support requires File::Slurp::Remote>
3626  
3627 TOML files in Newcastle Connection remote directories are only fetched when the
3628 C<File::Slurp::Remote> module is installed. Without it, remote directories are
3629 skipped entirely regardless of file format.
3630  
3631 =back
3632  
3633 =head1 BUGS
3634  
3635 It should be possible to escape the separator character either with backslashes or quotes.
3636  
3637 Due to the case-insensitive nature of environment variables on Windows,
3638 it may be challenging to override values using environment variables on that platform.
3639  
3640 =head1 REPOSITORY
3641  
3642 L<https://github.com/nigelhorne/Config-Abstraction>
3643  
3644 =head1 SUPPORT
3645  
3646 This module is provided as-is without any warranty.
3647  
3648 Please report any bugs or feature requests to C<bug-config-abstraction at rt.cpan.org>,
3649 or through the web interface at
3650 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Config-Abstraction>.
3651 I will be notified, and then you'll
3652 automatically be notified of progress on your bug as I make changes.
3653  
3654 You can find documentation for this module with the perldoc command.
3655  
3656 perldoc Config::Abstraction
3657  
3658 =head1 SEE ALSO
3659  
3660 =over 4
3661  
3662 =item * L<File::Slurp::Remote>
3663  
3664 Used to fetch configuration from remote hosts when C<config_dirs> contains
3665 Newcastle Connection paths (C</../hostname/path>).
3666  
3667 =item * L<Config::Any>
3668  
3669 =item * L<Config::Auto>
3670  
3671 =item * L<Config::General>
3672  
3673 =item * L<Data::Reuse>
3674  
3675 Used to C<fixate()> elements when installed, unless C<no-fixate> is given
3676  
3677 =item * L<Hash::Merge>
3678  
3679 =item * L<Log::Abstraction>
3680  
3681 =item * L<Test Dashboard|https://nigelhorne.github.io/Config-Abstraction/coverage/>
3682  
3683 =item * Development version on GitHub L<https://github.com/nigelhorne/Config-Abstraction>
3684  
3685 =back
3686  
3687 =head1 AUTHOR
3688  
3689 Nigel Horne, C<< <njh at nigelhorne.com> >>
3690  
3691 =encoding UTF-8
3692  
3693 =head1 FORMAL SPECIFICATION
3694  
3695 =head2 get
3696  
3697 get : Config x Key → Value ∪ {⊥}
3698 get(c, k) ≜ if k = ⊥ then ⊥
3699 else lookup(c.config, split(c.sep_char, k))
3700 lookup(h, []) ≜ h
3701 lookup(h, p:rest) ≜ if p ∉ dom(h) then ⊥
3702 else lookup(h[p], rest)
3703  
3704 =head2 encrypt_value
3705  
3706 encrypt_value : Config x Plaintext → Token
3707 encrypt_value(c, p) ≜
3708 let k = resolve_key(c) where k ≠ ⊥
3709 let n ~ Uniform(Bytes^12) -- fresh random nonce
3710 let ct = AES256GCM_enc(k, n, p)
3711 let t = GCM_tag(k, n, p)
3712 in "ENC[AES256GCM," || base64url(n || ct || t) || "]"
3713  
3714 =head2 exists
3715  
3716 exists : Config x Key → {0, 1}
3717 exists(c, k) ≜ if k = ⊥ then 0
3718 else 1 if lookup(c.config, split(c.sep_char, k)) ≠ ⊥
3719 else 0
3720  
3721 =head2 all
3722  
3723 all : Config → HashRef ∪ {⊥}
3724 all(c) ≜ if |dom(c.config)| = 0 then ⊥ else c.config
3725  
3726 =head1 LICENCE AND COPYRIGHT
3727  
3728 Copyright 2025-2026 Nigel Horne.
3729  
3730 Usage is subject to the GPL2 licence terms.
3731 If you use it,
3732 please let me know.
3733  
3734 =cut
3735  
3736 22 1;
↑ Summary