blib/lib/Getopt/Tree.pm

filter: Statementstmt 75.6% 224 / 296 Branchbran 60.0% 96 / 160 Conditioncond 58.3% 28 / 48 MC/DCmcdc 27.5% 8 / 29 Subroutinesub 100% 18 / 18 Podpod 28.5% 2 / 7 totaltotal 67.3% 376 / 558 CC 111 SCAR 38.2
CC
111
Cov
69%
parse_command_line
103.9
check_parameter
49.1
calc_param_value
33.4
CRAP 45.5
↑ Summary
1 package Getopt::Tree;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Text::Wrap;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Getopt::Long qw( :config no_auto_abbrev no_getopt_compat no_permute require_order no_ignore_case_always );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶ use Exporter ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 our ( @ISA, @EXPORT );
11  
12 1 @ISA = qw(Exporter);
13 1 @EXPORT = qw/ parse_command_line print_usage /;
14 }
15  
16 1 ▶use vars qw( $VERSION );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 $VERSION = '1.12';
18  
19 1 ▶use constant ABBR_PARAM_SEPARATOR => ', ';
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use constant ABBR_PARAM_SEPARATOR_LENGTH => length( ABBR_PARAM_SEPARATOR );
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use constant DEPTH_STR => ' ';
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 1 our $USAGE_HEADER = '';
24 1 our $USAGE_FOOTER = '';
25 1 our $SWITCH_PREFIX_STR = '-';
26  
27 =head1 NAME
28  
29 Getopt::Tree - Get tree-like options (like the route command).
30  
31 =head1 ABSTRACT
32  
33 Getopt::Tree is a module to help parse and validate command line parameters
34 built on top of Getopt::Long. Getopt::Tree allows the developer to specify an
35 array parameters, including the name, abbreviation, type, description, and any
36 parameters that are applicable to and/or dependent on that parameter.
37  
38 =head1 EXAMPLE
39  
40 =head2 Simple "route" example
41  
42 # Accept the commands add, remove, print, and their associated dependent
43 # options.
44 my $p = [
45 {
46 name => 'add',
47 exists => 1,
48 descr => 'Add a new route',
49 params => [
50 {
51 name => 'gateway',
52 abbr => 'gw',
53 descr => 'Remote gateway for this network',
54 },
55 {
56 name => 'network',
57 abbr => 'net',
58 descr => 'Network address to add route for',
59 },
60 {
61 name => 'subnet',
62 abbr => 'mask',
63 descr => 'Subnet mask for the given network',
64 },
65 ],
66 },
67 {
68 name => 'remove',
69 abbr => 'delete',
70 exists => 1,
71 descr => 'Delete a route',
72 params => [
73 {
74 name => 'network',
75 abbr => 'net',
76 descr => 'Network address to delete',
77 },
78 {
79 name => 'subnet',
80 abbr => 'mask',
81 descr => 'Subnet mask for the given network',
82 },
83 ],
84 },
85 {
86 name => 'print',
87 exists => 1,
88 descr => 'Display routing table',
89 },
90 ];
91
92 =head2 Complex example
93  
94 my $p = [
95 # Required global parameter.
96 { name => 'user', leaf => 1, eval => sub { my ( $p ) = @_; return 1 if $p =~ /^[a-z]+$/i; },
97 # Optional global parameter.
98 {
99 name => 'no-cache',
100 abbr => 'nc',
101 exists => 1,
102 optional => 1,
103 descr => 'Don\'t cache your credentials in /tmp/.'
104 },
105 # Start of a branch. If one or more branches exist, at least one must be
106 # followed.
107 {
108 name => 'search',
109 abbr => 's',
110 descr => 'Search for ticket, list tickets in queue, or print contents of a ticket.',
111 params => [
112 {
113 name => 'ticket', # field name
114 abbr => 't', # alternate name
115 re => TICKET_REGEX, # field must match re
116 descr => 'The ticket number to search for.', # auto-doc
117 params => [
118 { # fields that are allowed if this field is set
119 name => 'show-all-worklog-fields',
120 exists => 1, # I just want a 1 or a 0 if set
121 optional => 1,
122 descr => 'Show all worklog fields.'
123 },
124 {
125 name => 'show-all-fields',
126 multi => 1, # can be set multiple times, returns arrayref
127 exists => 1, # unless exists is set too, then you just get the count
128 descr => 'Show all ticket fields.'
129 },
130 ],
131 },
132 ],
133 }
134 ];
135 my ( $operation, $params ) = parse_command_line( $p );
136 if ( !$operation ) { print_usage( $p ); die; }
137 print "Performing $operation!\n"
138  
139 =head1 USAGE
140  
141 Two functions are exported by default: L<parse_command_line> and
142 L<print_usage>.
143  
144 =head2 Functions
145  
146 =head3 parse_command_line
147  
148 Parses the command line (@ARGV) based on the specified data structure.
149  
150 Accepts two parameters. The first is a required array reference describing the
151 possible command line parameters. It returns three values, the "top level"
152 option, a hashref of the other specified options, and an arrayref of any
153 remaining unparsed options (similar to Getopt::Long).
154  
155 The second parameter is an optional array reference or string from which the
156 parameters are to be read, rather than reading them from @ARGV. If a string is
157 passed, it will be converted to an array via C<Text::ParseWords::shellwords>.
158  
159 If the command line was unable to be parsed (the passed data structure was
160 inconsistent, etc), parse_command_line will die with an appropriate error
161 message. If the command line was invalid (the user entered something that did
162 not meet the given requirements, etc) a warning will be printed and undef will
163 be returned.
164  
165 =head3 print_usage
166  
167 Prints usage information based on the specified data structure.
168  
169 Takes two parameters, the first is a required array reference describing the
170 possible command line parameters, and the second is an optional file handle to
171 which the usage information will be printed. Alternately, in place of a
172 filehandle, a hashref of options can be passed. Valid options are:
173  
174 =over 4
175  
176 =item fh
177  
178 The filehandle to print to. If not set, no output is printed.
179  
180 =item return
181  
182 A boolean value that determines whether or not the usage should be returned as
183 a string.
184  
185 =item wrap_at
186  
187 Number of characters to wrap the output at. Will be auto-detected from
188 $ENV{COLUMNS} if not set, defaults to 80 if auto-detection fails.
189  
190 =item hide_top_line
191  
192 Hides the top line of output which contains the program name how to pass
193 switches.
194  
195 =back
196  
197 Usage information is generated mostly from the "descr" fields in the data
198 structure, indentation is based on parameter dependence, parameters that accept
199 values are noted, and optional parameters are presented inside of brackets.
200  
201 =head2 Configuration
202  
203 The "expected command line configuration data structure" will be referred to as
204 "the data structure" because I can't think of a better name for it.
205  
206 =head3 Concepts
207  
208 The design is similar to the Unix "route" command, in which a "top level"
209 command (such as "add" or "delete") will have zero or more dependent parameters
210 (such as the "gateway" or "subnet"). Getopt::Tree uses Getopt::Long to actually
211 parse the command line, but adds a layer of logic on top to discover which
212 top level command and dependent options the user specified. Conflicting
213 options, parameter types, and usage document generation are all handled by
214 Getopt::Tree based on the data structure supplied by the developer.
215  
216 Commands are separated into two types, top level and dependent. At least on top
217 level command is required. Once Getopt::Tree identifies the proper top level
218 command, it will look for the dependent commands that apply to the specified
219 top level command. Since each dependent command can also have dependent
220 commands, the process is repeated until no more commands are found.
221  
222 Each set of dependents in the tree is considered a "level", with the top level
223 being the first set of entries in the structure, and each successive level
224 being composed of the dependents of the prior level. Note that a level could
225 simply be described as the distance to the top of a tree, where as a "branch"
226 would be the specific set of dependents for a given command, irrespective of
227 dependents of commands on the same level.
228  
229 =head3 Data Structure
230  
231 The data structure is composed of an array of hashrefs. Each hashref describes
232 a single parameter. Each hashref in the array contains various options
233 describing the parameter. Valid options are as follows:
234  
235 =head4 name
236  
237 Full parameter name. Required. Must not contain the characters "@", "|", or "="
238 and must not conflict with other names or abbreviations in the same branch.
239 This is the name that will be returned, if the parameter is set, by
240 L<parse_command_line>.
241  
242 =head4 abbr
243  
244 Parameter abbreviation. Will be accepted on the command line in place of the
245 proper name, but must obey the same rules as the proper name.
246  
247 =head4 optional
248  
249 Defines whether this parameter is optional. Boolean. Defaults to false, ie, the
250 parameter is required.
251  
252 =head4 exists
253  
254 Defines whether or not the parameter has a value or whether it should simply be
255 checked for existence. Boolean. Defaults to false, ie, the parameter must have
256 a value.
257  
258 =head4 leaf
259  
260 Defines whether or not the parameter should be considered a "leaf" on the
261 current branch or not. A leaf is a required parameter at the current level and
262 has no dependents. Useful to place a required parameter that applies to
263 multiple branches without specifying the required parameter in each branch.
264 Conflicts with "optional" and "params". Defaults to false, ie, this parameter
265 is not a leaf.
266  
267 =head4 params
268  
269 An optional arrayref of hashrefs representing parameters dependent on this
270 parameter. Format is exactly the same as for the primary data structure.
271  
272 =head4 descr
273  
274 Textural description of what the parameter is and does. Used as part of the
275 usage information. If not set, a placeholder is supplied.
276  
277 =head4 multi
278  
279 Defines whether or not this parameter can be specified multiple times or not.
280 Boolean. Defaults to false.
281  
282 =head4 re
283  
284 Defines a regular expression to match values against. The result of the first
285 capture of this expression will be treated as the value in place of the
286 user-specified value. If no capture is found or the match fails, the parameter
287 will be treated as invalid. Conflicts with "exists". If both "re" and "eval"
288 are specified, "re" will be processed first and the result passed to "eval".
289  
290 =head4 eval
291  
292 Defines a subroutine to be called to validate the value passed for this
293 parameter. The returned value from the subroutine will be used in place of the
294 user-specified value. If undef is returned, the parameter is treated as
295 invalid. Conflicts with "exists". If both "re" and "eval" are specified, "re"
296 will be processed first and the result passed to "eval".
297  
298 =head1 VARIABLES
299  
300 =head2 $Getopt::Tree::USAGE_HEADER
301  
302 Text to be printed near the top of the "usage" output.
303  
304 =head2 $Getopt::Tree::USAGE_HEADER
305  
306 Text to be printed at the end of the "usage" output.
307  
308 =head2 $Getopt::Tree::SWITCH_PREFIX_STR
309  
310 Characters to prefix a switch. Defaults to a single hyphen ('-'). Can be set to
311 an empty string to use switchless options (Note: This option is not well
312 tested!).
313  
314 =head1 NOTES
315  
316 You can't have a dependent parameter of the same name as a non-optional
317 parameter higher in the tree. If the parser sees a two instances of the same
318 parameter it will bail, so you have to make sure that there are no identically
319 named parameters in one part of the tree as in another part of the tree that
320 the parser passes through. Example:
321  
322 { name => 'bad' },
323 { name => 'normal', params => [ { name => 'bad' }, { name => 'bad2' } ] }
324 { name => 'normal2', params => [ { name => 'bad2' } ] }
325  
326 Both of the 'bad' entries will collide when the user specifies 'normal', since
327 the parser passes through the top level and the normal->params level. However,
328 bad2 will never collide because the parser will never pass through both levels.
329  
330 Also, identical abbreviations are not checked for or corrected. They will
331 probably cause problems.
332  
333 =cut
334  
335 # Process the name and abbreviations into something Getopt::Long would like.
336 20 ▶sub process_getopt_params {
Subroutine process_getopt_params: called CC=11 SCAR=25.4
Pod undocumented
337 20 my ( $param_array ) = @_;
338 20 my @param_array;
339 my $p_name;
340  
341 20 foreach my $param_ref ( @{$param_array} ) {
342 0 ▶ if ( !$param_ref->{name} ) { die "Parameter lacks a name!"; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($param_ref->{"name"}) 0 43 43
343 0 ▶ if ( $param_ref->{name} =~ /[=|@]/ ) { die "Parameter names should not contain [=|@]!"; }
Branch: 1 branch
BranchTrueFalseTotal
if ($param_ref->{"name"} =~ /[=|\@]/) 0 43 43
344 0 ▶ if ( $param_ref->{name} =~ /^-/ ) { die "Parameter names should not begin with a dash!"; }
Branch: 1 branch
BranchTrueFalseTotal
if ($param_ref->{"name"} =~ /^-/) 0 43 43
345 43 ▶ if ( $param_ref->{abbr} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($param_ref->{'abbr'}) { } 26 17 43
346 0 ▶ if ( $param_ref->{abbr} =~ /[-=|]@/ ) { die "Parameter abbreviations should not contain [=|@]!"; }
Branch: 1 branch
BranchTrueFalseTotal
if ($param_ref->{"abbr"} =~ /[-=|]@/) 0 26 26
347 0 ▶ if ( $param_ref->{abbr} =~ /^-/ ) { die "Parameter abbreviations should not begin with a dash!"; }
Branch: 1 branch
BranchTrueFalseTotal
if ($param_ref->{"abbr"} =~ /^-/) 0 26 26
348 26 $p_name = $param_ref->{name} . '|' . $param_ref->{abbr};
349 } else {
350 17 $p_name = $param_ref->{name};
351 }
352 43 ▶ if ( $param_ref->{multi} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($param_ref->{'multi'}) { } 1 42 43
elsif (not $param_ref->{'exists'}) { } 17 25 42
353 1 $p_name .= '=s@';
354 } elsif ( !$param_ref->{exists} ) {
355 17 $p_name .= '=s';
356 }
357 43 push @param_array, $p_name;
358 43 ▶ if ( $param_ref->{params} ) { push @param_array, process_getopt_params( $param_ref->{params} ); }
Branch: 1 branch
BranchTrueFalseTotal
if ($param_ref->{"params"}) 12 31 43
359 }
360 20 return @param_array;
361 }
362  
363 # Check to see if a given parameter is valid (handles exists, checks against passed regex,
364 # runs associated code blocks, etc).
365 # Returns ( status, value ). Sorry.
366 8 ▶sub calc_param_value {
Subroutine calc_param_value: called CC=12 SCAR=35.1
Pod undocumented
367 8 my ( $top_level, $g_opts ) = @_;
368 8 my $v = $g_opts->{ $top_level->{name} };
369  
370 # If all they want is 'exists', quickly check and return.
371 8 ▶ if ( $top_level->{exists} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"exists"}) 4 4 8
372 4 ▶ if ( $top_level->{multi} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"multi"}) 0 4 4
373 0 ▶ if ( ref $v eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq 'ARRAY') { } 0 0 0
374 0 return ( 1, scalar( @{$v} ) );
375 } else {
376 0 die "Should be an array?";
377 }
378 }
379 4 return ( 1, 1 );
380 }
381  
382 4 ▶ if ( $top_level->{re} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"re"}) 3 1 4
383 3 ▶ if ( $top_level->{multi} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{'multi'}) { } 0 3 3
384 0 my $result = [];
385 0 ▶ if ( ref $v eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq 'ARRAY') { } 0 0 0
386 0 foreach my $entry ( @{$v} ) {
387 0 $entry =~ $top_level->{re};
388 0 ▶ if ( !defined $1 ) { return ( 0, undef ); }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $1) 0 0 0
389 0 push @{$result}, $1;
390 }
391 } else {
392 0 die "Should be an array?";
393 }
394 0 $v = $result;
395 } else {
396 3 $v =~ $top_level->{re};
397 0 ▶ if ( !defined $1 ) { return ( 0, undef ); }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $1) 0 3 3
398 3 $v = $1;
399 }
400 }
401 4 ▶ if ( $top_level->{eval} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"eval"}) 1 3 4
402 1 $v = $top_level->{eval}->( $v, $g_opts );
403 0 ▶ if ( !defined $v ) { return ( 0, undef ); }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v) 0 1 1
404 }
405 4 return ( 1, $v );
406 }
407  
408 # Recursive function to check the user's input against our data structure.
409 14 ▶sub check_parameter {
Subroutine check_parameter: called CC=20 SCAR=38.9
Pod undocumented
410 14 my ( $g_opts, $params ) = @_;
411  
412 14 my @approved_flags;
413 my $this_level;
414 14 my $this_level_is_a_leaf = 1;
415 # This is a bit of a pain, but we have to track existence of leaves
416 # separately from regular parameters. Since we don't recurse into a leaf
417 # like we do a branch, we can't let check_parameter() handle the existence
418 # test for us.
419 14 my %matched_leaves;
420  
421 14 foreach my $top_level ( @{$params} ) {
422 35 ▶ if ( $top_level->{params} && $top_level->{leaf} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"params"} and $top_level->{"leaf"}) 0 35 35
Condition66%2/3
$top_level->{"params"} and $top_level->{"leaf"}
!ll&&!rl&&r
24110
MC/DC0%0/2
$top_level->{"params"} and $top_level->{"leaf"}
$top_level->{"params"} $top_level->{"leaf"}
Truth table66%2/3
A and B
A= $top_level->{"params"}B= $top_level->{"leaf"}
ABresult
0X0
100
111
423 0 die "Invalid settings! You can not specify params and leaf!";
424 }
425 35 ▶ if ( !$top_level->{optional} && !$top_level->{leaf} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($top_level->{"optional"} or $top_level->{"leaf"}) 13 22 35
Condition66%2/3
$top_level->{"optional"} or $top_level->{"leaf"}
l!l&&r!l&&!r
22013
MC/DC50%1/2
$top_level->{"optional"} or $top_level->{"leaf"}
$top_level->{"optional"} $top_level->{"leaf"}
Truth table66%2/3
A or B
A= $top_level->{"optional"}B= $top_level->{"leaf"}
ABresult
1X1
011
000
426 13 $this_level_is_a_leaf = 0;
427 }
428 # This level has a flag that was passed on the command line
429 35 ▶ if ( defined $g_opts->{ $top_level->{name} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$g_opts{$top_level->{"name"}}) 8 27 35
430 # We only get one non-optional command per branch in the tree
431 8 ▶ if ( $top_level->{optional} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($top_level->{'optional'}) { } 1 7 8
elsif ($top_level->{'leaf'}) { } 0 7 7
432 1 my ( $status, $v ) = calc_param_value( $top_level, $g_opts );
433 0 ▶ if ( !$status ) { warn "Invalid value for $top_level->{name}!\n"; return; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($status) 0 1 1
434 1 $g_opts->{ $top_level->{name} } = $v;
435 1 push @approved_flags, $top_level->{name};
436 } elsif ( $top_level->{leaf} ) {
437 0 my ( $status, $v ) = calc_param_value( $top_level, $g_opts );
438 0 ▶ if ( !$status ) { warn "Invalid value for $top_level->{name}!\n"; return; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($status) 0 0 0
439 0 $g_opts->{ $top_level->{name} } = $v;
440 0 push @approved_flags, $top_level->{name};
441 0 $matched_leaves{ $top_level->{name} } = 1;
442 } else {
443 7 ▶ if ( $this_level ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($this_level) 0 7 7
444 # Already got a required parameter for this level, can't accept two!
445 0 warn "Can not specify $this_level and $top_level->{name}\n";
446 0 return;
447 }
448 7 $this_level = $top_level->{name};
449  
450 7 my ( $status, $v ) = calc_param_value( $top_level, $g_opts );
451 0 ▶ if ( !$status ) { warn "Invalid value for $top_level->{name}!\n"; return; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($status) 0 7 7
452 7 $g_opts->{ $top_level->{name} } = $v;
453 7 push @approved_flags, $top_level->{name};
454 }
455 8 ▶ if ( $top_level->{params} && !$top_level->{leaf} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"params"} and not $top_level->{"leaf"}) 6 2 8
Condition66%2/3
$top_level->{"params"} and not $top_level->{"leaf"}
!ll&&!rl&&r
206
MC/DC50%1/2
$top_level->{"params"} and not $top_level->{"leaf"}
$top_level->{"params"} not $top_level->{"leaf"}
Truth table66%2/3
A and not(B)
A= $top_level->{"params"}B= not $top_level->{"leaf"}
ABresult
0X0
100
111
456 6 my ( $status, @a ) = check_parameter( $g_opts, $top_level->{params} );
457 0 ▶ if ( !$status ) { return; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($status) 0 6 6
458 6 push @approved_flags, @a;
459 }
460 }
461 }
462 14 foreach my $l ( grep { $_->{leaf} } @{$params} ) {
463 0 ▶ if ( !$matched_leaves{ $l->{name} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($matched_leaves{$l->{"name"}}) 0 0 0
464 0 warn "Missing the following parameter: $l->{name}\n";
465 0 return;
466 }
467 }
468  
469 # We didn't match a parameter on this level and this level requires at
470 # least one match!
471 14 ▶ if ( ( !$this_level ) && ( !$this_level_is_a_leaf ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($this_level or $this_level_is_a_leaf) 0 14 14
Condition66%2/3
$this_level or $this_level_is_a_leaf
l!l&&r!l&&!r
770
MC/DC0%0/2
$this_level or $this_level_is_a_leaf
$this_level $this_level_is_a_leaf
Truth table66%2/3
A or B
A= $this_levelB= $this_level_is_a_leaf
ABresult
1X1
011
000
472 0 my @missing = map { $_->{name} } @{$params};
473 0 warn "Missing one (or more) of the following parameters: " . join( ', ', @missing ) . "\n";
474 0 return;
475 }
476  
477 14 return 1, @approved_flags;
478 }
479  
480 # Sets up the recursive call to check_parameter. This handles the first
481 # parameter in a special manner. A lot of this is probably unnecessary. Returns
482 # two values, the first is the "operation name" (the name of the first level
483 # parameter we matched on) and the hash of parameter name => value pairs.
484 # This function is exported.
485 4 ▶sub parse_command_line {
Subroutine parse_command_line: called CC=34 SCAR=46.4
Pod documented
486 4 my ( $params, $source ) = @_;
487 4 my @getopt_params;
488 my %g_opts;
489 4 my $status;
490 4 my $op_ref;
491 4 my $argv_index = 0;
492 4 my $op;
493 my $remaining_options;
494  
495 4 ▶ if ( !$SWITCH_PREFIX_STR || $SWITCH_PREFIX_STR ne '-' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $Getopt::Tree::SWITCH_PREFIX_STR or $Getopt::Tree::SWITCH_PREFIX_STR ne "-") 0 4 4
Condition33%1/3
not $Getopt::Tree::SWITCH_PREFIX_STR or $Getopt::Tree::SWITCH_PREFIX_STR ne "-"
l!l&&r!l&&!r
004
MC/DC0%0/2
not $Getopt::Tree::SWITCH_PREFIX_STR or $Getopt::Tree::SWITCH_PREFIX_STR ne "-"
not $Getopt::Tree::SWITCH_PREFIX_STR $Getopt::Tree::SWITCH_PREFIX_STR ne "-"
Truth table33%1/3
not(A) or B
A= not $Getopt::Tree::SWITCH_PREFIX_STRB= $Getopt::Tree::SWITCH_PREFIX_STR ne "-"
ABresult
1X1
011
000
496 0 ▶ my $t = $SWITCH_PREFIX_STR || '(?:)';
Condition0%0/2
$Getopt::Tree::SWITCH_PREFIX_STR || '(?:)'
l!l
00
MC/DC0%0/1
$Getopt::Tree::SWITCH_PREFIX_STR || '(?:)'
$Getopt::Tree::SWITCH_PREFIX_STR
Truth table0%0/2
A
A= $Getopt::Tree::SWITCH_PREFIX_STR
Aresult
11
00
497 0 Getopt::Long::Configure( "prefix_pattern=$t" );
498 }
499  
500 4 ▶ if ( !defined $source ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $source) { } 4 0 4
elsif (not ref $source) { } 0 0 0
501 4 $source = \@ARGV;
502 } elsif ( !ref $source ) {
503 0 require Text::ParseWords;
504 0 $source = [ Text::ParseWords::shellwords($source) ];
505 }
506  
507 # We can check our ARGV source for the first top level branch (non-optional
508 # and non-leaf) here, and then use that when we process that branch (only)
509 # below.
510 4 ARGV_INDEX_LOOP: while ( 1 ) {
511 4 $op = $source->[ $argv_index++ ];
512 4 ▶ last if !defined $op;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $op 0 4 4
513  
514 # If we encounter a value without a parameter before we find a top
515 # level op, abort with an error. Any values tied to a parameter should
516 # be skipped in the loop below.
517 # Is this really necessary? Any problems would be caught below
518 # --jeagle 20110411
519 #die "The command '$op' is not valid!\n" unless $op =~ /^-/;
520 4 ▶ if ( $SWITCH_PREFIX_STR ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Getopt::Tree::SWITCH_PREFIX_STR) 4 0 4
521 4 $op =~ s/^\Q$SWITCH_PREFIX_STR\E//;
522 }
523 4 foreach my $known_ops ( @{$params} ) {
524 0 ▶ if ( !$known_ops->{name} ) { die 'Invalid name!'; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($known_ops->{"name"}) 0 28 28
525 28 ▶ if ( ( $op eq $known_ops->{name} )
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq $known_ops->{"name"} or $known_ops->{"abbr"} and $op eq $known_ops->{"abbr"}) 4 24 28
Condition83%5/6
$op eq $known_ops->{"name"} or $known_ops->{"abbr"} and $op eq $known_ops->{"abbr"}
l!l&&r!l&&!r
0424
$known_ops->{"abbr"} and $op eq $known_ops->{"abbr"}
!ll&&!rl&&r
4204
MC/DC66%2/3
$op eq $known_ops->{"name"} or $known_ops->{"abbr"} and $op eq $known_ops->{"abbr"}
$op eq $known_ops->{"name"} $known_ops->{"abbr"} $op eq $known_ops->{"abbr"}
Truth table75%3/4
A or B and C
A= $op eq $known_ops->{"name"}B= $known_ops->{"abbr"}C= $op eq $known_ops->{"abbr"}
ABCresult
1XX1
0111
00X0
0100
526 || ( ( $known_ops->{abbr} ) && ( $op eq $known_ops->{abbr} ) ) )
527 {
528 4 ▶ if ( ( $known_ops->{optional} ) || ( $known_ops->{leaf} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($known_ops->{"optional"} or $known_ops->{"leaf"}) 0 4 4
Condition33%1/3
$known_ops->{"optional"} or $known_ops->{"leaf"}
l!l&&r!l&&!r
004
MC/DC0%0/2
$known_ops->{"optional"} or $known_ops->{"leaf"}
$known_ops->{"optional"} $known_ops->{"leaf"}
Truth table33%1/3
A or B
A= $known_ops->{"optional"}B= $known_ops->{"leaf"}
ABresult
1X1
011
000
529 0 ▶ if ( !$known_ops->{exists} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($known_ops->{"exists"}) 0 0 0
530 0 $argv_index++;
531 }
532 0 next ARGV_INDEX_LOOP;
533 }
534 4 $op = $known_ops->{name};
535 4 $op_ref = $known_ops;
536 4 last ARGV_INDEX_LOOP;
537 # if ( !$known_ops->{params} ) { return $op, { $op => 1 }; }
538 }
539 }
540 0 ▶ if ( !$op_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($op_ref) 0 0 0
541 0 warn "The command '$op' is unknown!\n";
542 0 return;
543 }
544 }
545  
546 0 ▶ if ( !$op ) { return; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($op) 0 4 4
547  
548 # Gather up all of the global non-branch parameters to pass to GetOptions.
549 # While we're at it, check to make sure the parameters are correct
550 4 my @global_options;
551 4 foreach my $optional_ops ( @{$params} ) {
552 36 ▶ next unless ( $optional_ops->{optional} ) || ( $optional_ops->{leaf} );
Branch: 1 branch
BranchTrueFalseTotal
unless $optional_ops->{"optional"} or $optional_ops->{"leaf"} 20 16 36
Condition66%2/3
$optional_ops->{"optional"} or $optional_ops->{"leaf"}
l!l&&r!l&&!r
16020
MC/DC50%1/2
$optional_ops->{"optional"} or $optional_ops->{"leaf"}
$optional_ops->{"optional"} $optional_ops->{"leaf"}
Truth table66%2/3
A or B
A= $optional_ops->{"optional"}B= $optional_ops->{"leaf"}
ABresult
1X1
011
000
553 0 ▶ if ( !$optional_ops->{name} ) { die 'Invalid name!'; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($optional_ops->{"name"}) 0 16 16
554 16 push @global_options, $optional_ops;
555 }
556  
557 4 ▶ if ( @global_options ) { push @getopt_params, process_getopt_params( \@global_options ); }
Branch: 1 branch
BranchTrueFalseTotal
if (@global_options) 4 0 4
558 4 push @getopt_params, process_getopt_params( [$op_ref] );
559 4 foreach my $p ( @getopt_params ) {
560 43 my ( $root ) = $p =~ /^(.+)=?/;
561 43 foreach my $k ( keys %g_opts ) {
562 0 ▶ if ( $k =~ /^\Q$root\E/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /^\Q$root\E/) 0 0 0
563 0 ▶ if ( $k ne $p ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k ne $p) 0 0 0
564 0 die "Duplicate parameter $p (matched $k) with different type specifications!\n";
565 }
566 }
567 }
568 }
569 4 undef %g_opts;
570  
571 4 eval {
572 4 ▶ local $SIG{__WARN__} = sub { };
Subroutine __ANON__: called CC=1 SCAR=0.0
573 # GetOptionsFromArray behaves badly unless called fully qualified. Not
574 # interested in tracking down why.
575 4 ( my $getopt_success, $remaining_options ) =
576 Getopt::Long::GetOptionsFromArray( $source, \%g_opts, @getopt_params );
577 4 ▶ return unless $getopt_success;
Branch: 1 branch
BranchTrueFalseTotal
unless $getopt_success 0 4 4
578 };
579 4 undef @getopt_params;
580  
581 # Find the top-level parameter we're going to work with.
582 4 ( $status, @getopt_params ) = check_parameter( \%g_opts, [$op_ref] );
583 4 ▶ return unless $status;
Branch: 1 branch
BranchTrueFalseTotal
unless $status 0 4 4
584  
585 4 ▶ if ( @global_options ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@global_options) 4 0 4
586 4 ( $status, @global_options ) = check_parameter( \%g_opts, \@global_options );
587 4 ▶ return unless $status;
Branch: 1 branch
BranchTrueFalseTotal
unless $status 0 4 4
588 4 push @getopt_params, @global_options;
589 }
590  
591 # By this point, %g_opts contains everything the user passed, and @global_options
592 # is everything that should have been passed.
593  
594 4 my %good_values;
595 4 my $all_good = 1;
596 4 @good_values{@getopt_params} = ();
597 4 foreach my $k ( keys( %g_opts ) ) {
598 8 ▶ if ( !exists $good_values{$k} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $good_values{$k}) 0 8 8
599 0 warn "Invalid parameter: $k\n";
600 0 $all_good = 0;
601 }
602 }
603  
604 4 ▶ if ( !$all_good ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($all_good) 0 4 4
605 0 warn "Not all good!";
606 0 return;
607 }
608 4 return $op, \%g_opts, $remaining_options;
609 }
610  
611 # Pre-scan to get the width of all of the parameters
612 9 ▶sub get_usage_param_width {
Subroutine get_usage_param_width: called CC=9 SCAR=22.0
Pod undocumented
613 9 my ( $params, $depth, $length ) = @_;
614 9 ▶ if ( !defined $depth ) { $depth = 0; }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $depth) 1 8 9
615 9 ▶ my $param_length = ( $length || 1 );
Condition100%2/2
$length || 1
l!l
81
MC/DC100%1/1
$length || 1
$length
Truth table100%2/2
A
A= $length
Aresult
11
00
616  
617 9 foreach my $top_level ( @{$params} ) {
618 23 my $this_length = ( length( DEPTH_STR ) * $depth ) + length( $top_level->{name} ) + 1;
619 23 ▶ if ( $top_level->{abbr} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"abbr"}) 15 8 23
620 15 $this_length += length( $top_level->{abbr} ) + ABBR_PARAM_SEPARATOR_LENGTH + 1;
621 }
622 23 ▶ if ( $top_level->{optional} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"optional"}) 12 11 23
623 12 $this_length += 4; # length of '[ ' . ' ]'
624 }
625 23 ▶ if ( !$top_level->{exists} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($top_level->{"exists"}) 10 13 23
626 10 $this_length += 5; # length of _<..>
627 }
628  
629 23 ▶ if ( $this_length > $param_length ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($this_length > $param_length) 5 18 23
630 5 $param_length = $this_length;
631 }
632 23 ▶ if ( $top_level->{params} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"params"}) 8 15 23
633 8 $param_length = get_usage_param_width( $top_level->{params}, $depth + 1, $param_length );
634 }
635 }
636 9 return $param_length;
637 }
638  
639 9 ▶sub print_actual_usage {
Subroutine print_actual_usage: called CC=15 SCAR=27.2
Pod undocumented
640 9 my ( $params, $param_width, $depth ) = @_;
641 9 ▶ if ( !defined $depth ) { $depth = 0; }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $depth) 1 8 9
642 9 my $d = DEPTH_STR x $depth;
643 9 my $out = '';
644 9 ▶ my $switch_prefix = $SWITCH_PREFIX_STR || '';
Condition50%1/2
$Getopt::Tree::SWITCH_PREFIX_STR || ''
l!l
90
MC/DC0%0/1
$Getopt::Tree::SWITCH_PREFIX_STR || ''
$Getopt::Tree::SWITCH_PREFIX_STR
Truth table50%1/2
A
A= $Getopt::Tree::SWITCH_PREFIX_STR
Aresult
11
00
645 9 ▶ return '' unless ref $params eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $params eq "ARRAY" 0 9 9
646  
647 # Print the parameters (recursively) with optional parameters first.
648 9 foreach my $top_level (
649 sort {
650 30 ▶ if ( ( $a->{optional} || 0 ) == ( $b->{optional} || 0 ) )
Branch: 1 branch
BranchTrueFalseTotal
if (($Getopt::Tree::a->{'optional'} || 0) == ($Getopt::Tree::b->{'optional'} || 0)) { } 21 9 30
Condition100%4/4
$Getopt::Tree::a->{'optional'} || 0
l!l
1119
$Getopt::Tree::b->{'optional'} || 0
l!l
1416
MC/DC100%1/1
$Getopt::Tree::a->{'optional'} || 0
$Getopt::Tree::a->{'optional'}
MC/DC100%1/1
$Getopt::Tree::b->{'optional'} || 0
$Getopt::Tree::b->{'optional'}
Truth table100%2/2
A
A= $Getopt::Tree::a->{'optional'}
Aresult
11
00
Truth table100%2/2
A
A= $Getopt::Tree::b->{'optional'}
Aresult
11
00
651 {
652 21 return $a->{name} cmp $b->{name};
653 } else {
654 9 ▶ if ( $a->{optional} ) { return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if ($Getopt::Tree::a->{"optional"}) 3 6 9
655 6 ▶ if ( $b->{optional} ) { return 1; }
Branch: 1 branch
BranchTrueFalseTotal
if ($Getopt::Tree::b->{"optional"}) 6 0 6
656 0 return 0;
657 }
658 9 } @{$params} )
659 {
660 # Don't show the leading dash on the first parameter (command).
661 #my $param_desc = ( ( $depth == 0 && !$top_level->{optional} ) ? '' : '-' ) . $top_level->{name};
662 23 my $param_desc = $switch_prefix . $top_level->{name};
663 23 ▶ if ( $top_level->{abbr} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"abbr"}) 15 8 23
664 $param_desc = $param_desc . ABBR_PARAM_SEPARATOR
665 #. ( ( $depth == 0 && !$top_level->{optional} ) ? '' : '-' )
666 15 . $switch_prefix . $top_level->{abbr};
667 }
668 23 ▶ if ( !$top_level->{exists} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($top_level->{"exists"}) 10 13 23
669 10 $param_desc .= ' <..>';
670 }
671 23 ▶ if ( $top_level->{optional} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"optional"}) 12 11 23
672 12 $param_desc = '[ ' . $param_desc . ' ]';
673 }
674 23 $param_desc = sprintf( "%-${param_width}.${param_width}s ", $d . $param_desc );
675  
676 $out .= wrap(
677 $param_desc,
678 ' ' x ( $param_width + 2 ),
679 23 ▶ ( $top_level->{descr} || '(No description provided.)' ) ) . "\n";
Condition50%1/2
$top_level->{'descr'} || '(No description provided.)'
l!l
230
MC/DC0%0/1
$top_level->{'descr'} || '(No description provided.)'
$top_level->{'descr'}
Truth table50%1/2
A
A= $top_level->{'descr'}
Aresult
11
00
680 23 ▶ if ( $top_level->{params} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($top_level->{"params"}) 8 15 23
681 8 $out .= print_actual_usage( $top_level->{params}, $param_width, $depth + 1 );
682 }
683 }
684  
685 9 return $out;
686 }
687  
688 # Calculate widths and set off the recursive call to print_actual_usage.
689 # This function is exported.
690 # Woah! Why did this get so complicated? Well, prior to 1.12 we accepted the
691 # second parameter as a filehandle to print to. In 1.12 I realized that was
692 # silly, and it would be better to just return the usage as a string. So now,
693 # for backward-compatability sake, we must support all of the options. Passing
694 # a filehandle causes us to print to that with an appropriate width. No
695 # filehandle will assume STDOUT as the filehandle. Passing a hash causes us to
696 # read various options from that hash.
697 1 ▶sub print_usage {
Subroutine print_usage: called CC=16 SCAR=33.3
Pod documented
698 1 my ( $params, $fh_or_options ) = @_;
699 1 my $param_width = get_usage_param_width( $params );
700 1 my $options;
701  
702 1 ▶ if ( !defined $fh_or_options ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $fh_or_options) { } 0 1 1
elsif (ref $fh_or_options eq 'HASH') { } 0 1 1
703 0 $options = { fh => *STDERR, return => 0 };
704 } elsif ( ref $fh_or_options eq 'HASH' ) {
705 # Copy it in case the caller wants to re-use.
706 0 $options = \%{ $fh_or_options };
707 } else {
708 1 $options = { fh => $fh_or_options, return => 0 };
709 }
710 1 ▶ if ( $options->{fh} && !$options->{wrap_at} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"fh"} and not $options->{"wrap_at"}) 1 0 1
Condition33%1/3
$options->{"fh"} and not $options->{"wrap_at"}
!ll&&!rl&&r
001
MC/DC0%0/2
$options->{"fh"} and not $options->{"wrap_at"}
$options->{"fh"} not $options->{"wrap_at"}
Truth table33%1/3
A and not(B)
A= $options->{"fh"}B= not $options->{"wrap_at"}
ABresult
0X0
100
111
711 1 ▶ if ( ( -t $options->{fh} ) && ( defined $ENV{COLUMNS} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-t $options->{"fh"} and defined $ENV{"COLUMNS"}) 0 1 1
Condition33%1/3
-t $options->{"fh"} and defined $ENV{"COLUMNS"}
!ll&&!rl&&r
100
MC/DC0%0/2
-t $options->{"fh"} and defined $ENV{"COLUMNS"}
-t $options->{"fh"} defined $ENV{"COLUMNS"}
Truth table33%1/3
A and B
A= -t $options->{"fh"}B= defined $ENV{"COLUMNS"}
ABresult
0X0
100
111
712 0 $options->{wrap_at} = $ENV{COLUMNS};
713 }
714 }
715 1 ▶ if ( !$options->{wrap_at} || $options->{wrap_at} !~ /^\d{1,4}$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options->{"wrap_at"} and $options->{"wrap_at"} =~ /^\d{1,4}$/) 1 0 1
Condition33%1/3
$options->{"wrap_at"} and $options->{"wrap_at"} =~ /^\d{1,4}$/
!ll&&!rl&&r
100
MC/DC0%0/2
$options->{"wrap_at"} and $options->{"wrap_at"} =~ /^\d{1,4}$/
$options->{"wrap_at"} $options->{"wrap_at"} =~ /^\d{1,4}$/
Truth table33%1/3
A and B
A= $options->{"wrap_at"}B= $options->{"wrap_at"} =~ /^\d{1,4}$/
ABresult
0X0
100
111
716 1 $options->{wrap_at} = 80;
717 }
718  
719 1 local $Text::Wrap::unexpand = 0;
720 1 local $Text::Wrap::columns = $options->{wrap_at};
721 1 my $usage_short = '';
722  
723 1 foreach my $p ( @{ $params } ) {
724 9 ▶ if ( $p->{leaf} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"leaf"}) 0 9 9
725 0 $usage_short .= "-$p->{name} ";
726 }
727 }
728  
729 1 my $usage_str = '';
730  
731 1 ▶ if ( !$options->{hide_top_line} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options->{"hide_top_line"}) 1 0 1
732 1 $usage_str = 'Usage: ' . basename( $0 ) . wrap( '', '', " <command> ${usage_short}\[flags\]\n" ) . "\n";
733 }
734  
735 1 ▶ if ( $USAGE_HEADER ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Getopt::Tree::USAGE_HEADER) 1 0 1
736 1 $usage_str .= $USAGE_HEADER;
737 }
738  
739 1 $usage_str .= "Options:\n" . print_actual_usage( $params, $param_width ), "\n";
740  
741 1 ▶ if ( $USAGE_FOOTER ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Getopt::Tree::USAGE_FOOTER) 1 0 1
742 1 $usage_str .= $USAGE_FOOTER;
743 }
744  
745 1 ▶ if ( $options->{fh} ) { print {$options->{fh}} $usage_str; }
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"fh"}) 1 0 1
746 0 ▶ if ( $options->{return} ) { return $usage_str; }
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"return"}) 0 1 1
747 }
748  
749 =head1 CHANGES
750  
751 =head2 Version 1.12, 20100411, jeagle
752  
753 Add ability to return usage as a string.
754  
755 Add ability to set the prefix character via $Getopt::Tree::SWITCH_PREFIX_STR
756  
757 Remove automatic -help flag.
758  
759 Fix a silly bug causing parameter values that evaluate to false to fail.
760  
761 =head2 Version 1.11, 20100917, jeagle
762  
763 Appease older versions of Perl in print_usage's usage of square brackets in
764 a string.
765  
766 =head2 Version 1.10, 20100709, jeagle
767  
768 Correct handling of eval flags mixed with other flags.
769  
770 Add optional destination filehandle to print_usage.
771  
772 Clean up for export to CPAN.
773  
774 =head2 Version 1.9, 20100428, jeagle
775  
776 Show usage if no parameters are passed.
777  
778 =head2 Version 1.8, 20100427, jeagle
779  
780 Add $Version variable.
781  
782 Give a better error message for parameters passed without a leading '-'.
783  
784 =head2 Version 1.4, 20100427, jeagle
785  
786 Add automatic -help flag parsing. This feature may cause problems if users
787 wanted to override '-help', so this may change in the future.
788  
789 Show required leaf parmeters at the top usage line, reformat usage a little.
790  
791 =cut
792  
793 1 1;
↑ Summary