blib/lib/CLI/Startup.pm

filter: Statementstmt 96.9% 472 / 487 Branchbran 78.7% 167 / 212 Conditioncond 73.9% 51 / 69 MC/DCmcdc 52.5% 21 / 40 Subroutinesub 100% 62 / 62 Podpod 100% 20 / 20 totaltotal 89.1% 793 / 890 SCAR 52.5
CC
163
Cov
90%
_validate_optspec
26.6
_process_command_line
14.0
_parse_setting
13.7
CRAP 190.8
↑ Summary Build »
1 package CLI::Startup;
2  
3 10 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 10 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use Symbol;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 ▶use Pod::Text;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use Text::CSV;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use Class::Std;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use Config::Any;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 10 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 10 ▶use File::HomeDir;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 10 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 10 ▶use Clone qw{ clone };
Subroutine BEGIN: called CC=1 SCAR=0.0
18 10 ▶use Hash::Merge qw{ merge };
Subroutine BEGIN: called CC=1 SCAR=0.0
19 10 ▶use List::Util qw{ max reduce };
Subroutine BEGIN: called CC=1 SCAR=0.0
20 10 use Getopt::Long qw{
21 :config posix_default bundling require_order no_ignore_case
22 10 ▶};
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 10 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
25 10 our @EXPORT_OK = qw/startup/;
26  
27 10 our $VERSION = '0.27'; # Don't forget to update the manpage version, too!
28  
29 10 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 10 Readonly my $V_FOR_VERBOSE => 'ALIAS OF VERBOSE';
31 10 Readonly my $V_OPTSPEC => 'v+';
32  
33 # Simple command-line processing with transparent
34 # support for config files.
35 sub startup
36 {
37 24 ▶ my $optspec = shift;
Subroutine startup: called CC=1 SCAR=0.0
Pod documented
38  
39 24 my $app = CLI::Startup->new($optspec);
40 20 $app->init;
41  
42 7 return $app->get_options;
43 }
44  
45 #<<< Leave this alone, perltidy
46 # Attributes of our inside-out objects.
47 10 my %config_of : ATTR();
48 10 my %initialized_of : ATTR( :get<initialized> );
49 10 my %options_of : ATTR();
50 10 my %optspec_of : ATTR( :initarg<optspec> );
51 10 my %raw_options_of : ATTR();
52 10 my %rcfile_of : ATTR( :get<rcfile> :initarg<rcfile> );
53 10 my %usage_of : ATTR( :get<usage> :initarg<usage> );
54 10 my %write_rcfile_of : ATTR( :get<write_rcfile> :initarg<write_rcfile> );
55 10 my %default_settings_of :
56 ATTR( :get<default_settings> :initarg<default_settings> );
57 #>>>
58  
59 # Returns a clone of the config object.
60 sub get_config
61 {
62 30 ▶ my $self = shift;
Subroutine get_config: called CC=2 SCAR=6.9
Pod documented
63 30 ▶ $self->die('get_config() called before init()')
Branch: 1 branch
BranchTrueFalseTotal
unless $self->get_initialized 1 29 30
64 unless $self->get_initialized;
65 29 return clone( $config_of{ ident $self} );
66 }
67  
68 # Set defaults for the command-line options. Can be done as much as
69 # desired until the app is initialized.
70 sub set_default_settings
71 {
72 5 ▶ my ( $self, $settings ) = @_;
Subroutine set_default_settings: called CC=4 SCAR=13.9
Pod documented
73  
74 5 ▶ $self->die('set_default_settings() requires a hashref')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $settings and ref $settings eq "HASH" 2 3 5
Condition100%3/3
defined $settings and ref $settings eq "HASH"
!ll&&!rl&&r
113
MC/DC100%2/2
defined $settings and ref $settings eq "HASH"
defined $settings ref $settings eq "HASH"
Truth table100%3/3
A and B
A= defined $settingsB= ref $settings eq "HASH"
ABresult
0X0
100
111
75 unless defined $settings and ref $settings eq 'HASH';
76 3 ▶ $self->die('set_default_settings() called after init()')
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_initialized 1 2 3
77 if $self->get_initialized;
78  
79 2 $default_settings_of{ ident $self} = clone($settings);
80  
81 2 return; # Needed so we don't leak a reference to the data!
82 }
83  
84 # Get the options provided on the command line. This, unlike most of
85 # the others, can ONLY be called after the app is initialized.
86 sub get_options
87 {
88 23 ▶ my $self = shift;
Subroutine get_options: called CC=2 SCAR=6.9
Pod documented
89 23 ▶ $self->die('get_options() called before init()')
Branch: 1 branch
BranchTrueFalseTotal
unless $self->get_initialized 1 22 23
90 unless $self->get_initialized;
91 22 return clone( $options_of{ ident $self} );
92 }
93  
94 # Returns the current specifications for the command-line options.
95 sub get_optspec
96 {
97 185 ▶ my $self = shift;
Subroutine get_optspec: called CC=1 SCAR=0.0
Pod documented
98 185 return clone( $optspec_of{ ident $self} );
99 }
100  
101 # Set the specifications of the current command-line options.
102 sub set_optspec
103 {
104 71 ▶ my $self = shift;
Subroutine set_optspec: called CC=3 SCAR=11.0
Pod documented
105 71 my $spec = shift;
106  
107 71 ▶ $self->die('set_optspec() requires a hashref')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 1 70 71
108 unless ref $spec eq 'HASH';
109 70 ▶ $self->die('set_optspec() called after init()')
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_initialized 1 69 70
110 if $self->get_initialized;
111  
112 69 $optspec_of{ ident $self} = clone( $self->_validate_optspec($spec) );
113  
114 64 return; # Needed so we don't leak a reference to the data!
115 }
116  
117 # Returns a clone of the actual command-line options.
118 sub get_raw_options
119 {
120 19 ▶ my $self = shift;
Subroutine get_raw_options: called CC=2 SCAR=6.9
Pod documented
121 19 ▶ $self->die('get_raw_options() called before init()')
Branch: 1 branch
BranchTrueFalseTotal
unless $self->get_initialized 1 18 19
122 unless $self->get_initialized;
123 18 return clone( $raw_options_of{ ident $self} );
124 }
125  
126 # Set the filename of the rcfile for the app.
127 sub set_rcfile
128 {
129 70 ▶ my ( $self, $rcfile ) = @_;
Subroutine set_rcfile: called CC=2 SCAR=6.9
Pod documented
130  
131 70 ▶ $self->die('set_rcfile() called after init()')
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_initialized 1 69 70
132 if $self->get_initialized;
133 69 $rcfile_of{ ident $self} = "$rcfile";
134  
135 69 return;
136 }
137  
138 # Set the usage string for the app. Only needed if there are
139 # arguments other than command-line options.
140 sub set_usage
141 {
142 64 ▶ my ( $self, $usage ) = @_;
Subroutine set_usage: called CC=2 SCAR=6.9
Pod documented
143  
144 64 ▶ $self->die('set_usage() called after init()')
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_initialized 1 63 64
145 if $self->get_initialized;
146 63 $usage_of{ ident $self} = "$usage";
147  
148 63 return;
149 }
150  
151 # Set a file writer for the rc file.
152 sub set_write_rcfile
153 {
154 7 ▶ my $self = shift;
Subroutine set_write_rcfile: called CC=9 SCAR=22.0
Pod documented
155 7 ▶ my $writer = shift || 0;
Condition100%2/2
shift() || 0
l!l
34
MC/DC100%1/1
shift() || 0
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
156  
157 7 ▶ $self->die('set_write_rcfile() called after init()')
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_initialized 1 6 7
158 if $self->get_initialized;
159 6 ▶ $self->die('set_write_rcfile() requires a coderef or false')
Branch: 1 branch
BranchTrueFalseTotal
if $writer and ref $writer ne "CODE" 1 5 6
Condition100%3/3
$writer and ref $writer ne "CODE"
!ll&&!rl&&r
321
MC/DC100%2/2
$writer and ref $writer ne "CODE"
$writer ref $writer ne "CODE"
Truth table100%3/3
A and B
A= $writerB= ref $writer ne "CODE"
ABresult
0X0
100
111
160 if $writer && ref($writer) ne 'CODE';
161  
162 5 my $optspec = $optspec_of{ ident $self}; # Need a reference, not a copy
163  
164 # Toggle the various rcfile options if writing is turned on or off
165 5 ▶ if ($writer)
Branch: 1 branch
BranchTrueFalseTotal
if ($writer) { } 2 3 5
166 {
167 2 my $options = $self->_get_default_optspec;
168 2 my $aliases = $self->_option_aliases($options);
169  
170 2 for my $alias (qw{ rcfile write-rcfile rcfile-format })
171 {
172 6 ▶ $optspec->{$alias} ||= $options->{ $aliases->{$alias} };
Condition66%2/3
$optspec->{$alias} ||= $$options{$aliases->{$alias}}
l!l&&r!l&&!r
150
MC/DC0%0/2
$optspec->{$alias} ||= $$options{$aliases->{$alias}}
$optspec->{$alias} $$options{$aliases->{$alias}}
Truth table66%2/3
A ||= B
A= $optspec->{$alias}B= $$options{$aliases->{$alias}}
ABresult
1X1
011
000
173 }
174 }
175 else
176 {
177 3 for my $alias (qw{ rcfile write-rcfile rcfile-format })
178 {
179 9 delete $optspec->{$alias};
180 }
181 }
182  
183 # Save the writer
184 5 $write_rcfile_of{ ident $self} = $writer;
185  
186 5 return; # Needed so we don't leak a reference to the data!
187 }
188  
189 # Die with a standardized message format.
190 sub die ## no critic ( Subroutines::RequireFinalReturn )
191 {
192 24 ▶ my ( undef, $msg ) = @_;
Subroutine die: called CC=1 SCAR=0.0
Pod documented
193  
194 24 my $name = basename($PROGRAM_NAME);
195 24 CORE::die "$name: FATAL: $msg\n";
196 }
197  
198 # Die with a usage summary.
199 sub die_usage
200 {
201 8 ▶ my $self = shift;
Subroutine die_usage: called CC=1 SCAR=0.0
Pod documented
202 8 my $msg = shift;
203  
204 8 print { \*STDERR } $self->_usage_message($msg);
205 8 exit 1;
206 }
207  
208 # Return a usage message
209 sub _usage_message
210 {
211 14 ▶ my $self = shift;
Subroutine _usage_message: called CC=13 SCAR=26.0
212 14 my $msg = shift;
213 14 my $optspec = $self->get_optspec;
214 14 my $name = basename($PROGRAM_NAME);
215  
216 # The message to be returned
217 14 my $message = '';
218  
219 # This happens if options aren't defined in the constructor
220 # and then die_usage() is called directly or indirectly.
221 $self->die('_usage_message() called without defining any options')
222 14 ▶ unless keys %{$optspec};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$optspec;} 0 14 14
223  
224 #<<< Leave this alone, perltidy
225  
226 # In the usage text, show the option names, not the aliases.
227 my %options =
228 122 map { ( $_->{names}[0], $_ ) }
229 122 map { $self->_parse_spec( $_, $optspec->{$_} ) }
230 14 keys %{$optspec};
231  
232 #>>> End perltidy-free zone
233  
234 # Automatically suppress 'v' if it's an alias of 'verbose'
235 14 ▶ delete $options{v} if $optspec->{$V_OPTSPEC} // '' eq $V_FOR_VERBOSE;
Branch: 1 branch
BranchTrueFalseTotal
if $optspec->{$V_OPTSPEC} // "" eq $V_FOR_VERBOSE 14 0 14
Condition33%1/3
$optspec->{$V_OPTSPEC} // "" eq $V_FOR_VERBOSE
l!l&&r!l&&!r
1400
MC/DC0%0/2
$optspec->{$V_OPTSPEC} // "" eq $V_FOR_VERBOSE
$optspec->{$V_OPTSPEC} "" eq $V_FOR_VERBOSE
Truth table33%1/3
A // B
A= $optspec->{$V_OPTSPEC}B= "" eq $V_FOR_VERBOSE
ABresult
1X1
011
000
236  
237 # Note the length of the longest option
238 14 my $length = max map { length() } keys %options;
239  
240 # Print the requested message, if any
241 14 ▶ if ( defined $msg )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $msg) 2 12 14
242 {
243 ## no critic (ValuesAndExpressions::RequireInterpolationOfMetachars)
244 2 $message .= sprintf '%s: FATAL: %s\n', $name, $msg;
245 }
246  
247 # Now print the help message.
248 $message
249 14 .= 'usage: '
250 . basename($PROGRAM_NAME) . ' '
251 . $self->get_usage . "\n"
252 . "Options:\n";
253  
254 # Print the options, sorted in dictionary order.
255 14 for my $option ( sort keys %options )
256 {
257 ## no critic (ValuesAndExpressions::ProhibitMagicNumbers)
258 108 my $indent = $length + 8;
259 108 my $spec = $options{$option};
260  
261 # Print the basic help option
262 108 ▶ if ( length($option) == 1 )
Branch: 1 branch
BranchTrueFalseTotal
if (length $option == 1) { } 5 103 108
263 {
264 $message .= sprintf " -%-${length}s - %s\n", $option,
265 5 $spec->{desc};
266 }
267 else
268 {
269 $message .= sprintf " --%-${length}s - %s\n", $option,
270 103 $spec->{desc};
271 }
272  
273 108 my @aliases = @{ $spec->{names} };
274 108 shift @aliases;
275  
276 # Insert 'v' as an alias of 'verbose' if it is
277 push @aliases, 'v'
278 if $option eq 'verbose'
279 108 ▶ && $optspec->{$V_OPTSPEC} // '' eq $V_FOR_VERBOSE;
Branch: 1 branch
BranchTrueFalseTotal
if $option eq "verbose" && $optspec->{$V_OPTSPEC} // "" eq $V_FOR_VERBOSE 14 94 108
Condition50%3/6
$option eq "verbose" && $optspec->{$V_OPTSPEC} // "" eq $V_FOR_VERBOSE
l!l&&r!l&&!r
10800
$option eq "verbose" and $optspec->{$V_OPTSPEC}
!ll&&!rl&&r
94014
MC/DC0%0/3
$option eq "verbose" && $optspec->{$V_OPTSPEC} // "" eq $V_FOR_VERBOSE
$option eq "verbose" $optspec->{$V_OPTSPEC} "" eq $V_FOR_VERBOSE
Truth table20%1/5
A and B // C
A= $option eq "verbose"B= $optspec->{$V_OPTSPEC}C= "" eq $V_FOR_VERBOSE
ABCresult
11X1
0X11
1011
0X00
1000
280  
281 # Print aliases, if any
282 108 ▶ if ( @aliases > 0 )
Branch: 1 branch
BranchTrueFalseTotal
if (@aliases > 0) 57 51 108
283 {
284  
285 # Add in the dashes
286 57 ▶ @aliases = map { length() == 1 ? "-$_" : "--$_" } @aliases;
Branch: 1 branch
BranchTrueFalseTotal
length $_ == 1 ? : 59 0 59
287 57 $message .= sprintf "%${indent}s Aliases: %s\n", '',
288 join( ', ', @aliases );
289 }
290  
291 # Print negation, if any
292 108 ▶ if ( $spec->{boolean} )
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"boolean"}) 1 107 108
293 {
294 1 $message .= sprintf "%${indent}s Negate this with --no-%s\n", '',
295 $option;
296 }
297 }
298  
299 14 return $message;
300 }
301  
302 # Returns the "default" optspec, consisting of options
303 # that CLI::Startup normally creates automatically.
304 sub _get_default_optspec
305 {
306 return {
307 126 ▶ 'help|h' => 'Print this help message',
Subroutine _get_default_optspec: called CC=1 SCAR=0.0
308 'rcfile:s' => 'Config file to load',
309 'write-rcfile' => 'Write the current options to config file',
310 'rcfile-format=s' => 'Format to write the config file',
311 'version|V' => 'Print version information and exit',
312 'verbose:1' =>
313 'Print verbose messages', # Supports --verbose or --verbose=9
314 $V_OPTSPEC => $V_FOR_VERBOSE, # 'v+' Supports -vvv
315 'manpage|H' => 'Print the manpage for this script',
316 };
317 }
318  
319 # Parse the optspecs, returning a complete description of each.
320 sub _parse_optspecs
321 {
322 137 ▶ my ( $self, $optspecs ) = @_;
Subroutine _parse_optspecs: called CC=4 SCAR=13.9
323 137 my $parsed = { options => {}, aliases => {} };
324  
325 # Step through each option
326 137 for my $optspec ( keys %{$optspecs} )
327 {
328  
329 # Parse the spec completely
330 $parsed->{options}{$optspec}
331 712 = $self->_parse_spec( $optspec, $optspecs->{$optspec} );
332  
333 # Make a reverse-lookup by option name/alias
334 712 for my $alias ( @{ $parsed->{options}{$optspec}{names} } )
335 {
336  
337 # It's a fatal error to use the same alias twice
338 $self->die("--$alias option defined twice")
339 928 ▶ if defined $parsed->{aliases}{$alias};
Branch: 1 branch
BranchTrueFalseTotal
if defined $parsed->{"aliases"}{$alias} 1 927 928
340  
341 927 $parsed->{aliases}{$alias} = $optspec;
342 }
343 }
344  
345 136 return $parsed;
346 }
347  
348 # Parses the option specs, identifying array and hash data types
349 sub _option_data_types
350 {
351 50 ▶ my $self = shift;
Subroutine _option_data_types: called CC=5 SCAR=16.1
352 50 my $optspecs = $self->get_optspec;
353 50 my %types;
354  
355 # Build a list of the array and hash configs, so we can
356 # unflatten them from the config file if necessary.
357 50 for my $option ( keys %{$optspecs} )
358 {
359 550 my $spec = $self->_parse_spec( $option, $optspecs->{$option} );
360  
361 550 for my $type (qw{ array hash boolean count flag })
362 {
363 2750 ▶ next unless $spec->{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $spec->{$type} 2395 355 2750
364 355 $types{$_} = uc($type) for @{ $spec->{names} };
365 }
366 }
367  
368 50 return \%types;
369 }
370  
371 # Breaks an option spec down into its components.
372 sub _parse_spec
373 {
374 1448 ▶ my ( $self, $spec, $help_text ) = @_;
Subroutine _parse_spec: called CC=12 SCAR=24.9
375  
376 ## no critic ( Perl::Critic::Policy::RegularExpressions::ProhibitComplexRegexes )
377 ## no critic ( Perl::Critic::Policy::RegularExpressions::ProhibitUnusedCapture )
378  
379 # We really want the "name(s)" portion
380 1448 $spec =~ m{
381 (?:
382 (?&start)
383 (?<names> (?&word_list) )
384 (?:
385 (?: # Boolean
386 (?<type> (?&bang) (?&end) ) )
387 | (?: # Counter
388 (?<argument> (?&optional)? )
389 (?<type> (?&plus) (?&end) ) )
390 | (?: # Scalar types - number, integer, string
391 (?<argument> (?&arg) )
392 (?<subtype> (?&scalar_type) )
393 (?<type> (?&non_scalar)? ) )
394 | (?: # Int with default argument
395 (?<argument> (?&optional) )
396 (?<default> (?&integer) ) )
397 | (?: # Flag
398 (?&end) ) # Nothing to capture
399 )?
400 (?<garbage> (?&unmatched)? )
401  
402 # This ensures that every token is defined, even if only
403 # to the empty string.
404 (?<default> (?(<default>)) )
405 (?<type> (?(<type>)) )
406 (?<subtype> (?(<subtype>)) )
407 (?<argument> (?(<argument>)) )
408 )
409 (?(DEFINE)
410 (?<start> ^ )
411 (?<word_list> (?: (?&word) (?: (?&separator) (?&alias) )* ) )
412 (?<word> \w[-\w]* )
413 (?<alias> (?: [?] | (?&word) ) )
414 (?<separator> [|] )
415 (?<scalar_type> (?: [fions] ) )
416 (?<integer> (?: -? \d+ ) )
417 (?<arg> [:=] )
418 (?<optional> [:] )
419 (?<mandatory> [=] )
420 (?<non_scalar> [@%] )
421 (?<hash> [%] )
422 (?<array> [@] )
423 (?<bang> [!] )
424 (?<plus> [+] )
425 (?<end> (?! . ) )
426 (?<unmatched> (?: .* $ ) ) # This will be the last thing in an invalid spec
427 )
428 }xms;
429  
430 # Capture the pieces of the optspec that we found
431 1448 my %attrs = %LAST_PAREN_MATCH;
432  
433 # If there's anything left that we failed to match, it's a fatal error
434 1448 ▶ $self->die("Invalid optspec: $spec") if $attrs{garbage};
Branch: 1 branch
BranchTrueFalseTotal
if $attrs{"garbage"} 0 1448 1448
435  
436 ## no critic ( ValuesAndExpressions::ProhibitNoisyQuotes Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers)
437 #<< Leave this alone, perltidy
438  
439 # Note: doesn't identify string, int, float options
440 return {
441 spec => $spec,
442 names => [ split /[|]/xms, $attrs{names} ],
443 desc => $help_text,
444 default => $attrs{default},
445 required => ( $attrs{argument} eq '=' ? 1 : 0 ),
446 type => (
447 $attrs{subtype} eq '' ? 'i'
448 : $attrs{subtype} eq 'n' ? 'i'
449 : $attrs{subtype}
450 ),
451 array => ( $attrs{type} eq '@' ? 1 : 0 ),
452 hash => ( $attrs{type} eq '%' ? 1 : 0 ),
453 scalar => ( $attrs{type} !~ m{[@%]}xms ? 1 : 0 ),
454 boolean => ( $attrs{type} eq '!' ? 1 : 0 ),
455 count => ( $attrs{type} eq '+' ? 1 : 0 ),
456 1448 ▶ flag => ( $attrs{type} eq '' && $attrs{argument} eq '' ? 1 : 0 ),
Branch: 9 branches
BranchTrueFalseTotal
$attrs{'argument'} eq '=' ? : 327 1121 1448
$attrs{'subtype'} eq '' ? : 982 466 1448
$attrs{'subtype'} eq 'n' ? : 0 466 466
$attrs{'type'} eq '@' ? : 45 1403 1448
$attrs{'type'} eq '%' ? : 49 1399 1448
!($attrs{'type'} =~ /[\@%]/msx) ? : 1354 94 1448
$attrs{'type'} eq '!' ? : 26 1422 1448
$attrs{'type'} eq '+' ? : 144 1304 1448
$attrs{'type'} eq '' && $attrs{'argument'} eq '' ? : 671 777 1448
Condition100%3/3
$attrs{"type"} eq "" and $attrs{"argument"} eq ""
!ll&&!rl&&r
264513671
MC/DC100%2/2
$attrs{"type"} eq "" and $attrs{"argument"} eq ""
$attrs{"type"} eq "" $attrs{"argument"} eq ""
Truth table100%3/3
A and B
A= $attrs{"type"} eq ""B= $attrs{"argument"} eq ""
ABresult
0X0
100
111
457 };
458  
459 #>> End perltidy free zone
460 }
461  
462 # Returns a hash of option aliases and specifications from the
463 # supplied hash. Also converts undef to 0 in $optspec.
464 sub _option_aliases
465 {
466 8 ▶ my ( $self, $optspec ) = @_;
Subroutine _option_aliases: called CC=5 SCAR=16.2
467 8 my %option_aliases;
468  
469 # Make sure that there are no duplicated option names,
470 # and that options with undefined help text are defined
471 # to false.
472 8 for my $option ( keys %{$optspec} )
473 {
474 64 ▶ $optspec->{$option} ||= 0;
Condition50%1/2
$optspec->{$option} ||= 0
l!l
640
MC/DC0%0/1
$optspec->{$option} ||= 0
$optspec->{$option}
Truth table50%1/2
A
A= $optspec->{$option}
Aresult
11
00
475 64 $option = $self->_parse_spec( $option, $optspec->{$option} );
476  
477 # The spec can define aliases
478 64 for my $name ( @{ $option->{names} } )
479 {
480 $self->die("--$name option defined twice")
481 88 ▶ if exists $option_aliases{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $option_aliases{$name} 0 88 88
482 88 $option_aliases{$name} = $option->{spec};
483 }
484 }
485  
486 8 return \%option_aliases;
487 }
488  
489 # Returns an options spec hashref, with automatic options
490 # added in.
491 sub _validate_optspec
492 {
493  
494 # no critic ( Perl::Critic::Policy::Modules::ProhibitExcessMainComplexity )
495 69 ▶ my ( $self, $user_optspecs ) = @_;
Subroutine _validate_optspec: called CC=24 SCAR=32.8
496 69 my $default_optspecs = $self->_get_default_optspec;
497  
498 69 my $parsed;
499  
500 # Parse the user optspecs
501 69 $parsed = $self->_parse_optspecs($user_optspecs);
502 68 my $user_options = $parsed->{options};
503 68 my $user_aliases = $parsed->{aliases};
504  
505 # Parse the default optspecs
506 68 $parsed = $self->_parse_optspecs($default_optspecs);
507 68 my $default_options = $parsed->{options};
508 68 my $default_aliases = $parsed->{aliases};
509  
510 # While we're here, remember the "help" option settings for later.
511 # If a tricksy user deletes it, we'll put it back.
512 68 my $default_help_optspec = $default_aliases->{'help'};
513 68 my $default_help_parsed = $default_options->{$default_help_optspec};
514  
515 # At this point we also know that there are no conflicting aliases
516 # in either the user or default optspecs. So the only thing to check
517 # is whether the user invokes any of the default optspecs.
518  
519 # Step through each user alias. Check for collisions, and also delete
520 # any default options for which this was requested.
521 68 for my $alias ( keys %{$user_aliases} )
522 {
523  
524 # Only look at options that collide with default options.
525 176 ▶ next unless defined $default_aliases->{$alias};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $default_aliases->{$alias} 166 10 176
526  
527 # If the option specifications are identical, then we can
528 # skip this option.
529 10 my $user_optspec = $user_aliases->{$alias};
530 10 my $default_optspec = $default_aliases->{$alias};
531  
532 # If the option evaluates to true, it MAY be changing something,
533 # which is an error.
534 10 ▶ if ( $user_optspecs->{$user_optspec} || 0 )
Branch: 1 branch
BranchTrueFalseTotal
if ($user_optspecs->{$user_optspec} or 0) 5 5 10
Condition100%2/2
$user_optspecs->{$user_optspec} or 0
l!l
55
MC/DC100%1/1
$user_optspecs->{$user_optspec} or 0
$user_optspecs->{$user_optspec}
Truth table100%2/2
A
A= $user_optspecs->{$user_optspec}
Aresult
11
00
535 {
536 5 ▶ if ( $user_optspec ne $default_optspec )
Branch: 1 branch
BranchTrueFalseTotal
if ($user_optspec ne $default_optspec) 4 1 5
537 {
538 4 $self->die("Multiple definitions for --$alias option");
539 }
540 }
541  
542 # OK, this option is being deleted.
543  
544 # If the alias was not the primary name of the default option,
545 # then we delete only the specific alias requested.
546 6 my $default_name = $default_options->{$default_optspec}{names}[0];
547 6 ▶ if ( $alias ne $default_name )
Branch: 1 branch
BranchTrueFalseTotal
if ($alias ne $default_name) 0 6 6
548 {
549 0 delete $default_aliases->{$alias};
550 0 next;
551 }
552  
553 # Completely delete the default options corresponding to this alias.
554 6 for my $name ( @{ $default_options->{$default_optspec}{names} } )
555 {
556 8 delete $default_aliases->{$name};
557 }
558 6 delete $default_options->{$default_optspec};
559  
560 # Special case: we use two options to cover 'verbose'
561 6 ▶ if ( $alias eq 'verbose'
Branch: 1 branch
BranchTrueFalseTotal
if ($alias eq "verbose" and $default_optspecs->{$V_OPTSPEC} eq $V_FOR_VERBOSE) 2 4 6
Condition66%2/3
$alias eq "verbose" and $default_optspecs->{$V_OPTSPEC} eq $V_FOR_VERBOSE
!ll&&!rl&&r
402
MC/DC50%1/2
$alias eq "verbose" and $default_optspecs->{$V_OPTSPEC} eq $V_FOR_VERBOSE
$alias eq "verbose" $default_optspecs->{$V_OPTSPEC} eq $V_FOR_VERBOSE
Truth table66%2/3
A and B
A= $alias eq "verbose"B= $default_optspecs->{$V_OPTSPEC} eq $V_FOR_VERBOSE
ABresult
0X0
100
111
562 and $default_optspecs->{$V_OPTSPEC} eq $V_FOR_VERBOSE )
563 {
564 2 delete $default_options->{ $default_aliases->{v} };
565 2 delete $default_aliases->{v};
566 }
567 }
568  
569 # Remove any disabled user options. Options are disabled by
570 # setting them to anything that evaluates to false.
571 64 for my $optspec ( keys %{$user_options} )
572 {
573 159 ▶ next if $user_options->{$optspec}{desc} || 0;
Branch: 1 branch
BranchTrueFalseTotal
if $user_options->{$optspec}{"desc"} or 0 154 5 159
Condition100%2/2
$user_options->{$optspec}{"desc"} or 0
l!l
1545
MC/DC100%1/1
$user_options->{$optspec}{"desc"} or 0
$user_options->{$optspec}{"desc"}
Truth table100%2/2
A
A= $user_options->{$optspec}{"desc"}
Aresult
11
00
574  
575 5 for my $alias ( @{ $user_options->{$optspec}{names} } )
576 {
577 5 delete $user_aliases->{$alias};
578 }
579 5 delete $user_options->{$optspec};
580 }
581  
582 # Now we just check for ordinary collisions. Since we've performed any
583 # requested deletions, any collisions between user and default aliases
584 # means that an alias is defined twice.
585 64 for my $name ( keys %{$user_aliases} )
586 {
587 166 ▶ next unless defined $default_aliases->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $default_aliases->{$name} 166 0 166
588  
589 0 $self->die("Multiple definitions for --$name option");
590 }
591  
592 # The --help option is NOT optional, so we override it if it evaluates
593 # to false. It must be present, because if we didn't find it above we
594 # would have inserted it.
595 64 ▶ if ( not defined $user_aliases->{'help'} )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $user_aliases->{"help"}) 64 0 64
596 {
597 64 $user_options->{$default_help_optspec} = $default_help_parsed;
598 }
599  
600 # If the --rcfile option is disabled, then we must also delete the
601 # --rcfile-format and --write-rcfile options, since they make no
602 # sense in scripts that don't support config files.
603 64 ▶ if ( not defined $user_aliases->{rcfile} )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $user_aliases->{"rcfile"}) 64 0 64
604 {
605 64 for my $option (qw{ rcfile rcfile-format write-rcfile })
606 {
607 192 ▶ if ( defined $user_aliases->{$option} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $user_aliases->{$option}) 0 192 192
608 {
609 0 delete $user_options->{ $user_aliases->{$option} };
610 0 delete $user_aliases->{$option};
611 }
612 }
613 }
614  
615 # If rcfile writing is disabled, then we must delete the --rcfile-format
616 # option, which is meaningless when we don't write config files.
617 64 ▶ if ( not defined $user_aliases->{'write-rcfile'} )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $user_aliases->{"write-rcfile"}) 64 0 64
618 {
619 64 ▶ if ( defined $user_aliases->{'rcfile-format'} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $user_aliases->{"rcfile-format"}) 0 64 64
620 {
621 0 delete $user_options->{ $user_aliases->{'rcfile-format'} };
622 0 delete $user_aliases->{'rcfile-format'};
623 }
624 }
625  
626 # Create a new optspec which includes both the user and default options.
627 64 my $optspecs = {};
628  
629 64 for my $optspec ( keys %{$default_options} )
630 {
631 504 $optspecs->{$optspec} = $default_options->{$optspec}{desc};
632 }
633  
634 64 for my $optspec ( keys %{$user_options} )
635 {
636 218 $optspecs->{$optspec} = $user_options->{$optspec}{desc};
637 }
638  
639 64 return $optspecs;
640 }
641  
642 # This is the core method of the whole module: it actually does the
643 # command-line processing, config-file reading, etc.. Once it
644 # completes, most of the write accesors are disabled, and this
645 # object becomes a reference for looking up configuration info.
646 sub init
647 {
648 61 ▶ my $self = shift;
Subroutine init: called CC=11 SCAR=24.3
Pod documented
649  
650 61 ▶ $self->die('init() method takes no arguments') if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 60 61
651 60 ▶ $self->die('init() called a second time')
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_initialized 1 59 60
652 if $self->get_initialized;
653  
654 # It's a fatal error to call init() without defining any
655 # command-line options
656 59 ▶ $self->die('init() called without defining any command-line options')
Branch: 1 branch
BranchTrueFalseTotal
unless $self->get_optspec or 0 0 59 59
Condition50%1/2
$self->get_optspec or 0
l!l
590
MC/DC0%0/1
$self->get_optspec or 0
$self->get_optspec
Truth table50%1/2
A
A= $self->get_optspec
Aresult
11
00
657 unless $self->get_optspec || 0;
658  
659 # Parse command-line options, then read the config file if any.
660 59 my $options = $self->_process_command_line;
661 49 my $config = $self->_read_config_file;
662 49 my $default = $self->get_default_settings;
663  
664 # Save the unprocessed command-line options
665 49 $raw_options_of{ ident $self} = clone($options);
666  
667 # Now, combine the command options, the config-file defaults,
668 # and the wired-in app defaults, in that order of precedence.
669 98 ▶ $options = reduce { merge( $a, $b ) }
Subroutine __ANON__: called CC=1 SCAR=0.0
670 49 ( $options, $config->{default}, $default );
671  
672 # Add a 'verbose' option that evaluates to false if there isn't
673 # already one in $options.
674 49 ▶ $options->{verbose} //= 0;
Condition50%1/2
$options->{"verbose"} //= 0
l!l
049
MC/DC0%0/1
$options->{"verbose"} //= 0
$options->{"verbose"}
Truth table50%1/2
A
A= $options->{"verbose"}
Aresult
11
00
675  
676 # Consolidate the 'v' and 'verbose' options if the default
677 # options are in play here.
678 49 ▶ if ( $self->_get_default_optspec->{$V_OPTSPEC} eq $V_FOR_VERBOSE )
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_get_default_optspec->{$V_OPTSPEC} eq $V_FOR_VERBOSE) 49 0 49
679 {
680 49 ▶ if ( defined $options->{v} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"v"}) 0 49 49
681 {
682 0 $options->{verbose} += delete $options->{v};
683 }
684 }
685  
686 # Save the fully-processed options
687 49 $options_of{ ident $self} = clone($options);
688  
689 # Mark the object as initialized
690 49 $initialized_of{ ident $self} = 1;
691  
692 #
693 # Automatically processed options:
694 #
695  
696 # Print the version information, if requested
697 49 ▶ $self->print_version if $options->{version};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"version"} 2 47 49
698  
699 # Print the POD manpage from the script, if requested
700 47 ▶ $self->print_manpage if $options->{manpage};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"manpage"} 2 45 47
701  
702 # Write back the config if requested
703 45 ▶ $self->write_rcfile() if $options->{'write-rcfile'};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"write-rcfile"} 5 40 45
704  
705 40 return;
706 }
707  
708 sub _process_command_line
709 {
710 59 ▶ my $self = shift;
Subroutine _process_command_line: called CC=14 SCAR=26.4
711 59 my $optspec = $self->get_optspec;
712 59 my %options;
713  
714 # Parse the command line and die if anything is wrong.
715 59 my $opts_ok = GetOptions( \%options, keys %{$optspec} );
716  
717 59 ▶ if ( $options{help} )
Branch: 2 branches
BranchTrueFalseTotal
if ($options{'help'}) { } 5 54 59
elsif (not $opts_ok) { } 4 50 54
718 {
719 5 print $self->_usage_message();
720 5 exit 0;
721 }
722 elsif ( !$opts_ok )
723 {
724 4 $self->die_usage();
725 }
726  
727 # Treat array and hash options as CSV records, so we can
728 # cope with quoting and values containing commas.
729 50 my $csv = Text::CSV->new( { allow_loose_quotes => 1 } );
730  
731 # Further process the array and hash options
732 50 for my $option ( keys %options )
733 {
734 26 ▶ if ( ref $options{$option} eq 'ARRAY' )
Branch: 2 branches
BranchTrueFalseTotal
if (ref $options{$option} eq 'ARRAY') { } 2 24 26
elsif (ref $options{$option} eq 'HASH') { } 2 22 24
735 {
736 2 my @values;
737 2 for my $value ( @{ $options{$option} } )
738 {
739 5 ▶ $csv->parse($value)
Branch: 1 branch
BranchTrueFalseTotal
$csv->parse($value) or $self->die_usage(qq[Can't parse --$option option "$value": ] . $csv->error_diag) 1 4 5
740 or $self->die_usage(
741 "Can't parse --$option option \"$value\": "
742 . $csv->error_diag );
743 4 push @values, $csv->fields;
744 }
745  
746 1 $options{$option} = \@values;
747 }
748 elsif ( ref $options{$option} eq 'HASH' )
749 {
750 2 my $hash = $options{$option};
751 2 for my $key ( keys %{$hash} )
752 {
753 # Extract each value and tech for embedded name/value
754 # pairs. We only go one level deep.
755 4 my $value = $hash->{$key};
756 4 ▶ $csv->parse($value)
Branch: 1 branch
BranchTrueFalseTotal
$csv->parse($value) or $self->die_usage(qq[Can't parse --$option option "$value": ] . $csv->error_diag) 0 4 4
757 or $self->die_usage(
758 "Can't parse --$option option \"$value\": "
759 . $csv->error_diag );
760  
761 # If there's only one field, nothing to do
762 4 ▶ next if ( $csv->fields == 1 );
Branch: 1 branch
BranchTrueFalseTotal
if $csv->fields == 1 3 1 4
763  
764 # Pick off the first value
765 1 my @values = $csv->fields;
766 1 $hash->{$key} = shift @values;
767  
768 # Now parse the rest
769 1 for my $value (@values)
770 {
771 3 my ( $k, $v ) = $value =~ m/^ ([^=]+) = (.*) $/xmsg;
772  
773 # Check for collision
774 carp "Redefined option value: $k"
775 3 ▶ if defined $hash->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if defined $hash->{$k} 0 3 3
776  
777 # Set the value
778 3 $hash->{$k} = $v;
779 }
780 }
781 }
782 }
783  
784 # Process the rcfile option immediately, to override any settings
785 # hard-wired in the app, as well as this module's defaults. If the
786 # rcfile has already been set to a false value, however, then this
787 # option is disallowed.
788 49 ▶ $self->set_rcfile( $options{rcfile} ) if defined $options{rcfile};
Branch: 1 branch
BranchTrueFalseTotal
if defined $options{"rcfile"} 5 44 49
789  
790 # That's it!
791 49 return \%options;
792 }
793  
794 sub _read_config_file
795 {
796 49 ▶ my $self = shift;
Subroutine _read_config_file: called CC=11 SCAR=24.5
797 49 my $types = $self->_option_data_types;
798 49 ▶ my $rcfile = $self->get_rcfile || '';
Condition100%2/2
$self->get_rcfile || ''
l!l
454
MC/DC100%1/1
$self->get_rcfile || ''
$self->get_rcfile
Truth table100%2/2
A
A= $self->get_rcfile
Aresult
11
00
799 49 my $options = {
800 files => [$rcfile],
801 use_ext => 0,
802 force_plugins => [ qw{
803 Config::Any::INI Config::Any::XML Config::Any::YAML
804 Config::Any::JSON Config::Any::Perl
805 }
806 ],
807 };
808  
809 49 my $raw_config;
810  
811 # Attempt to parse the file, if any
812 49 ▶ if ( $rcfile && -r $rcfile )
Branch: 1 branch
BranchTrueFalseTotal
if ($rcfile and -r $rcfile) { } 26 23 49
Condition100%3/3
$rcfile and -r $rcfile
!ll&&!rl&&r
41926
MC/DC100%2/2
$rcfile and -r $rcfile
$rcfile -r $rcfile
Truth table100%3/3
A and B
A= $rcfileB= -r $rcfile
ABresult
0X0
100
111
813 {
814  
815 # Defend against badly configured parsers. I'm looking
816 # at YOU, XML::SAX!
817 local $SIG{__WARN__} = sub {
818 18 ▶ my @args = @_;
Subroutine __ANON__: called CC=5 SCAR=20.9
819  
820 18 for my $arg (@args)
821 {
822 18 ▶ next if ref $arg;
Branch: 1 branch
BranchTrueFalseTotal
if ref $arg 0 18 18
823 18 ▶ return if $arg =~ /Unable to recognise encoding/ms;
Branch: 1 branch
BranchTrueFalseTotal
if $arg =~ /Unable to recognise encoding/ms 18 0 18
824 0 ▶ return if $arg =~ /ParserDetails[.]ini/xms;
Branch: 1 branch
BranchTrueFalseTotal
if $arg =~ /ParserDetails[.]ini/msx 0 0 0
825 }
826  
827 0 CORE::warn(@args);
828 26 };
829  
830 # OK, NOW load the files.
831 26 my $files = Config::Any->load_files($options);
832 26 ▶ $files = shift @{$files} || {};
Condition50%1/2
shift @{$files;} || {}
l!l
260
MC/DC0%0/1
shift @{$files;} || {}
shift @{$files;}
Truth table50%1/2
A
A= shift @{$files;}
Aresult
11
00
833 26 ▶ $raw_config = $files->{$rcfile} || {};
Condition50%1/2
$files->{$rcfile} || {}
l!l
260
MC/DC0%0/1
$files->{$rcfile} || {}
$files->{$rcfile}
Truth table50%1/2
A
A= $files->{$rcfile}
Aresult
11
00
834 }
835 else
836 {
837 23 $raw_config = {};
838 }
839  
840 # Initialize an empty config
841 49 my $config = { default => {} };
842  
843 # Copy in the default section, if there is one.
844 49 ▶ if ( defined $raw_config->{default} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $raw_config->{"default"}) 20 29 49
845 {
846 20 ▶ if ( ref $raw_config->{default} ne 'HASH' )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $raw_config->{'default'} ne 'HASH') { } 0 20 20
847 {
848 0 $self->die('Config file\'s "default" setting isn\'t a hash!');
849 }
850 else
851 {
852 20 $config->{default} = delete $raw_config->{default};
853 }
854 }
855  
856 # Now parse strings if they're supposed to be hashes or arrays.
857 # This is basically a fix for file formats like INI, that can't
858 # encode data structures.
859  
860 # Step through the config, moving any scalars we see into the
861 # default section.
862 49 for my $key ( keys %{$raw_config} )
863 {
864  
865 # We expect a hash, with a "default" section, but if there
866 # isn't one, or there are naked options, then we treat them
867 # as defaults.
868 25 ▶ if ( not ref $raw_config->{$key} )
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $raw_config->{$key}) { } 8 17 25
869 {
870 8 $config->{default}{$key} = delete $raw_config->{$key};
871 8 next;
872 }
873 else
874 {
875 17 $config->{$key} = delete $raw_config->{$key};
876 }
877 }
878  
879 # Now step through the default section, turning scalars into
880 # arrays and hashes as necessary.
881 49 for my $option ( keys %{ $config->{default} } )
882 {
883 123 my $value = $config->{default}{$option};
884 123 $value = $self->_parse_setting( $value, $option, $types );
885  
886 123 $config->{default}{$option} = $value;
887 }
888  
889 # Save the cleaned-up config for reference
890 49 $config_of{ ident $self} = $config;
891  
892 49 return $config;
893 }
894  
895 # Convert string values into an arrayref or hashref as needed
896 sub _parse_setting
897 {
898 123 ▶ my ( $self, $value, $option, $types ) = @_;
Subroutine _parse_setting: called CC=13 SCAR=26.2
899  
900 # If the data is the right type, or we have no spec, nothing to do.
901 123 ▶ my $type = $types->{$option} || 'NONE';
Condition100%2/2
$types->{$option} || 'NONE'
l!l
7746
MC/DC100%1/1
$types->{$option} || 'NONE'
$types->{$option}
Truth table100%2/2
A
A= $types->{$option}
Aresult
11
00
902 123 ▶ return $value if ref $value eq $type or $type eq 'NONE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq $type or $type eq "NONE" 80 43 123
Condition100%3/3
ref $value eq $type or $type eq "NONE"
l!l&&r!l&&!r
344643
MC/DC100%2/2
ref $value eq $type or $type eq "NONE"
ref $value eq $type $type eq "NONE"
Truth table100%3/3
A or B
A= ref $value eq $typeB= $type eq "NONE"
ABresult
1X1
011
000
903  
904 # All other data types we support are scalars.
905 43 ▶ $self->die("Bad data type for \"$option\" option in config file.")
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 0 43 43
906 if ref $value;
907  
908 # Boolean or flags are converted to boolean. Booleans are just
909 # negatable flags.
910 43 ▶ if ( $type eq 'BOOLEAN' or $type eq 'FLAG' )
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "BOOLEAN" or $type eq "FLAG") 35 8 43
Condition100%3/3
$type eq "BOOLEAN" or $type eq "FLAG"
l!l&&r!l&&!r
11248
MC/DC100%2/2
$type eq "BOOLEAN" or $type eq "FLAG"
$type eq "BOOLEAN" $type eq "FLAG"
Truth table100%3/3
A or B
A= $type eq "BOOLEAN"B= $type eq "FLAG"
ABresult
1X1
011
000
911 {
912 35 ▶ return $value // 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$value // 0 ? : 18 17 35
Condition50%1/2
$value // 0
l!l
350
MC/DC0%0/1
$value // 0
$value
Truth table50%1/2
A
A= $value
Aresult
11
00
913 }
914  
915 # Counters are integer-valued
916 8 ▶ if ( $type eq 'COUNT' )
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "COUNT") 0 8 8
917 {
918  
919 # All other data types we support are scalars.
920 0 ▶ $self->die(
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /^ \d+ $/msx 0 0 0
921 "Invalid value \"$value\" for option \"$option\" in config file.")
922 if $value !~ /^ \d+ $/xms;
923  
924 0 return $value;
925 }
926  
927 # The only fix we implement is to parse CSV and primitive name/value
928 # pairs.
929 8 my $csv = Text::CSV->new( {
930 allow_loose_quotes => 1,
931 allow_whitespace => 1,
932 } );
933  
934 # Start by turning the string to an array
935 8 $csv->parse($value);
936 8 $value = [ $csv->fields ];
937 8 ▶ return $value if $type eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "ARRAY" 3 5 8
938  
939 5 my %hash;
940  
941 # Now it has to be a hash, so we need to split the values
942 # on equal signs or colons.
943  
944 5 for ( @{$value} )
945 {
946 9 my ( $key, $val ) = m/^([^=:]+)(?:\s*[:=]\s*)?(.*)$/xms;
947 9 $hash{$key} = $val;
948 }
949  
950 5 return \%hash;
951 }
952  
953 # Constructor for this object.
954 sub BUILD
955 {
956 67 ▶ my ( $self, undef, $argref ) = @_;
Subroutine BUILD: called CC=7 SCAR=19.5
Pod documented
957  
958 # Shorthand: { options => \%options } can be
959 # abbreviated \%options.
960 67 ▶ if ( not exists $argref->{options} )
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $argref->{"options"}) 30 37 67
961 {
962 30 $argref = { options => $argref };
963 }
964 67 ▶ $self->set_optspec( $argref->{options} || {} );
Condition100%2/2
$argref->{'options'} || {}
l!l
652
MC/DC100%1/1
$argref->{'options'} || {}
$argref->{'options'}
Truth table100%2/2
A
A= $argref->{'options'}
Aresult
11
00
965  
966 # Caller can specify default settings for all options.
967 $self->set_default_settings( $argref->{default_settings} )
968 62 ▶ if exists $argref->{default_settings};
Branch: 1 branch
BranchTrueFalseTotal
if exists $argref->{"default_settings"} 1 61 62
969  
970 ## no critic ( ValuesAndExpressions::ProhibitNoisyQuotes )
971  
972 # Setting rcfile to undef in the constructor disables rcfile reading
973 # for the script.
974 $self->set_rcfile(
975 exists $argref->{rcfile}
976 ? $argref->{rcfile}
977 62 ▶ : File::HomeDir->my_home . '/.' . basename($PROGRAM_NAME) . 'rc'
Branch: 1 branch
BranchTrueFalseTotal
exists $argref->{'rcfile'} ? : 29 33 62
978 );
979  
980 # Caller can forbid writing of rcfiles by setting
981 # the write_rcfile option to undef, or can supply
982 # a coderef to do the writing.
983 62 ▶ if ( exists $argref->{write_rcfile} )
Branch: 1 branch
BranchTrueFalseTotal
if (exists $argref->{"write_rcfile"}) 2 60 62
984 {
985 2 $self->set_write_rcfile( $argref->{write_rcfile} );
986 }
987  
988 # Set an optional usage message for the script.
989 $self->set_usage(
990 exists $argref->{usage}
991 ? $argref->{usage}
992 62 ▶ : '[options]'
Branch: 1 branch
BranchTrueFalseTotal
exists $argref->{'usage'} ? : 1 61 62
993 );
994  
995 62 return;
996 }
997  
998 # Destructor. Nothing much to do, but without it we get
999 # a warning about CLI::Startup::DEMOLISH only being used
1000 # once by Class::Std.
1001 sub DEMOLISH
1002 ▶{
Subroutine DEMOLISH: called CC=1 SCAR=0.0
Pod documented
1003 }
1004  
1005 # Prints out the POD contained in the script file, if any.
1006 sub print_manpage
1007 {
1008 2 ▶ my $self = shift;
Subroutine print_manpage: called CC=2 SCAR=6.9
Pod documented
1009 2 my $parser = Pod::Text->new;
1010  
1011 # Print SOMETHING...
1012 2 $parser->output_fh(*STDOUT);
1013 2 $parser->parse_file($PROGRAM_NAME);
1014 2 ▶ print $self->_usage_message() unless $parser->content_seen;
Branch: 1 branch
BranchTrueFalseTotal
unless $parser->content_seen 1 1 2
1015  
1016 2 exit 0;
1017 }
1018  
1019 # Prints the version of the script.
1020 sub print_version
1021 {
1022 2 ▶ my $version = $::VERSION || 'UNKNOWN';
Subroutine print_version: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$main::VERSION || 'UNKNOWN'
l!l
11
MC/DC100%1/1
$main::VERSION || 'UNKNOWN'
$main::VERSION
Truth table100%2/2
A
A= $main::VERSION
Aresult
11
00
1023 2 my $name = basename($PROGRAM_NAME);
1024  
1025 2 print { \*STDERR } <<"EOF";
1026 This is $name, version $version
1027 path: $PROGRAM_NAME
1028 perl: $PERL_VERSION
1029 EOF
1030 2 exit 0;
1031 }
1032  
1033 # Print a nicely-formatted warning message.
1034 sub warn ## no critic ( Subroutines::RequireFinalReturn )
1035 {
1036 1 ▶ my ( undef, $msg ) = @_;
Subroutine warn: called CC=1 SCAR=0.0
Pod documented
1037  
1038 1 my $name = basename($PROGRAM_NAME);
1039 1 CORE::warn "$name: WARNING: $msg\n";
1040 }
1041  
1042 # Writes the config file in the specified format.
1043 sub write_rcfile
1044 {
1045 7 ▶ my $self = shift;
Subroutine write_rcfile: called CC=5 SCAR=16.1
Pod documented
1046 7 ▶ my $file = shift || $self->get_rcfile;
Condition66%2/3
shift() || $self->get_rcfile
l!l&&r!l&&!r
043
MC/DC50%1/2
shift() || $self->get_rcfile
shift() $self->get_rcfile
Truth table66%2/3
A || B
A= shift()B= $self->get_rcfile
ABresult
1X1
011
000
1047  
1048 # It's a fatal error to call write_rcfile() before init()
1049 7 ▶ $self->die('write_rcfile() called before init()')
Branch: 1 branch
BranchTrueFalseTotal
unless $self->get_initialized 1 6 7
1050 unless $self->get_initialized;
1051  
1052 # If there's no file to write, abort.
1053 6 ▶ $self->die('can\'t write rcfile: no file specified') unless $file;
Branch: 1 branch
BranchTrueFalseTotal
unless $file 3 3 6
1054  
1055 # Check whether a writer has been set
1056 3 my $writer = $self->_choose_rcfile_writer;
1057  
1058 # If there's a writer, call it.
1059 3 ▶ if ( ref $writer eq 'CODE' )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $writer eq 'CODE') { } 2 1 3
1060 {
1061 2 $writer->( $self, $file );
1062 }
1063 else
1064 {
1065 1 $self->die('write_rcfile() disabled, but called anyway');
1066 }
1067  
1068 2 exit 0;
1069 }
1070  
1071 # Returns a hashref that looks like a config file's contents, with
1072 # the defaults overwritten by the options used for the current
1073 # invocation of the script.
1074 sub get_options_as_defaults
1075 {
1076 6 ▶ my $self = shift;
Subroutine get_options_as_defaults: called CC=2 SCAR=6.9
Pod documented
1077  
1078 # Collate the settings for writing
1079 6 my $settings = $self->get_config;
1080 6 my $options = $self->get_raw_options;
1081 6 my $default = $self->get_default_settings;
1082 6 my $default_aliases
1083 = $self->_option_aliases( $self->_get_default_optspec );
1084  
1085 # Copy the current options back into the "default" group
1086 12 ▶ $settings->{default} = reduce { merge( $a, $b ) }
Subroutine __ANON__: called CC=1 SCAR=0.0
1087 6 ( $options, $settings->{default}, $default );
1088  
1089 # Delete settings for the automatically-generated options; none of them
1090 # belong in the rcfile.
1091 6 for my $option ( keys %{$default_aliases} )
1092 {
1093 66 delete $settings->{default}{$option};
1094 }
1095  
1096 6 return $settings;
1097 }
1098  
1099 # Choose the correct built-in config writer based on the current
1100 # value of --rcfile-format.
1101 sub _choose_rcfile_writer
1102 {
1103 3 ▶ my $self = shift;
Subroutine _choose_rcfile_writer: called CC=5 SCAR=16.4
1104  
1105 # If a writer was specified by the user, we don't have to think.
1106 # If it evaluates to false, or isn't a coderef, write_rcfile()
1107 # will abort with an error.
1108 3 ▶ if ( exists $write_rcfile_of{ ident $self} )
Branch: 1 branch
BranchTrueFalseTotal
if (exists $write_rcfile_of{builtin::refaddr($self)}) 2 1 3
1109 {
1110 2 return $write_rcfile_of{ ident $self};
1111 }
1112  
1113 1 my $writer = {
1114 INI => \&_write_rcfile_ini,
1115 XML => \&_write_rcfile_xml,
1116 JSON => \&_write_rcfile_json,
1117 YAML => \&_write_rcfile_yaml,
1118 PERL => \&_write_rcfile_perl,
1119 };
1120  
1121 # Decide what the default should be: INI falling back on Perl
1122 1 ▶ eval 'use Config::INI::Writer';
Subroutine BEGIN: called CC=1 SCAR=0.0
1123 1 ▶ my $default = $EVAL_ERROR ? 'PERL' : 'INI';
Branch: 1 branch
BranchTrueFalseTotal
$CLI::Startup::EVAL_ERROR ? : 0 1 1
1124  
1125 # Check whether a file format was specified; if not, use the default.
1126 1 my $options = $self->get_options;
1127 1 ▶ my $format = uc( $options->{'rcfile-format'} || $default );
Condition33%1/3
$options->{'rcfile-format'} || $default
l!l&&r!l&&!r
100
MC/DC0%0/2
$options->{'rcfile-format'} || $default
$options->{'rcfile-format'} $default
Truth table33%1/3
A || B
A= $options->{'rcfile-format'}B= $default
ABresult
1X1
011
000
1128  
1129 $self->die("Unknown --rcfile-format option specified: \"$format\"")
1130 1 ▶ unless defined $writer->{$format};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $writer->{$format} 0 1 1
1131  
1132 1 return $writer->{$format};
1133 }
1134  
1135 # Write the current settings to an INI file. Serialize hash and array
1136 # values for known command-line options. Leave everything else alone.
1137 sub _write_rcfile_ini
1138 {
1139 1 ▶ my ( $self, $file ) = @_;
Subroutine _write_rcfile_ini: called CC=10 SCAR=23.6
1140  
1141 # Installing the INI module is optional
1142 1 ▶ eval 'use Config::INI::Writer';
Subroutine BEGIN: called CC=1 SCAR=0.0
1143 1 ▶ $self->die('Can\'t write rcfile: Config::INI::Writer is not installed.')
Branch: 1 branch
BranchTrueFalseTotal
if $CLI::Startup::EVAL_ERROR 0 1 1
1144 if $EVAL_ERROR;
1145  
1146 # Get out current settings, and then fix the formats of array and
1147 # hash values.
1148 1 my $settings = $self->get_options_as_defaults;
1149 1 my $types = $self->_option_data_types;
1150  
1151 1 for my $setting ( keys %{ $settings->{default} } )
1152 {
1153 5 my $value = $settings->{default}{$setting};
1154  
1155 # String data doesn't need anything done to it.
1156 5 ▶ next unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 3 2 5
1157  
1158 # We produce compliant CSV; no options needed.
1159 2 my $csv = Text::CSV->new( {} );
1160  
1161 # Serialize the two structures we know about.
1162 2 ▶ if ( ref $value eq 'ARRAY' )
Branch: 2 branches
BranchTrueFalseTotal
if (ref $value eq 'ARRAY') { } 1 1 2
elsif (ref $value eq 'HASH') { } 1 0 1
1163 {
1164  
1165 # Just stringify. Deep structure will be silently lost.
1166 1 $csv->combine( map {"$_"} @{$value} );
1167 1 $value = $csv->string;
1168  
1169 # Warn if the type is wrong, but proceed anyway.
1170 $self->warn("Option \"$setting\" is unexpectedly an array")
1171 1 ▶ if ( $types->{$setting} || '' ) ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ($types->{$setting} || "") ne "ARRAY" 0 1 1
Condition50%1/2
$types->{$setting} || ''
l!l
10
MC/DC0%0/1
$types->{$setting} || ''
$types->{$setting}
Truth table50%1/2
A
A= $types->{$setting}
Aresult
11
00
1172 }
1173 elsif ( ref $value eq 'HASH' )
1174 {
1175  
1176 # Just stringify. Deep structure will be silently lost.
1177 1 $csv->combine( map {"$_=$value->{$_}"} keys %{$value} );
1178 1 $value = $csv->string;
1179  
1180 # Warn if the type is wrong, but proceed anyway.
1181 $self->warn("Option \"$setting\" is unexpectedly a hash")
1182 1 ▶ if ( $types->{$setting} || '' ) ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ($types->{$setting} || "") ne "HASH" 0 1 1
Condition50%1/2
$types->{$setting} || ''
l!l
10
MC/DC0%0/1
$types->{$setting} || ''
$types->{$setting}
Truth table50%1/2
A
A= $types->{$setting}
Aresult
11
00
1183 }
1184 else
1185 {
1186 # Just stringify. We know this is wrong, but the user
1187 # shouldn't be using an INI file for structured data.
1188 0 $value = "$value";
1189  
1190 # Don't know what to do; can't do anything about it.
1191 0 $self->warn("Option \"$setting\" will be corrupt in config file");
1192 }
1193  
1194 2 $settings->{default}{$setting} = $value;
1195 }
1196  
1197 # Write settings to the file.
1198 1 Config::INI::Writer->write_file( $settings, $file );
1199  
1200 1 return 1;
1201 }
1202  
1203 # Write the current settings to an XML file.
1204 sub _write_rcfile_xml
1205 {
1206 1 ▶ my ( $self, $file ) = @_;
Subroutine _write_rcfile_xml: called CC=5 SCAR=16.6
1207  
1208 # Installing a XML module is optional.
1209 1 ▶ eval 'use XML::Simple';
Subroutine BEGIN: called CC=1 SCAR=0.0
1210 1 ▶ $self->die('Can\'t write rcfile: XML::Simple is not installed.')
Branch: 1 branch
BranchTrueFalseTotal
if $CLI::Startup::EVAL_ERROR 0 1 1
1211 if $EVAL_ERROR;
1212  
1213 1 ▶ open my $RCFILE, '>', $file
Branch: 1 branch
BranchTrueFalseTotal
open my $RCFILE, ">", $file or $self->die(qq[Couldn't open file "$file": $CLI::Startup::OS_ERROR]) 0 1 1
1214 or $self->die("Couldn't open file \"$file\": $OS_ERROR");
1215 1 ▶ print {$RCFILE} XMLout( $self->get_options_as_defaults )
Branch: 1 branch
BranchTrueFalseTotal
print {$RCFILE;} XMLout($self->get_options_as_defaults) or $self->die(qq[Couldn't write to file "$file": $CLI::Startup::OS_ERROR]) 0 1 1
1216 or $self->die("Couldn't write to file \"$file\": $OS_ERROR");
1217 1 ▶ close $RCFILE
Branch: 1 branch
BranchTrueFalseTotal
close $RCFILE or $self->die(qq[Couldn't close file "$file": $CLI::Startup::OS_ERROR]) 0 1 1
1218 or $self->die("Couldn't close file \"$file\": $OS_ERROR");
1219  
1220 1 return 1;
1221 }
1222  
1223 # Write the current settings to a JSON file.
1224 sub _write_rcfile_json
1225 {
1226 1 ▶ my ( $self, $file ) = @_;
Subroutine _write_rcfile_json: called CC=5 SCAR=16.5
1227  
1228 # Installing a JSON module is optional.
1229 1 ▶ eval 'use JSON::MaybeXS';
Subroutine BEGIN: called CC=1 SCAR=0.0
1230 1 ▶ $self->die('Can\'t write rcfile: JSON::MaybeXS is not installed.')
Branch: 1 branch
BranchTrueFalseTotal
if $CLI::Startup::EVAL_ERROR 0 1 1
1231 if $EVAL_ERROR;
1232  
1233 1 my $json = JSON::MaybeXS->new();
1234  
1235 1 ▶ open my $RCFILE, '>', $file
Branch: 1 branch
BranchTrueFalseTotal
open my $RCFILE, ">", $file or $self->die(qq[Couldn't open file "$file": $CLI::Startup::OS_ERROR]) 0 1 1
1236 or $self->die("Couldn't open file \"$file\": $OS_ERROR");
1237 1 ▶ print {$RCFILE} $json->encode( $self->get_options_as_defaults )
Branch: 1 branch
BranchTrueFalseTotal
print {$RCFILE;} $json->encode($self->get_options_as_defaults) or $self->die(qq[Couldn't write to file "$file": $CLI::Startup::OS_ERROR]) 0 1 1
1238 or $self->die("Couldn't write to file \"$file\": $OS_ERROR");
1239 1 ▶ close $RCFILE
Branch: 1 branch
BranchTrueFalseTotal
close $RCFILE or $self->die(qq[Couldn't close file "$file": $CLI::Startup::OS_ERROR]) 0 1 1
1240 or $self->die("Couldn't close file \"$file\": $OS_ERROR");
1241  
1242 1 return 1;
1243 }
1244  
1245 # Write the current settings to a YAML file.
1246 sub _write_rcfile_yaml
1247 {
1248 1 ▶ my ( $self, $file ) = @_;
Subroutine _write_rcfile_yaml: called CC=2 SCAR=7.0
1249  
1250 # Installing a YAML module is optional.
1251 1 ▶ eval 'use YAML::Any qw{DumpFile}';
Subroutine BEGIN: called CC=1 SCAR=0.0
1252 1 ▶ $self->die('Can\'t write rcfile: YAML::Any is not installed.')
Branch: 1 branch
BranchTrueFalseTotal
if $CLI::Startup::EVAL_ERROR 0 1 1
1253 if $EVAL_ERROR;
1254  
1255 1 DumpFile( $file, $self->get_options_as_defaults );
1256  
1257 1 return 1;
1258 }
1259  
1260 # Write the current settings to a Perl file.
1261 sub _write_rcfile_perl
1262 {
1263 2 ▶ my ( $self, $file ) = @_;
Subroutine _write_rcfile_perl: called CC=4 SCAR=14.3
1264  
1265 2 local $Data::Dumper::Terse = 1;
1266  
1267 2 ▶ open my $RCFILE, '>', $file
Branch: 1 branch
BranchTrueFalseTotal
open my $RCFILE, ">", $file or $self->die(qq[Couldn't open file "$file": $CLI::Startup::OS_ERROR]) 0 2 2
1268 or $self->die("Couldn't open file \"$file\": $OS_ERROR");
1269 2 ▶ print {$RCFILE} Dumper( $self->get_options_as_defaults )
Branch: 1 branch
BranchTrueFalseTotal
print {$RCFILE;} Dumper($self->get_options_as_defaults) or $self->die(qq[Couldn't write to file "$file": $CLI::Startup::OS_ERROR]) 0 2 2
1270 or $self->die("Couldn't write to file \"$file\": $OS_ERROR");
1271 2 ▶ close $RCFILE
Branch: 1 branch
BranchTrueFalseTotal
close $RCFILE or $self->die(qq[Couldn't close file "$file": $CLI::Startup::OS_ERROR]) 0 2 2
1272 or $self->die("Couldn't close file \"$file\": $OS_ERROR");
1273  
1274 2 return 1;
1275 }
1276  
1277 10 1; # End of CLI::Startup
1278  
1279 __END__
↑ Summary Build »