blib/lib/Getopt/ArgParse/Parser.pm untested

filter: Statementstmt 0.0% 0 / 622 Branchbran 0.0% 0 / 306 Conditioncond 0.0% 0 / 159 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 29 totaltotal 0.0% 0 / 1152 SCAR 100.4
CC
151
Cov
0%
add_argument
1722.0
_post_parse_processing
420.0
_format_usage_by_spec
182.0
CRAP 22952.0
1 package Getopt::ArgParse::Parser;
2  
3 use Moo;
4  
5 use Getopt::Long qw(GetOptionsFromArray);
6 use Text::Wrap;
7 use Scalar::Util qw(blessed);
8  
9 use File::Basename ();
10 use Getopt::ArgParse::Namespace;
11  
12 use constant {
13 TYPE_UNDEF => 0,
14 TYPE_SCALAR => 1,
15 TYPE_ARRAY => 2,
16 TYPE_COUNT => 3,
17 TYPE_PAIR => 4, # key=value pair
18 TYPE_BOOL => 5,
19  
20 CONST_TRUE => 1,
21 CONST_FALSE => 0,
22  
23 # Export these?
24 ScalarArg => 'scalar',
25 ArrayArg => 'Array',
26 PairArg => 'Pair',
27 CountArg => 'Count',
28 BoolArg => 'Bool',
29  
30 # Internal
31 ERROR_PREFIX => 'Getopt::ArgParse: ',
32 PRINT_REQUIRED => 1,
33 PRINT_OPTIONAL => 2,
34 };
35  
36 # Allow customization
37 # default actions
38 my %Action2ClassMap = (
39 '_store' => 'Getopt::ArgParse::ActionStore',
40 '_append' => 'Getopt::ArgParse::ActionAppend',
41 '_count' => 'Getopt::ArgParse::ActionCount',
42 # Not supported - Maybe in the future
43 # '_help' => 'Getopt::ArgParse::ActionHelp',
44 # '_version' => 'Getopt::ArgParse::ActionVersion',
45 );
46  
47 my %Type2ConstMap = (
48 '' => TYPE_UNDEF(),
49 'Scalar' => TYPE_SCALAR(),
50 'Array' => TYPE_ARRAY(),
51 'Count' => TYPE_COUNT(),
52 'Pair' => TYPE_PAIR(),
53 'Bool' => TYPE_BOOL(),
54 );
55  
56  
57 sub _croak {
58 die join('', @_, "\n");
59 }
60  
61 # Program name. Default $0
62  
63 has prog => ( is => 'rw', required => 1, default => sub { File::Basename::basename($0) }, );
64  
65 # short one
66 has help => ( is => 'rw', required => 1, default => sub { '' }, );
67  
68 # long one
69 has description => ( is => 'rw', required => 1, default => sub { '' }, );
70  
71 has epilog => ( is => 'rw', required => 1, default => sub { '' }, );
72  
73 has error_prefix => (is => 'rw', default => sub { ERROR_PREFIX() }, );
74  
75 has aliases => (is => 'ro', default => sub { [] }); # for subcommand only
76  
77 # namespace() - Read/write
78 # Contains the parsed results.
79 has namespace => (
80 is => 'rw',
81 isa => sub {
82 return undef unless $_[0]; # allow undef
83 my $class = blessed $_[0];
84 die 'namespace doesn\'t comform to the required interface'
85 unless $class && $class->can('set_attr') && $class->can('get_attr');
86 },
87 );
88  
89 # parent - Readonly
90 has parents => (
91 is => 'ro',
92 isa => sub {
93 my $parents = shift;
94 for my $parent (@$parents) {
95 my $parent_class = blessed $parent;
96 die 'parent is not a Getopt::ArgParse::Parser'
97 unless $parent_class && $parent_class->isa(__PACKAGE__);
98 }
99 },
100 default => sub { [] },
101 );
102  
103 # parser_configs - Read/write
104  
105 # The configurations that will be passed to Getopt::Long::Configure(
106 # $self->parser_configs ) when parse_args is invoked.
107 has parser_configs => ( is => 'rw', required => 1, default => sub { [] }, );
108  
109 # Behavioural properties
110 #
111 # Print usage message if help is no, by default. Turn this off by
112 # setting this to a false value
113 has print_usage_if_help => (is => 'ro', default => 1);
114  
115 # internal properties
116  
117 has _option_position => ( is => 'rw', required => 1, default => sub { 0 } );
118  
119 # The current subcommand the same as namespace->current_command
120 has _command => ( is => 'rw');
121  
122 sub BUILD {
123 my $self = shift;
124  
125 $self->{-option_specs} = {};
126 $self->{-position_specs} = {};
127  
128 $self->add_argument(
129 '--help', '-h',
130 type => 'Bool',
131 dest => 'help',
132 help => 'show this help message and exit',
133 reset => 1,
134 );
135  
136 # merge
137 for my $parent (@{$self->parents}) {
138 $self->copy($parent);
139 }
140 }
141  
142 #
143 sub _check_parent {
144 my $parent = shift;
145 my $parent_class = blessed $parent;
146 _croak 'Parent is not a Getopt::ArgParse::Parser'
147 unless $parent_class && $parent_class->isa(__PACKAGE__);
148 }
149  
150 sub copy {
151 my $self = shift;
152 my $parent = shift;
153  
154 _croak 'Parent is missing' unless $parent;
155 _check_parent($parent);
156  
157 $self->copy_args($parent);
158 $self->copy_parsers($parent);
159 }
160  
161 sub copy_args {
162 my $self = shift;
163 my $parent = shift;
164  
165 _croak 'Parent is missing' unless $parent;
166 _check_parent($parent);
167  
168 $self->add_arguments( @{ $parent->{-pristine_add_arguments} } );
169 }
170  
171 sub copy_parsers {
172 my $self = shift;
173 my $parent = shift;
174  
175 _croak 'Parent is missing' unless $parent;
176 _check_parent($parent);
177  
178 if (exists $parent->{-subparsers}) {
179 $self->add_subparsers(
180 @{$parent->{-pristine_add_subparsers}->[0]}
181 );
182  
183 for my $args (@{$parent->{-pristine_add_parser}}) {
184 my $command = $args->[0];
185 next if $command eq 'help';
186 $self->add_parser(
187 @$args,
188 parents => [ $parent->{-subparsers}{-parsers}{$command} ],
189 );
190 }
191 }
192 }
193  
194 #
195 # subcommands
196 #
197 sub add_subparsers {
198 my $self = shift;
199  
200 push @{$self->{-pristine_add_subparsers}}, [ @_ ];
201  
202 _croak $self->error_prefix . 'Incorrect number of arguments' if scalar(@_) % 2;
203  
204 my $args = { @_ };
205  
206 my $title = (delete $args->{title} || 'subcommands') . ':';
207 my $description = delete $args->{description} || '';
208  
209 _croak $self->error_prefix . sprintf(
210 'Unknown parameters: %s',
211 join(',', keys %$args)
212 ) if keys %$args;
213  
214 if (exists $self->{-subparsers}) {
215 _croak $self->error_prefix . 'Subparsers already added';
216 }
217  
218 $self->{-subparsers}{-title} = $title;
219 $self->{-subparsers}{-description} = $description;
220 $self->{-subparsers}{-alias_map} = {};
221  
222 my $hp = $self->add_parser(
223 'help',
224 help => 'display help information about ' . $self->prog,
225 );
226  
227 $hp->add_arguments(
228 [
229 '--all', '-a',
230 help => 'Show the full usage',
231 type => 'Bool',
232 ],
233 [
234 'command',
235 help => 'Show the usage for this command',
236 dest => 'help_command',
237 nargs => 1,
238 ],
239 );
240  
241 return $self;
242 }
243  
244 # $command, aliases => [], help => ''
245 sub add_parser {
246 my $self = shift;
247  
248 _croak $self->error_prefix . 'add_subparsers() is not called first' unless $self->{-subparsers};
249  
250 my $command = shift;
251  
252 _croak $self->error_prefix . 'Subcommand is empty' unless $command;
253  
254 _croak $self->error_prefix . 'Incorrect number of arguments' if scalar(@_) % 2;
255  
256 if (exists $self->{-subparsers}{-parsers}{$command}) {
257 _croak $self->error_prefix . "Subcommand $command already defined";
258 }
259  
260 my $args = { @_ };
261  
262 my $parents = delete $args->{parents} || [];
263 push @{ $self->{-pristine_add_parser} }, [ $command, %$args ];
264  
265 _croak $self->error_prefix . 'Add_subparsers() is not called first' unless $self->{-subparsers};
266  
267 my $help = delete $args->{help} || '';
268 my $description = delete $args->{description} || '';
269 my $aliases = delete $args->{aliases} || [];
270  
271 _croak $self->error_prefix . 'Aliases is not an arrayref'
272 if ref($aliases) ne 'ARRAY';
273  
274 _croak $self->error_prefix . sprintf(
275 'Unknown parameters: %s',
276 join(',', keys %$args)
277 ) if keys %$args;
278  
279 my $alias_map = {};
280  
281 for my $alias ($command, @$aliases) {
282 if (exists $self->{-subparsers}{-alias_map}{$alias}) {
283 _croak $self->error_prefix
284 . "Alias=$alias already used by command="
285 . $self->{-subparsers}{-alias_map}{$alias};
286 }
287 }
288  
289 $self->{-subparsers}{-alias_map}{$_} = $command for ($command, @$aliases);
290  
291 my $prog = $command;
292  
293 # $prog .= ' (' . join(', ', @$aliases) . ')' if @$aliases;
294  
295 $self->{-subparsers}{-aliases}{$command} = $aliases;
296 return $self->{-subparsers}{-parsers}{$command} = __PACKAGE__->new(
297 prog => $prog,
298 aliases => $aliases, # subcommand
299 help => $help,
300 parents => $parents,
301 description => $description,
302 error_prefix => $self->error_prefix,
303 print_usage_if_help => $self->print_usage_if_help,
304 );
305 }
306  
307 sub get_parser { $_[0]->_get_subcommand_parser(@_) }
308  
309 *add_arg = \&add_argument;
310  
311 *add_args = \&add_arguments;
312  
313 # add_arguments([arg_spec], [arg_spec1], ...)
314 # Add multiple arguments.
315 # Interface method
316 sub add_arguments {
317 my $self = shift;
318  
319 $self->add_argument(@$_) for @_;
320  
321 return $self;
322 }
323  
324 #
325 sub add_argument {
326 my $self = shift;
327  
328 return unless @_; # mostly harmless
329 #
330 # FIXME: This is for merginng parent parents This is a dirty hack
331 # and should be done properly by merging internal specs
332 # and subcommand merging is missing
333 #
334 push @{ $self->{-pristine_add_arguments} }, [ @_ ];
335  
336 my ($name, $flags, $rest) = $self->_parse_for_name_and_flags([ @_ ]);
337  
338 _croak $self->error_prefix . 'Incorrect number of arguments' if scalar(@$rest) % 2;
339  
340 _croak $self->error_prefix . 'Empty option name' unless $name;
341  
342 my $args = { @$rest };
343  
344 my @flags = @{ $flags };
345  
346 ################
347 # nargs - positional only
348 ################
349 ################
350 # type
351 ################
352 my $type_name = delete $args->{type} || 'Scalar';
353 my $type = $Type2ConstMap{$type_name} if exists $Type2ConstMap{$type_name};
354 _croak $self->error_prefix . "Unknown type=$type_name" unless defined $type;
355  
356 my $nargs = delete $args->{nargs};
357  
358 if ( defined $nargs ) {
359 _croak $self->error_prefix . 'Nargs only allowed for positional options' if @flags;
360  
361 if ( $type != TYPE_PAIR
362 && $type != TYPE_ARRAY
363 && $nargs ne '1'
364 && $nargs ne '?'
365 ) {
366 $type = TYPE_ARRAY;
367 }
368 }
369  
370 if ($type == TYPE_COUNT) {
371 $args->{action} = '_count' unless defined $args->{action};
372 $args->{default} = 0 unless defined $args->{default};
373 } elsif ($type == TYPE_ARRAY || $type == TYPE_PAIR) {
374 $args->{action} = '_append' unless defined $args->{action};
375 } else {
376 # pass
377 }
378  
379 ################
380 # action
381 ################
382 my $action_name = delete $args->{action} || '_store';
383  
384 my $action = $Action2ClassMap{$action_name}
385 if exists $Action2ClassMap{$action_name};
386  
387 $action = $action_name unless $action;
388  
389 {
390 local $SIG{__WARN__};
391 local $SIG{__DIE__};
392  
393 eval "require $action";
394  
395 _croak $self->error_prefix . "Cannot load $action for action=$action_name" if $@;
396 };
397  
398 ################
399 # split
400 ################
401 my $split = delete $args->{split};
402 if (defined $split && !$split && $split =~ /^ +$/) {
403 _croak $self->error_prefix . 'Cannot use whitespaces to split';
404 }
405  
406 if (defined $split && $type != TYPE_ARRAY && $type != TYPE_PAIR) {
407 _croak $self->error_prefix . 'Split only for Array and Pair';
408 }
409  
410 ################
411 # default
412 ################
413 my $default;
414 if (exists $args->{default}) {
415 my $val = delete $args->{default};
416  
417 if (ref($val) eq 'ARRAY') {
418 $default = $val;
419 } elsif (ref($val) eq 'HASH') {
420 _croak $self->error_prefix . 'HASH default only for type Pair'
421 if $type != TYPE_PAIR;
422 $default = $val;
423 } else {
424 $default = [ $val ];
425 }
426  
427 if ($type != TYPE_PAIR) {
428 if ($type != TYPE_ARRAY && scalar(@$default) > 1) {
429 _croak $self->error_prefix . 'Multiple default values for scalar type: $name';
430 }
431 }
432 }
433  
434 ################
435 # choices
436 ################
437 my $choices = delete $args->{choices} || undef;
438 if ( $choices
439 && ref($choices) ne 'CODE'
440 && ref($choices) ne 'ARRAY' )
441 {
442 _croak $self->error_prefix . "Must provide choices in an arrayref or a coderef";
443 }
444  
445 my $choices_i = delete $args->{choices_i} || undef;
446  
447 if ($choices && $choices_i) {
448 _croak $self->error_prefix . 'Not allow to specify choices and choices_i';
449 }
450  
451 if ( $choices_i
452 && ref($choices_i) ne 'ARRAY' )
453 {
454 _croak $self->error_prefix . "Must provide choices_i in an arrayref";
455 }
456  
457 ################
458 # required
459 ################
460 my $required = delete $args->{required} || '';
461  
462 if ($type == TYPE_BOOL || $type == TYPE_COUNT) {
463 $required = ''; # TYPE_BOOL and TYPE_COUNT will already have default values
464 }
465  
466 ################
467 # help
468 ################
469 my $help = delete $args->{help} || '';
470  
471 ################
472 # metavar
473 ################
474 my $metavar = delete $args->{metavar} || uc($name);
475  
476 $metavar = ''
477 if $type == TYPE_BOOL
478 || $action_name eq '_count';
479  
480 ################
481 # dest
482 ################
483 my $dest = delete $args->{dest} || $name;
484 $dest =~ s/-/_/g; # option-name becomes option_name
485  
486 if (@flags) {
487 while (my ($d, $s) = each %{$self->{-option_specs}}) {
488 if ($dest ne $d) {
489 for my $f (@flags) {
490 _croak $self->error_prefix . "Flag $f already used for a different option ($d)"
491 if grep { $f eq $_ } @{$s->{flags}};
492 }
493 }
494 }
495  
496 if (exists $self->{-position_specs}{$dest}) {
497 _croak $self->error_prefix . "Option dest=$dest already used by a positional argument";
498 }
499 } else {
500 if (exists $self->{-option_specs}{$dest}) {
501 _croak $self->error_prefix . "Option dest=$dest already used by an optional argument";
502 }
503 }
504  
505 # never modify existing ones so that the parent's structure will
506 # not be modified
507 my $spec = {
508 name => $name,
509 flags => \@flags,
510 action => $action,
511 nargs => $nargs,
512 split => $split,
513 required => $required || '',
514 type => $type,
515 default => $default,
516 choices => $choices,
517 choices_i => $choices_i,
518 dest => $dest,
519 metavar => $metavar,
520 help => $help,
521 position => $self->{-option_position}++, # sort order
522 groups => [ '' ],
523 };
524  
525 my $specs;
526 if (@flags) {
527 $specs = $self->{-option_specs};
528 } else {
529 $specs = $self->{-position_specs};
530 }
531  
532 # reset
533 if (delete $args->{reset}) {
534 $self->namespace->set_attr($spec->{dest}, undef) if $self->namespace;
535 delete $specs->{$spec->{dest}};
536 }
537  
538 _croak $self->error_prefix . sprintf(
539 'Unknown spec: %s',
540 join(',', keys %$args)
541 ) if keys %$args;
542  
543 # type check
544 if (exists $specs->{$spec->{dest}}) {
545 _croak $self->error_prefix . sprintf(
546 'Redefine option %s without reset',
547 $spec->{dest},
548 );
549 }
550  
551 # override
552 $specs->{$spec->{dest}} = $spec;
553  
554 # specs changed, need to force to resort specs by groups
555 delete $self->{-groups} if $self->{-groups};
556  
557 # Return $self for chaining, $self->add_argument()->add_argument()
558 # or use add_arguments
559 return $self;
560 }
561  
562 sub _parse_for_name_and_flags {
563 my $self = shift;
564 my $args = shift;
565  
566 my ($name, @flags);
567 FLAG:
568 while (my $flag = shift @$args) {
569 if (substr($flag, 0, 1) eq '-') {
570 push @flags, $flag;
571 } else {
572 unshift @$args, $flag;
573 last FLAG;
574 }
575 }
576  
577 # It's a positional argument spec if there are no flags
578 $name = @flags ? $flags[0] : shift(@$args);
579 $name =~ s/^-+//g;
580  
581 return ( $name, \@flags, $args );
582 }
583  
584 #
585 # parse_args([@_])
586 #
587 # Parse @ARGV if called without passing arguments. It returns an
588 # instance of ArgParse::Namespace upon success
589 #
590 # Interface
591  
592 sub parse_args {
593 my $self = shift;
594  
595 my @argv = scalar(@_) ? @_ : @ARGV;
596  
597 $self->{-saved_argv} = \@ARGV;
598 @ARGV = ();
599  
600 my @option_specs = sort {
601 $a->{position} <=> $b->{position}
602 } values %{$self->{-option_specs}};
603  
604 my @position_specs = sort {
605 $a->{position} <=> $b->{position}
606 } values %{$self->{-position_specs}};
607  
608 $self->{-argv} = \@argv;
609 # We still want to continue even if @argv is empty to allow:
610 # - namespace initialization
611 # - default values asssigned
612 # - post checks applied, e.g. required check
613  
614 $self->namespace(Getopt::ArgParse::Namespace->new) unless $self->namespace;
615  
616 my $parsed_subcmd;
617 $self->namespace->set_attr(current_command => undef);
618  
619 # If the first argument is a subcommand, it will parse for the
620 # subcommand
621 if (exists $self->{-subparsers} && scalar(@argv) && defined($argv[0]) && substr($argv[0], 0, 1) ne '-') {
622 # Subcommand must appear as the first argument
623 # or it will parse as the top command
624 my $cmd = shift @argv;
625 my $subparser = $self->_get_subcommand_parser($cmd);
626 _croak $self->error_prefix
627 . sprintf("%s is not a %s command. See help", $cmd, $self->prog)
628 unless $subparser;
629  
630 $parsed_subcmd = $self->_parse_subcommand($self->_command => $subparser);
631  
632 $self->namespace->set_attr(current_command => $self->_command);
633 }
634  
635 if (!$parsed_subcmd) {
636 $self->_parse_optional_args(\@option_specs) if @option_specs;
637 $self->_parse_positional_args(\@position_specs) if @position_specs;
638  
639 if ($self->print_usage_if_help() && $self->namespace->get_attr('help')) {
640 $self->print_usage();
641 exit(0);
642 }
643 } else {
644 if ($self->print_usage_if_help() && $self->_command() eq 'help') {
645 if ($self->namespace->get_attr('help_command')) {
646 $self->print_command_usage();
647 exit(0);
648 } else {
649 $self->print_usage();
650 exit(0);
651 }
652 }
653 }
654  
655 # Return value
656 return $self->namespace;
657 }
658  
659 sub _get_subcommand_parser {
660 my $self = shift;
661 my $alias = shift;
662  
663 return unless $alias;
664  
665 my $command = $self->{-subparsers}{-alias_map}{$alias}
666 if exists $self->{-subparsers}{-alias_map}{$alias};
667  
668 return unless $command;
669  
670 $self->_command($command);
671 # The subcommand parser must exist if the alias is mapped
672 return $self->{-subparsers}{-parsers}{$command};
673 }
674  
675 sub _parse_subcommand {
676 my $self = shift;
677 my ($cmd, $subparser) = @_;
678  
679 $subparser->namespace($self->namespace);
680 $subparser->parse_args(@{$self->{-argv}});
681  
682 $self->{-argv} = $subparser->{-argv};
683  
684 return 1;
685 }
686  
687 #
688 # After each call of parse_args(), call this to retrieve any
689 # unconsumed arguments
690 # Interface call
691 #
692 sub argv {
693 @{ $_[0]->{-argv} || [] };
694 }
695  
696 sub _parse_optional_args {
697 my $self = shift;
698 my $specs = shift;
699 my $options = {};
700 my $dest2spec = {};
701  
702 for my $spec ( @$specs ) {
703 my @values;
704 $dest2spec->{$spec->{dest}} = $self->_get_option_spec($spec);
705 if ( $spec->{type} == TYPE_ARRAY
706 || $spec->{type} == TYPE_COUNT
707 || $spec->{type} == TYPE_PAIR
708 || $spec->{type} == TYPE_SCALAR
709 ) {
710 my @values;
711 $options->{ $dest2spec->{$spec->{dest}} } = \@values;
712 } else {
713 my $value;
714 $options->{ $dest2spec->{$spec->{dest}} } = \$value;
715 }
716 }
717  
718 Getopt::Long::Configure( @{ $self->parser_configs });
719  
720 my (@warns, $result);
721  
722 eval {
723 local $SIG{__WARN__} = sub { push @warns, @_ };
724 local $SIG{__DIE__};
725  
726 $result = GetOptionsFromArray( $self->{-argv}, %$options );
727  
728 1;
729 };
730  
731 # die on errors
732 _croak $self->error_prefix, $@ if $@;
733  
734 _croak $self->error_prefix, @warns if @warns;
735  
736 _croak $self->error_prefix, 'Failed to parse for options' if !$result;
737  
738 Getopt::Long::Configure('default');
739  
740 $self->_post_parse_processing($specs, $options, $dest2spec);
741  
742 $self->_apply_action($specs, $options, $dest2spec);
743  
744 $self->_post_apply_processing($specs, $options, $dest2spec);
745 }
746  
747 sub _parse_positional_args {
748 my $self = shift;
749 my $specs = shift;
750  
751 # short-circuit it if it's for help
752 return if $self->namespace->get_attr('help');
753  
754 my $options = {};
755 my $dest2spec = {};
756  
757 for my $spec (@$specs) {
758 $dest2spec->{$spec->{dest}} = $spec->{dest};
759 my @values = ();
760 # Always assigne values to an option
761 $options->{$spec->{dest}} = \@values;
762 }
763  
764 POSITION_SPEC:
765 for my $spec (@$specs) {
766 my $values = $options->{$spec->{dest}};
767  
768 if ($spec->{type} == TYPE_BOOL) {
769 _croak $self->error_prefix . 'Bool not allowed for positional arguments';
770 }
771  
772 my $number = 1;
773 my $nargs = defined $spec->{nargs} ? $spec->{nargs} : 1;
774 if (defined $spec->{nargs}) {
775 if ($nargs eq '?') {
776 $number = 1;
777 } elsif ($nargs eq '+') {
778 _croak $self->error_prefix . "Too few arguments: narg='+'" unless @{$self->{-argv}};
779 $number = scalar @{$self->{-argv}};
780 } elsif ($nargs eq '*') { # remainder
781 $number = scalar @{$self->{-argv}};
782 } elsif ($nargs !~ /^\d+$/) {
783 _croak $self->error_prefix . 'Invalid nargs:' . $nargs;
784 } else {
785 $number = $nargs;
786 }
787 }
788  
789 push @$values, splice(@{$self->{-argv}}, 0, $number) if @{$self->{-argv}};
790  
791 # If no values, let it pass for required checking
792 # If there are values, make sure there is the right number of
793 # values
794 if (scalar(@$values) && scalar(@$values) != $number) {
795 _croak($self->error_prefix . sprintf(
796 'Too few arguments for %s: expected:%d,actual:%d',
797 $spec->{dest}, $number, scalar(@$values),
798 )
799 );
800 }
801 }
802  
803 $self->_post_parse_processing($specs, $options, $dest2spec);
804  
805 $self->_apply_action($specs, $options, $dest2spec);
806  
807 $self->_post_apply_processing($specs, $options, $dest2spec);
808 }
809  
810 #
811 sub _post_parse_processing {
812 my $self = shift;
813 my ($option_specs, $options, $dest2spec) = @_;
814  
815 #
816 for my $spec ( @$option_specs ) {
817 my $values = $options->{ $dest2spec->{$spec->{dest}} };
818  
819 if (defined($values)) {
820 if (ref $values eq 'SCALAR') {
821 if (defined($$values)) {
822 $values = [ $$values ];
823 } else {
824 $values = [];
825 }
826 }
827 } else {
828 $values = [];
829 }
830  
831 $options->{ $dest2spec->{$spec->{dest}} } = $values;
832  
833 # default
834 if (!defined($self->namespace->get_attr($spec->{dest}))
835 && scalar(@$values) < 1
836 && defined($spec->{default}) )
837 {
838 if ($spec->{type} == TYPE_COUNT) {
839 $self->namespace->set_attr($spec->{dest}, @{$spec->{default}});
840 } elsif ($spec->{type} == TYPE_BOOL) {
841 $self->namespace->set_attr($spec->{dest}, @{$spec->{default}});
842 } elsif ($spec->{type} == TYPE_PAIR) {
843 $self->namespace->set_attr($spec->{dest}, $spec->{default});
844 } else {
845 push @$values, @{$spec->{default}};
846 }
847 }
848  
849 # split and expand
850 # Pair are processed here as well
851 if ( my $delimit = $spec->{split} ) {
852 my @expanded;
853 for my $v (@$values) {
854 push @expanded,
855 map {
856 $spec->{type} == TYPE_PAIR ? { split('=', $_) } : $_
857 } split($delimit, $v);
858 }
859  
860 $options->{ $dest2spec->{$spec->{dest} } } = \@expanded;
861 } else {
862 # Process PAIR only
863 if ($spec->{type} == TYPE_PAIR) {
864 $options->{ $dest2spec->{$spec->{dest} } }
865 = [ map { { split('=', $_) } } @$values ];
866 }
867 }
868  
869 # choices
870 if ( $spec->{choices} ) {
871 if (ref($spec->{choices}) eq 'CODE') {
872 for my $v (@$values) {
873 $spec->{choices}->($v);
874 }
875 } else {
876 my %choices =
877 map { defined($_) ? $_ : '_undef' => 1 }
878 @{$spec->{choices}};
879  
880 VALUE:
881 for my $v (@$values) {
882 my $k = defined($v) ? $v : '_undef';
883 next VALUE if exists $choices{$k};
884  
885 _croak $self->error_prefix . sprintf(
886 "Option %s value %s not in choices: [ %s ]",
887 $spec->{dest}, $v, join( ', ', @{ $spec->{choices} } ),
888 );
889 }
890 }
891 }
892  
893 if ( $spec->{choices_i} ) {
894 my %choices =
895 map { defined($_) ? uc($_) : '_undef' => 1 }
896 @{$spec->{choices_i}};
897  
898 VALUE:
899 for my $v (@$values) {
900 my $k = defined($v) ? uc($v) : '_undef';
901 next VALUE if exists $choices{$k};
902  
903 _croak $self->error_prefix . sprintf(
904 "Option %s value %s not in choices: [ %s ] (case insensitive)",
905 $spec->{dest}, $v, join( ', ', @{ $spec->{choices_i} } ),
906 );
907 }
908 }
909 }
910  
911 return '';
912 }
913  
914 sub _apply_action {
915 my $self = shift;
916 my ($specs, $options, $dest2spec) = @_;
917  
918 for my $spec (@$specs) {
919 # Init
920 # We want to preserve already set attributes if the namespace
921 # is passed in.
922 #
923 # This is because one may want to load configs from a file
924 # into a namespace and then use the same namespace for parsing
925 # configs from command line.
926 #
927 $self->namespace->set_attr($spec->{dest}, undef)
928 unless defined($self->namespace->get_attr($spec->{dest}));
929  
930 my $error = $spec->{action}->apply(
931 $spec,
932 $self->namespace,
933 $options->{ $dest2spec->{$spec->{dest}} },
934 $spec->{name},
935 );
936  
937 _croak $self->error_prefix . $error if $error;
938 }
939  
940 return '';
941 }
942  
943 sub _post_apply_processing {
944 my $self = shift;
945 my ($specs, $options, $dest2spec) = @_;
946  
947 #
948 # required is checked after applying actions
949 # This is because required checking is bypassed if help is on
950 #
951 for my $spec (@$specs) {
952 my $v = $self->namespace->get_attr($spec->{dest});
953  
954 # required
955 if ( $spec->{required} && not $self->namespace->get_attr('help') ) {
956 my $has_v;
957 if ($spec->{type} == TYPE_ARRAY) {
958 $has_v = @$v;
959 } elsif ($spec->{type} == TYPE_PAIR) {
960 $has_v = scalar(keys %$v);
961 } else {
962 $has_v = defined $v;
963 }
964  
965 _croak $self->error_prefix . sprintf("Option %s is required\n", $spec->{dest}) unless $has_v;
966 }
967 }
968 }
969  
970 # interface
971 sub print_usage {
972 my $self = shift;
973  
974 my $usage = $self->format_usage;
975  
976 print STDERR $_, "\n" for @$usage;
977 }
978  
979 # interface
980 sub print_command_usage {
981 my $self = shift;
982 my $command = shift
983 || $self->namespace->get_attr('help_command')
984 || $self->namespace->get_attr('current_command'); # running help command
985  
986 my $usage = $self->format_command_usage($command);
987 if ($usage) {
988 print STDERR $_, "\n" for @$usage;
989 } else {
990 print STDERR
991 $self->error_prefix,
992 sprintf('No help for %s. See help', $self->namespace->get_attr('help_command')),
993 "\n";
994 }
995 }
996  
997 # Interface
998 sub format_usage {
999 my $self = shift;
1000  
1001 $self->_sort_specs_by_groups() unless $self->{-groups};
1002  
1003 my $old_wrap_columns = $Text::Wrap::columns;
1004  
1005 my @usage;
1006  
1007 my $aliases = $self->aliases;
1008 my $prog = $self->prog;
1009 $prog .= ' (' . join(', ', @$aliases) . ')' if @$aliases;
1010 if( $self->help ) {
1011 push @usage, wrap('', '', $prog. ': ' . $self->help);
1012 push @usage, '';
1013 }
1014  
1015 my ($help, $option_string) = $self->_format_group_usage();
1016 $Text::Wrap::columns = 80;
1017  
1018 my $header = sprintf(
1019 'usage: %s %s',
1020 $self->prog, $option_string
1021 );
1022  
1023 push @usage, wrap('', '', $header);
1024  
1025 if ($self->description) {
1026 my @lines = split("\n", $self->description);
1027  
1028 my @paragraphs;
1029  
1030 my $para = '';
1031 for my $line (@lines) {
1032 if ($line =~ /^\s*$/) {
1033 push @paragraphs, $para;
1034 $para = '';
1035 } else {
1036 $para .= ( $para ? ' ' : '' ) . $line;
1037 }
1038 }
1039  
1040 push @paragraphs, $para;
1041 for (@paragraphs) {
1042 push @usage, '';
1043 push @usage, wrap('', '', $_);
1044 }
1045 }
1046  
1047 push @usage, @$help;
1048  
1049 if (exists $self->{-subparsers}) {
1050 push @usage, '';
1051 push @usage, wrap('', '', $self->{-subparsers}{-title});
1052 push @usage, wrap('', '', $self->{-subparsers}{-description}) if $self->{-subparsers}{-description};
1053  
1054 my $max = 12;
1055  
1056 for my $command ( keys %{$self->{-subparsers}{-parsers}} ) {
1057 my $len = length($command);
1058 $max = $len if $len > $max;
1059 }
1060  
1061 for my $command ( sort keys %{$self->{-subparsers}{-parsers}} ) {
1062 my $parser = $self->{-subparsers}{-parsers}{$command};
1063 my $tab_head = ' ' x ( $max + 2 );
1064  
1065 my @desc = split("\n", wrap('', '', $parser->help));
1066 my $desc = (shift @desc) || '';
1067 $_ = $tab_head . $_ for @desc;
1068 push @usage, sprintf(" %-${max}s %s", $command, join("\n", $desc, @desc));
1069 }
1070 }
1071  
1072 push @usage, '', wrap('', '', $self->epilog) if $self->epilog;
1073  
1074 $Text::Wrap::columns = $old_wrap_columns; # restore to original
1075  
1076 return \@usage;
1077 }
1078  
1079 sub format_command_usage {
1080 my $self = shift;
1081 my $alias = shift;
1082  
1083 my $subp = $self->_get_subcommand_parser($alias);
1084 return '' unless $subp;
1085  
1086 return $subp->format_usage();
1087 }
1088  
1089 # FIXME: Maybe we should remove this grouping thing
1090 sub _sort_specs_by_groups {
1091 my $self = shift;
1092  
1093 my $specs = $self->{-option_specs};
1094  
1095 for my $dest ( keys %{ $specs } ) {
1096 for my $group ( @{ $specs->{$dest}{groups} } ) {
1097 push @{ $self->{-groups}{$group}{-option} }, $specs->{$dest};
1098 }
1099 }
1100  
1101 $specs = $self->{-position_specs};
1102  
1103 for my $dest ( keys %{ $specs } ) {
1104 for my $group ( @{ $specs->{$dest}{groups} } ) {
1105 push @{ $self->{-groups}{$group}{-position} }, $specs->{$dest};
1106 }
1107 }
1108 }
1109  
1110 sub _format_group_usage {
1111 my $self = shift;
1112 my $group = '';
1113 # my $group = shift || '';
1114  
1115 unless ($self->{-groups}) {
1116 $self->_sort_specs_by_groups();
1117 }
1118  
1119 my $old_wrap_columns = $Text::Wrap::columns;
1120 $Text::Wrap::columns = 80;
1121  
1122 my @usage;
1123  
1124 my @option_specs = sort {
1125 $a->{position} <=> $b->{position}
1126 } @{ $self->{-groups}{$group}{-option} || [] };
1127  
1128 my @flag_items = map {
1129 ($_->{required} ? '' : '[')
1130 . join('|', @{$_->{flags}})
1131 . ($_->{required} ? '' : ']')
1132 } @option_specs;
1133  
1134 my @position_specs = sort {
1135 $a->{position} <=> $b->{position}
1136 } @{ $self->{-groups}{$group}{-position} || [] };
1137  
1138 my @position_items = map {
1139 ($_->{required} ? '' : '[')
1140 . $_->{metavar}
1141 . ($_->{required} ? '' : ']')
1142 } @position_specs;
1143  
1144 my @subcommand_items = ('<command>', '[<args>]') if exists $self->{-subparsers};
1145  
1146 if ($group) {
1147 push @usage, wrap('', '', $group . ': ' . ($self->{-group_description}{$group} || '') );
1148 }
1149  
1150 # named arguments are arguments preceded by a hyphen as optional
1151 # vs. positional are too confusing.
1152 for my $spec_name ( [ \@position_specs, 'positional' ], [ \@option_specs, 'named' ]) {
1153 my ($specs, $spec_name) = @$spec_name;
1154 for my $type_name ( [ PRINT_REQUIRED, 'required'], [ PRINT_OPTIONAL, 'optional'] ) {
1155 my ($type, $type_name) = @$type_name;
1156 my $output = $self->_format_usage_by_spec($specs, $type);
1157 if (@$output) {
1158 push @usage, '';
1159 # Start a section: e.g. required positional arguments:
1160 push @usage, sprintf('%s %s arguments:', $type_name, $spec_name);
1161 push @usage, @$output;
1162 }
1163 }
1164 }
1165  
1166 $Text::Wrap::columns = $old_wrap_columns; # restore to original
1167  
1168 return ( \@usage, join(' ', @position_items, @flag_items, @subcommand_items) ) ;
1169 }
1170  
1171 sub _format_usage_by_spec {
1172 my $self = shift;
1173 my $specs = shift;
1174 my $print_type = shift;
1175  
1176 return unless $specs;
1177  
1178 my @usage;
1179 my $max = 10;
1180 my @item_help;
1181  
1182 SPEC: for my $spec ( @$specs ) {
1183 next SPEC if ($print_type == PRINT_OPTIONAL && $spec->{'required'})
1184 || ($print_type == PRINT_REQUIRED && !$spec->{'required'});
1185  
1186 my $item = $spec->{metavar};
1187  
1188 if (@{$spec->{flags}}) {
1189 $item = sprintf(
1190 "%s %s",
1191 join(', ', @{$spec->{flags}}),
1192 $spec->{metavar},
1193 );
1194 }
1195 my $len = length($item);
1196 $max = $len if $len > $max;
1197  
1198 # generate default string
1199 my $default = '';
1200 my $values = [];
1201  
1202 if (defined $spec->{default}) {
1203 if (ref $spec->{default} eq 'HASH') {
1204 while (my ($k, $v) = each %{$spec->{default}}) {
1205 push @$values, "$k=$v";
1206 }
1207 } elsif (ref $spec->{default} eq 'ARRAY') {
1208 $values = $spec->{default};
1209 } else {
1210 $values = [ $spec->{default} ];
1211 }
1212 }
1213  
1214 if (@$values) {
1215 $default = 'Default: ' . join(', ', @$values);
1216 }
1217  
1218 # generate choice string
1219 my $choices;
1220 my $case = '';
1221  
1222 if ($spec->{choices} && ref $spec->{choices} ne 'CODE') {
1223 $choices = $spec->{choices};
1224 $case = 'case sensitive';
1225 } elsif ($spec->{choices_i}) {
1226 $choices = $spec->{choices_i};
1227 $case = 'case insensitive';
1228 } else {
1229 $choices = undef;
1230 }
1231  
1232 my $choice_str = '';
1233 if ($choices) {
1234 $choice_str = 'Choices: [' . join(', ', @$choices) . '], ' . $case . "\n";
1235 }
1236  
1237 push @item_help, [
1238 $item,
1239 ($spec->{required} ? ' ' : '?'),
1240 join("\n", ($spec->{help} || 'This is option ' . $spec->{dest}), $choice_str . $default),
1241 ];
1242 }
1243  
1244 my $format = " %-${max}s %s %s";
1245 $Text::Wrap::columns = 60;
1246 for my $ih (@item_help) {
1247 my $item_len = length($ih->[0]);
1248 # The prefixed whitespace in subsequent lines in the wrapped
1249 # help string
1250 my $sub_tab = " " x ($max + 4 + 4 + 2);
1251 my @help = split("\n", wrap('', '', $ih->[2]));
1252  
1253 my $help = (shift @help) || '' ; # head
1254 $_ = $sub_tab . $_ for @help; # tail
1255  
1256 push @usage, sprintf($format, $ih->[0], $ih->[1], join("\n", $help, @help));
1257 }
1258  
1259 return \@usage;
1260 }
1261  
1262 # translate option spec to the one accepted by
1263 # Getopt::Long::GetOptions
1264 sub _get_option_spec {
1265 my $self = shift;
1266 my $spec = shift;
1267  
1268 my @flags = @{ $spec->{flags} };
1269 $_ =~ s/^-+// for @flags;
1270 my $name = join('|', @flags);
1271 my $type = 's';
1272 my $desttype = '';
1273  
1274 my $optional_flag = '='; # not optional
1275  
1276 if ($spec->{type} == TYPE_SCALAR) {
1277 $desttype = '@';
1278 } elsif ($spec->{type} == TYPE_ARRAY) {
1279 $desttype = '@';
1280 } elsif ($spec->{type} == TYPE_PAIR) {
1281 $desttype = '@';
1282 } elsif ($spec->{type} == TYPE_UNDEF) {
1283 $optional_flag = ':';
1284 } elsif ($spec->{type} == TYPE_BOOL) {
1285 $type = '';
1286 $optional_flag = '';
1287 $desttype = '';
1288 } elsif ($spec->{type} == TYPE_COUNT) {
1289 # pass
1290 $type = '';
1291 $optional_flag = '';
1292 $desttype = '+';
1293 } else {
1294 # pass
1295 # should never be here
1296 _croak $self->error_prefix . 'Unknown type:' . ($spec->{type} || 'undef');
1297 }
1298  
1299 my $repeat = '';
1300  
1301 my $opt = join('', $name, $optional_flag, $type, $repeat, $desttype);
1302  
1303 return $opt;
1304 }
1305  
1306 1;
1307  
1308 __END__