blib/lib/Config/Abstraction.pm

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