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