File Coverage

blib/lib/Getopt/Long/Descriptive.pm
Criterion Covered Total %
statement 234 324 72.2
branch 77 140 55.0
condition 38 63 60.3
subroutine 33 40 82.5
pod 3 3 100.0
total 385 570 67.5


line stmt bran cond sub pod time code
1 2     2   149484 use strict;
  2         4  
  2         83  
2 2     2   11 use warnings;
  2         7  
  2         151  
3             package Getopt::Long::Descriptive 0.117;
4             # ABSTRACT: Getopt::Long, but simpler and more powerful
5              
6 2     2   35 use v5.12;
  2         9  
7              
8 2     2   13 use Carp qw(carp croak);
  2         4  
  2         188  
9 2     2   15 use File::Basename ();
  2         5  
  2         67  
10 2     2   1632 use Getopt::Long 2.55;
  2         36364  
  2         55  
11 2     2   346 use List::Util qw(first);
  2         4  
  2         195  
12 2     2   1085 use Params::Validate 0.97 qw(:all);
  2         16203  
  2         402  
13 2     2   20 use Scalar::Util ();
  2         3  
  2         45  
14              
15 2     2   1086 use Getopt::Long::Descriptive::Opts;
  2         7  
  2         65  
16 2     2   961 use Getopt::Long::Descriptive::Usage;
  2         6  
  2         310  
17              
18             #pod =head1 SYNOPSIS
19             #pod
20             #pod use Getopt::Long::Descriptive;
21             #pod
22             #pod my ($opt, $usage) = describe_options(
23             #pod 'my-program %o ',
24             #pod [ 'server|s=s', "the server to connect to", { required => 1 } ],
25             #pod [ 'port|p=i', "the port to connect to", { default => 79 } ],
26             #pod [],
27             #pod [ 'verbose|v', "print extra stuff" ],
28             #pod [ 'help', "print usage message and exit", { shortcircuit => 1 } ],
29             #pod );
30             #pod
31             #pod print($usage->text), exit if $opt->help;
32             #pod
33             #pod Client->connect( $opt->server, $opt->port );
34             #pod
35             #pod print "Connected!\n" if $opt->verbose;
36             #pod
37             #pod ...and running C will produce:
38             #pod
39             #pod my-program [-psv] [long options...]
40             #pod -s --server the server to connect to
41             #pod -p --port the port to connect to
42             #pod
43             #pod -v --verbose print extra stuff
44             #pod --help print usage message and exit
45             #pod
46             #pod =head1 DESCRIPTION
47             #pod
48             #pod Getopt::Long::Descriptive is yet another Getopt library. It's built atop
49             #pod Getopt::Long, and gets a lot of its features, but tries to avoid making you
50             #pod think about its huge array of options.
51             #pod
52             #pod It also provides usage (help) messages, data validation, and a few other useful
53             #pod features.
54             #pod
55             #pod =head1 FUNCTIONS
56             #pod
57             #pod Getopt::Long::Descriptive only exports one routine by default:
58             #pod C. All GLD's exports are exported by L.
59             #pod
60             #pod =head2 describe_options
61             #pod
62             #pod my ($opt, $usage) = describe_options($usage_desc, @opt_spec, \%arg);
63             #pod
64             #pod This routine inspects C<@ARGV> for options that match the supplied spec. If all
65             #pod the options are valid then it returns the options given and an object for
66             #pod generating usage messages; if not then it dies with an explanation of what was
67             #pod wrong and a usage message.
68             #pod
69             #pod The C<$opt> object will be a dynamically-generated subclass of
70             #pod L. In brief, each of the options in
71             #pod C<@opt_spec> becomes an accessor method on the object, using the first-given
72             #pod name, with dashes converted to underscores. For more information, see the
73             #pod documentation for the Opts class.
74             #pod
75             #pod The C<$usage> object will be a L object,
76             #pod which provides a C method to get the text of the usage message and C
77             #pod to die with it. For more methods and options, consults the documentation for
78             #pod the Usage class.
79             #pod
80             #pod =head3 $usage_desc
81             #pod
82             #pod The C<$usage_desc> parameter to C is a C-like string
83             #pod that is used in generating the first line of the usage message. It's a
84             #pod one-line summary of how the command is to be invoked. A typical usage
85             #pod description might be:
86             #pod
87             #pod $usage_desc = "%c %o ";
88             #pod
89             #pod C<%c> will be replaced with what Getopt::Long::Descriptive thinks is the
90             #pod program name (it's computed from C<$0>, see L).
91             #pod
92             #pod C<%o> will be replaced with a list of the short options, as well as the text
93             #pod "[long options...]" if any have been defined.
94             #pod
95             #pod The rest of the usage description can be used to summarize what arguments are
96             #pod expected to follow the program's options, and is entirely free-form.
97             #pod
98             #pod Literal C<%> characters will need to be written as C<%%>, just like with
99             #pod C.
100             #pod
101             #pod =head3 @opt_spec
102             #pod
103             #pod The C<@opt_spec> part of the args to C is used to configure
104             #pod option parsing and to produce the usage message. Each entry in the list is an
105             #pod arrayref describing one option, like this:
106             #pod
107             #pod @opt_spec = (
108             #pod [ "verbose|V" => "be noisy" ],
109             #pod [ "logfile=s" => "file to log to" ],
110             #pod );
111             #pod
112             #pod The first value in the arrayref is a Getopt::Long-style option specification.
113             #pod In brief, they work like this: each one is a pipe-delimited list of names,
114             #pod optionally followed by a type declaration. Type declarations are '=x' or ':x',
115             #pod where C<=> means a value is required and C<:> means it is optional. I may
116             #pod be 's' to indicate a string is required, 'i' for an integer, or 'f' for a
117             #pod number with a fractional part. The type spec may end in C<@> to indicate that
118             #pod the option may appear multiple times.
119             #pod
120             #pod For more information on how these work, see the L documentation.
121             #pod
122             #pod The first name given should be the canonical name, as it will be used as the
123             #pod accessor method on the C<$opt> object. Dashes in the name will be converted to
124             #pod underscores, and all letters will be lowercased. For this reason, all options
125             #pod should generally have a long-form name.
126             #pod
127             #pod The second value in the arrayref is a description of the option, for use in the
128             #pod usage message.
129             #pod
130             #pod =head4 Special Option Specifications
131             #pod
132             #pod If the option specification (arrayref) is empty, it will have no effect other
133             #pod than causing a blank line to appear in the usage message.
134             #pod
135             #pod If the option specification contains only one element, it will be printed in
136             #pod the usage message with no other effect. If the element is a reference, its
137             #pod referent will be printed as-is. Otherwise, it will be reformatted like other
138             #pod text in the usage message.
139             #pod
140             #pod If the option specification contains a third element, it adds extra constraints
141             #pod or modifiers to the interpretation and validation of the value. These are the
142             #pod keys that may be present in that hashref, and how they behave:
143             #pod
144             #pod =over 4
145             #pod
146             #pod =item implies
147             #pod
148             #pod implies => 'bar'
149             #pod implies => [qw(foo bar)]
150             #pod implies => { foo => 1, bar => 2 }
151             #pod
152             #pod If option I has an "implies" entry, then if I is given, other options
153             #pod will be enabled. The value may be a single option to set, an arrayref of
154             #pod options to set, or a hashref of options to set to specific values.
155             #pod
156             #pod =item required
157             #pod
158             #pod required => 1
159             #pod
160             #pod If an option is required, failure to provide the option will result in
161             #pod C printing the usage message and exiting.
162             #pod
163             #pod =item hidden
164             #pod
165             #pod hidden => 1
166             #pod
167             #pod This option will not show up in the usage text.
168             #pod
169             #pod You can achieve the same behavior by using the string "hidden" for the option's
170             #pod description.
171             #pod
172             #pod =item one_of
173             #pod
174             #pod one_of => \@subopt_specs
175             #pod
176             #pod This is useful for a group of options that are related. Each option
177             #pod spec is added to the list for normal parsing and validation.
178             #pod
179             #pod Your option name will end up with a value of the name of the
180             #pod option that was chosen. For example, given the following spec:
181             #pod
182             #pod [ "mode" => hidden => { one_of => [
183             #pod [ "get|g" => "get the value" ],
184             #pod [ "set|s" => "set the value" ],
185             #pod [ "delete" => "delete it" ],
186             #pod ] } ],
187             #pod
188             #pod No usage text for 'mode' will be displayed, but text for get, set, and delete
189             #pod will be displayed.
190             #pod
191             #pod If more than one of get, set, or delete is given, an error will be thrown.
192             #pod
193             #pod So, given the C<@opt_spec> above, and an C<@ARGV> of C<('--get')>, the
194             #pod following would be true:
195             #pod
196             #pod $opt->get == 1;
197             #pod
198             #pod $opt->mode eq 'get';
199             #pod
200             #pod B: C would not be set if C defaulted to 'get' and no arguments
201             #pod were passed in.
202             #pod
203             #pod Even though the option sub-specs for C are meant to be 'first
204             #pod class' specs, some options don't make sense with them, e.g. C.
205             #pod
206             #pod As a further shorthand, you may specify C options using this form:
207             #pod
208             #pod [ mode => \@option_specs, \%constraints ]
209             #pod
210             #pod
211             #pod =item shortcircuit
212             #pod
213             #pod shortcircuit => 1
214             #pod
215             #pod If this option is present no other options will be returned. Other
216             #pod options present will be checked for proper types, but I for
217             #pod constraints. This provides a way of specifying C<--help> style options.
218             #pod
219             #pod =item Params::Validate
220             #pod
221             #pod In addition, any constraint understood by Params::Validate may be used.
222             #pod
223             #pod For example, to accept positive integers:
224             #pod
225             #pod [ 'max-iterations=i', "maximum number of iterations",
226             #pod { callbacks => { positive => sub { shift() > 0 } } } ],
227             #pod
228             #pod (Internally, all constraints are translated into Params::Validate options or
229             #pod callbacks.)
230             #pod
231             #pod =back
232             #pod
233             #pod =head3 %arg
234             #pod
235             #pod The C<%arg> to C is optional. If the last parameter is a
236             #pod hashref, it contains extra arguments to modify the way C
237             #pod works. Valid arguments are:
238             #pod
239             #pod getopt_conf - an arrayref of strings, passed to Getopt::Long::Configure
240             #pod show_defaults - a boolean which controls whether an option's default
241             #pod value (if applicable) is shown as part of the usage message
242             #pod (for backward compatibility this defaults to false)
243             #pod
244             #pod =head2 prog_name
245             #pod
246             #pod This routine, exported on demand, returns the basename of C<$0>, grabbed at
247             #pod compile-time. You can override this guess by calling C
248             #pod yourself.
249             #pod
250             #pod =head1 OTHER EXPORTS
251             #pod
252             #pod =head2 C<-types>
253             #pod
254             #pod Any of the Params::Validate type constants (C, etc.) can be imported as
255             #pod well. You can get all of them at once by importing C<-types>.
256             #pod
257             #pod =head2 C<-all>
258             #pod
259             #pod This import group will import C<-type>, C, and C.
260             #pod
261             #pod =cut
262              
263             my $prog_name;
264 33 100   33 1 281 sub prog_name { @_ ? ($prog_name = shift) : $prog_name }
265              
266             BEGIN {
267             # grab this before someone decides to change it
268 2     2   148 prog_name(File::Basename::basename($0));
269             }
270              
271 2     2   985 use Sub::Exporter::Util ();
  2         31993  
  2         181  
272             use Sub::Exporter 0.972 -setup => {
273             exports => [
274             describe_options => \'_build_describe_options',
275             q(prog_name),
276 2         26 @{ $Params::Validate::EXPORT_TAGS{types} }
277             ],
278             groups => [
279             default => [ qw(describe_options) ],
280             types => $Params::Validate::EXPORT_TAGS{types},
281 2         7 ],
282 2     2   17 };
  2         30  
283              
284             my %CONSTRAINT = (
285             implies => \&_mk_implies,
286             only_one => \&_mk_only_one,
287             );
288              
289             our $MungeOptions = 1;
290              
291             our $TERM_WIDTH;
292             {
293             $TERM_WIDTH = $ENV{COLUMNS} || 80;
294              
295             # So, this was the old code:
296             #
297             # if (eval { require Term::ReadKey; 1 }) {
298             # my ($width) = Term::ReadKey::GetTerminalSize();
299             # $TERM_WIDTH = $width;
300             # } else {
301             # $TERM_WIDTH = $ENV{COLUMNS} || 80;
302             # }
303             #
304             # ...but the problem is that Term::ReadKey will carp when it can't get an
305             # answer, it can't be trivially made to keep quiet. (I decline to stick a
306             # local $SIG{__WARN__} here, as it's too heavy a hammer.) With the new (as
307             # of 2021-03) formatting code, using the full width is less of an issue,
308             # anyway.
309             }
310              
311             sub _nohidden {
312 62     62   119 return grep { ! $_->{constraint}->{hidden} } @_;
  204         644  
313             }
314              
315             sub _expand {
316 39     39   71 my @expanded;
317              
318 39         86 for my $opt (@_) {
319 112 100 100     929 push @expanded, {
    100 100        
      50        
320             spec => $opt->[0] || '',
321             desc => @$opt > 1 ? $opt->[1] : 'spacer',
322             constraint => $opt->[2] || {},
323              
324             # if @$_ is 0 then we got [], a spacer
325             name => @$opt ? _munge((split /[:=|!+]/, $opt->[0] || '')[0]) : '',
326             };
327             }
328              
329 39         141 return @expanded;
330             }
331              
332             my %HIDDEN = (
333             hidden => 1,
334             );
335              
336             my $SPEC_RE = qr{(?:[:=][0-9\w\+]+[%@]?(\{[0-9]*,[0-9]*\})?|[!+])$};
337             sub _strip_assignment {
338 171     171   345 my ($self, $str) = @_;
339              
340 171         1270 (my $copy = $str) =~ s{$SPEC_RE}{};
341              
342 171 100       429 if (wantarray) {
343 84         149 my $len = length $copy;
344 84   50     224 my $assignment = substr($str, $len) // q{};
345              
346 84         293 return ($copy, $assignment);
347             }
348 87         207 return $copy;
349             }
350              
351             # This is here only to deal with people who were calling this fully-qualified
352             # without importing. Sucks to them! -- rjbs, 2009-08-21
353             sub describe_options {
354 0     0 1 0 my $sub = __PACKAGE__->_build_describe_options(describe_options => {} => {});
355 0         0 $sub->(@_);
356             }
357              
358 31     31 1 89 sub usage_class { 'Getopt::Long::Descriptive::Usage' }
359              
360             sub _build_describe_options {
361 2     2   473 my ($class) = @_;
362              
363             sub {
364 31 100   31   918378 my $format = (ref $_[0] ? '%c %o' : shift(@_));
365 31 100 66     202 my $arg = (ref $_[-1] and ref $_[-1] eq 'HASH') ? pop @_ : {};
366              
367             # If GETOPT_LONG_DESCRIPTIVE_COMPLETION is set, emit a shell completion
368             # script to stdout and exit 42. Supported values are 'bash' and 'zsh'.
369             # Any other value raises an exception. If
370             # GETOPT_LONG_DESCRIPTIVE_COMPLETION_NAME is set, it is treated as a
371             # comma-separated list of command names to register completion for,
372             # overriding the script name. -- claude, 2026-02-19
373 31 50       120 if (my $shell = $ENV{GETOPT_LONG_DESCRIPTIVE_COMPLETION}) {
374 0 0       0 if ($shell eq 'bash') {
    0          
375 0         0 print _bash_completion_script(@_);
376 0         0 exit 42;
377             } elsif ($shell eq 'zsh') {
378 0         0 print _zsh_completion_script(@_);
379 0         0 exit 42;
380             } else {
381 0         0 Carp::croak("unknown shell '$shell' in GETOPT_LONG_DESCRIPTIVE_COMPLETION");
382             }
383             }
384              
385 31         96 my @opts;
386              
387             my %parent_of;
388              
389             # special casing
390             # wish we had real loop objects
391 31         0 my %method_map;
392 31         163 for my $opt (_expand(@_)) {
393 92 100       307 $method_map{ $opt->{name} } = undef unless $opt->{desc} eq 'spacer';
394              
395 92 100       197 if (ref($opt->{desc}) eq 'ARRAY') {
396 5         18 $opt->{constraint}->{one_of} = delete $opt->{desc};
397 5         11 $opt->{desc} = 'hidden';
398             }
399              
400 92 100       206 if ($HIDDEN{$opt->{desc}}) {
401 6         20 $opt->{constraint}->{hidden}++;
402             }
403              
404 92 100       181 if ($opt->{constraint}->{one_of}) {
405 6         13 for my $one_opt (_expand(
406 6         20 @{delete $opt->{constraint}->{one_of}}
407             )) {
408 10         31 $parent_of{$one_opt->{name}} = $opt->{name};
409             $one_opt->{constraint}->{implies}
410 10         36 ->{$opt->{name}} = $one_opt->{name};
411 10         21 for my $wipe (qw(required default)) {
412 20 50       55 if ($one_opt->{constraint}->{$wipe}) {
413 0         0 carp "'$wipe' constraint does not make sense in sub-option";
414 0         0 delete $one_opt->{constraint}->{$wipe};
415             }
416             }
417 10         22 $one_opt->{constraint}->{one_of} = $opt->{name};
418 10         21 push @opts, $one_opt;
419              
420             # Ensure that we generate accessors for all one_of sub-options
421             $method_map{ $one_opt->{name} } = undef
422 10 50       52 unless $one_opt->{desc} eq 'spacer';
423             }
424             }
425              
426 92 100 100     197 if ($opt->{constraint}{shortcircuit}
427             && exists $opt->{constraint}{default}
428             ) {
429 1         152 carp('option "' . $opt->{name} . q[": 'default' does not make sense for shortcircuit options]);
430             }
431              
432 92         159 push @opts, $opt;
433             }
434              
435 31 50 66     58 my @go_conf = @{ $arg->{getopt_conf} || $arg->{getopt} || [] };
  31         200  
436 31 50       111 if ($arg->{getopt}) {
437 0         0 warn "describe_options: 'getopt' is deprecated, please use 'getopt_conf' instead\n";
438             }
439              
440 31 50       98 push @go_conf, "bundling" unless grep { /bundling/i } @go_conf;
  1         11  
441 31 50       69 push @go_conf, "no_auto_help" unless grep { /no_auto_help/i } @go_conf;
  32         128  
442             push @go_conf, "no_ignore_case"
443 31 50       83 unless grep { /no_ignore_case/i } @go_conf;
  63         154  
444              
445             # not entirely sure that all of this (until the Usage->new) shouldn't be
446             # moved into Usage -- rjbs, 2009-08-19
447              
448             # all specs including hidden
449             my @getopt_specs =
450 95         191 map { $_->{spec} }
451 31         64 grep { $_->{desc} ne 'spacer' }
  102         200  
452             @opts;
453              
454             my @specs =
455 87         168 map { $_->{spec} }
456 31         99 grep { $_->{desc} ne 'spacer' }
  94         182  
457             _nohidden(@opts);
458              
459             my @options =
460 87         196 map { split /\|/ }
461 31         64 map { scalar __PACKAGE__->_strip_assignment($_) }
  87         213  
462             @specs;
463              
464 31         86 my %opt_count;
465 31         205 $opt_count{$_}++ for @options;
466              
467             my $short = join q{},
468 22 50       90 sort { lc $a cmp lc $b or $a cmp $b }
469 31         69 grep { /^.$/ }
  101         264  
470             @options;
471              
472 31         177 my $long = grep /\b[^|]{2,}/, @specs;
473              
474 31 100       122 my %replace = (
    100          
475             "%" => "%",
476             "c" => prog_name,
477             "o" => join(q{ },
478             ($short ? "[-$short]" : ()),
479             ($long ? "[long options...]" : ())
480             ),
481             );
482              
483 31         214 (my $str = $format) =~ s<%(.)><
484 44   33     243 $replace{$1}
485             // Carp::croak("unknown sequence %$1 in first argument to describe_options")
486             >ge;
487              
488 31         135 $str =~ s/[\x20\t]{2,}/ /g;
489              
490             my $usage = $class->usage_class->new({
491             options => [ _nohidden(@opts) ],
492             leader_text => $str,
493             show_defaults => $arg->{show_defaults},
494 31         95 });
495              
496 31         180 my $old_go_conf = Getopt::Long::Configure(@go_conf);
497              
498 31         2164 my %return;
499 31 50       106 $usage->die unless GetOptions(\%return, grep { length } @getopt_specs);
  95         208  
500 31         11507 my @given_keys = keys %return;
501              
502 31         124 Getopt::Long::Configure($old_go_conf);
503              
504 31         696 for my $opt (keys %return) {
505 28         60 my $newopt = _munge($opt);
506 28 100       78 next if $newopt eq $opt;
507 1         5 $return{$newopt} = delete $return{$opt};
508             }
509              
510             # ensure that shortcircuit options are handled first
511 31         76 for my $copt (
512             sort { ($b->{constraint}{shortcircuit} || 0)
513 118   100     489 <=> ($a->{constraint}{shortcircuit} || 0)
      50        
514 102         263 } grep { $_->{constraint} } @opts
515             ) {
516 77         168 delete $copt->{constraint}->{hidden};
517 77         196 my $is_shortcircuit = delete $copt->{constraint}{shortcircuit};
518 77         164 my $name = $copt->{name};
519             my $new = _validate_with(
520             name => $name,
521             params => \%return,
522             spec => $copt->{constraint},
523 77         260 opts => \@opts,
524             usage => $usage,
525             given_keys => \@given_keys,
526             parent_of => \%parent_of,
527             );
528 74 50 66     300 next unless defined $new || exists $return{$name};
529 29         59 $return{$name} = $new;
530              
531 29 100       79 if ($is_shortcircuit) {
532 3         5 %return = ($name => $return{$name});
533 3         30 last;
534             }
535             }
536              
537             my $opt_obj = Getopt::Long::Descriptive::Opts->___new_opt_obj({
538             values => { %method_map, %return },
539 28         222 given => { map {; $_ => 1 } @given_keys },
  26         123  
540             });
541              
542 28         411 return($opt_obj, $usage);
543             }
544 2         26 }
545              
546             sub _munge {
547 134     134   244 my ($opt) = @_;
548 134 50       270 return $opt unless $MungeOptions;
549 134         222 $opt = lc($opt);
550 134         227 $opt =~ tr/-/_/;
551 134         581 return $opt;
552             }
553              
554             sub _validate_with {
555 77     77   2247 my (%arg) = validate(@_, {
556             name => 1,
557             params => 1,
558             spec => 1,
559             opts => 1,
560             usage => 1,
561             given_keys => 1,
562             parent_of => 1,
563             });
564              
565 77         634 my $spec = $arg{spec};
566 77         124 my %pvspec;
567 77         128 SPEC_ENTRY: for my $ct (keys %{$spec}) {
  77         224  
568 40 100       137 if ($ct eq 'required') {
569             # This used to be in %CONSTRAINT but this whole system is a bit
570             # overcomplex, I think, and moving this here makes life simpler. Someday
571             # (ha ha) this can all be overhauled. -- rjbs, 2024-01-20
572 9         18 $pvspec{optional} = ! $spec->{$ct};
573 9         18 next SPEC_ENTRY;
574             }
575              
576 31 100 66     121 if ($CONSTRAINT{$ct} and ref $CONSTRAINT{$ct} eq 'CODE') {
577 11   50     91 $pvspec{callbacks} ||= {};
578             $pvspec{callbacks} = {
579 11         53 %{$pvspec{callbacks}},
580             $CONSTRAINT{$ct}->(
581             $arg{name},
582             $spec->{$ct},
583             $arg{params},
584             $arg{opts},
585 11         19 ),
586             };
587             } else {
588             %pvspec = (
589             %pvspec,
590 20 50       84 $CONSTRAINT{$ct} ? %{$CONSTRAINT{$ct}} : ($ct => $spec->{$ct}),
  0         0  
591             );
592             }
593             }
594              
595 77 100       266 $pvspec{optional} = 1 unless exists $pvspec{optional};
596              
597             # we need to implement 'default' by ourselves sometimes
598             # because otherwise the implies won't be checked/executed
599             # XXX this should be more generic -- we'll probably want
600             # other callbacks to always run, too
601 77 50 100     382 if (!defined($arg{params}{$arg{name}})
      66        
602             && $pvspec{default}
603             && $spec->{implies}) {
604              
605 0         0 $arg{params}{$arg{name}} = delete $pvspec{default};
606             }
607              
608 77         175 my %p;
609 77         146 my $ok = eval {
610             %p = validate_with(
611             params => [
612 77         1831 %{$arg{params}},
613             '-given_keys', $arg{given_keys},
614             '-parent_of', $arg{parent_of},
615             ],
616             spec => { $arg{name} => \%pvspec },
617             allow_extra => 1,
618             on_fail => sub {
619 3     3   8 my $fail_msg = shift;
620 3         22 Getopt::Long::Descriptive::_PV_Error->throw($fail_msg);
621             },
622 77         145 );
623 74         659 1;
624             };
625              
626 77 100       217 if (! $ok) {
627 3         7 my $error = $@;
628 3 50 33     31 if (
629             Scalar::Util::blessed($error)
630             && $error->isa('Getopt::Long::Descriptive::_PV_Error')
631             ) {
632 3         10 $arg{usage}->die({ pre_text => $error->error . "\n" });
633             }
634              
635 0         0 die $@;
636             }
637              
638 74         477 return $p{$arg{name}};
639             }
640              
641             # scalar: single option = true
642             # arrayref: multiple options = true
643             # hashref: single/multiple options = given values
644             sub _norm_imply {
645 11     11   26 my ($what) = @_;
646              
647 11 100       38 return { $what => 1 } unless my $ref = ref $what;
648              
649 9 50       36 return $what if $ref eq 'HASH';
650 0 0       0 return { map { $_ => 1 } @$what } if $ref eq 'ARRAY';
  0         0  
651              
652 0         0 die "can't imply: $what";
653             }
654              
655             sub _mk_implies {
656 11     11   24 my $name = shift;
657 11         27 my $what = _norm_imply(shift);
658 11         20 my $param = shift;
659 11         23 my $opts = shift;
660              
661 11         30 for my $implied (keys %$what) {
662             die("option specification for $name implies nonexistent option $implied\n")
663 11 50   29   114 unless first { $_->{name} eq $implied } @$opts
  29         98  
664             }
665              
666 11         32 my $whatstr = join(q{, }, map { "$_=$what->{$_}" } keys %$what);
  11         56  
667              
668             return "$name implies $whatstr" => sub {
669 6     6   20 my ($pv_val, $rest) = @_;
670              
671             # negatable options will be 0 here, which is ok.
672 6 50       17 return 1 unless defined $pv_val;
673              
674 6         29 while (my ($key, $val) = each %$what) {
675             # Really, this should be called "-implies" and should include all implies
676             # relationships, but they'll have to get handled by setting conflicts.
677 6         15 my $parent = $rest->{'-parent_of'}{$name};
678             my @siblings = $parent
679             ? (grep {; defined $rest->{'-parent_of'}{$_}
680 6 100       38 && $rest->{'-parent_of'}{$_} eq $parent }
681 6 100       67 @{ $rest->{'-given_keys'} })
  4         14  
682             : ();
683              
684 6 100       20 if (@siblings > 1) {
685 1         18 die "these options conflict; each wants to set the $parent: @siblings\n";
686             }
687              
688 5 50 66     22 if ( exists $param->{$key}
      66        
689             and $param->{$key} ne $val
690 1         36 and grep {; $_ eq $key } @{ $rest->{'-given_keys'} }
  1         4  
691             ) {
692 0         0 die(
693             "option specification for $name implies that $key should be "
694             . "set to '$val', but it is '$param->{$key}' already\n"
695             );
696             }
697 5         27 $param->{$key} = $val;
698             }
699              
700 5         57 return 1;
701 11         132 };
702             }
703              
704             sub _mk_only_one {
705 0     0   0 die "unimplemented";
706             }
707              
708             # Parse the opt_spec list (same format as describe_options) into a list of
709             # hashrefs suitable for generating completion data. Hidden and spacer entries
710             # are omitted. one_of grouping options are transparent: the outer option is
711             # skipped and its sub-options are included in its place.
712             sub _parse_specs_for_completion {
713 2 50   2   11 pop if ref $_[-1] eq 'HASH';
714 2         3 my @parsed;
715              
716 2         7 for my $opt (_expand(@_)) {
717 10 100       32 next if $opt->{desc} eq 'spacer'; # skip spacers and display-only text entries
718              
719 4         38 my $constraint = $opt->{constraint};
720              
721             # one_of comes in two forms:
722             # Form 1: [ 'group', [ [inner specs...] ] ] -- desc is the arrayref
723             # Form 2: [ 'group', 'desc', { one_of => [...] } ] -- explicit constraint
724             # In both cases suppress the outer option and recurse into the sub-options.
725 4 50       14 if (ref($opt->{desc}) eq 'ARRAY') {
726 0         0 push @parsed, _parse_specs_for_completion(@{ $opt->{desc} });
  0         0  
727 0         0 next;
728             }
729              
730 4 50       11 if (ref($constraint->{one_of}) eq 'ARRAY') {
731 0         0 push @parsed, _parse_specs_for_completion(@{ $constraint->{one_of} });
  0         0  
732 0         0 next;
733             }
734              
735 4 50 50     26 next if $constraint->{hidden} || ($opt->{desc} // '') eq 'hidden';
      33        
736              
737 4         14 my ($names_str, $assignment) = __PACKAGE__->_strip_assignment($opt->{spec});
738              
739             push @parsed, {
740             names => [ split /\|/, $names_str ],
741             takes_value => !!($assignment =~ /\A[:=]/),
742             negatable => !!($assignment =~ /\A!/),
743             desc => $opt->{desc},
744             completion => $constraint->{completion},
745 4         51 };
746             }
747              
748 2         17 return @parsed;
749             }
750              
751             sub _bash_completion_action {
752 0     0   0 my ($completion) = @_;
753              
754 0 0       0 if (ref $completion eq 'ARRAY') {
755 0 0       0 return undef unless @$completion;
756 0         0 my $vals = join q{ }, @$completion;
757 0         0 return qq{COMPREPLY=(\$(compgen -W "$vals" -- "\$cur"))};
758             }
759              
760 0 0       0 return q{COMPREPLY=($(compgen -f -- "$cur"))} if $completion eq 'files';
761 0 0       0 return q{COMPREPLY=($(compgen -d -- "$cur"))} if $completion eq 'dirs';
762              
763 0 0       0 if ($completion =~ /\Afn:(.+)\z/) {
764 0         0 return qq{COMPREPLY=(\$($1 "\$cur"))};
765             }
766              
767 0         0 return undef;
768             }
769              
770             sub _zsh_completion_action {
771 0     0   0 my ($completion) = @_;
772              
773 0 0       0 return '_files' if $completion eq 'files';
774 0 0       0 return '_files -/' if $completion eq 'dirs';
775              
776 0 0       0 if (ref $completion eq 'ARRAY') {
777 0         0 return '(' . join(' ', @$completion) . ')';
778             }
779              
780 0 0       0 if ($completion =~ /\Afn:(.+)\z/) {
781 0         0 return $1;
782             }
783              
784 0         0 return '';
785             }
786              
787             # _completion_for_bash(\@opt_spec)
788             #
789             # Given an @opt_spec in the same format as describe_options, returns a hashref
790             # describing bash completion for those options.
791             #
792             # The 'flags' key holds a space-separated string of all option flags, suitable
793             # for passing to compgen -W.
794             #
795             # The 'prev_cases' key holds an arrayref of hashrefs, each with a 'pattern'
796             # (suitable for a case "$prev" arm) and an 'action' (bash code that sets
797             # COMPREPLY). Only options that carry a 'completion' key in their constraint
798             # hashref produce a prev_case entry.
799             #
800             # The 'completion' key in an option's constraint hashref may be:
801             # - an arrayref: completes from a fixed list
802             # - 'files': completes to file paths
803             # - 'dirs': completes to directory paths
804             # - 'fn:NAME': delegates to the named shell function; $cur is available
805             # in the environment
806             sub _completion_for_bash {
807 1     1   2826 my (@specs) = @_;
808              
809 1         4 my @flags;
810             my @prev_cases;
811              
812 1         5 for my $p (_parse_specs_for_completion(@specs)) {
813 2         5 for my $name (@{ $p->{names} }) {
  2         6  
814 2 50       10 push @flags, length($name) == 1 ? "-$name" : "--$name";
815 2 50 33     9 push @flags, "--no-$name" if $p->{negatable} && length($name) > 1;
816             }
817              
818 2 50 33     7 if ($p->{takes_value} && defined $p->{completion}) {
819 0         0 my $action = _bash_completion_action($p->{completion});
820 0 0       0 if (defined $action) {
821             my $pattern = join '|',
822 0 0       0 map { length($_) == 1 ? "-$_" : "--$_" } @{ $p->{names} };
  0         0  
  0         0  
823 0         0 push @prev_cases, { pattern => $pattern, action => $action };
824             }
825             }
826             }
827              
828             return {
829 1         12 flags => join(' ', @flags),
830             prev_cases => \@prev_cases,
831             };
832             }
833              
834             # _completion_for_zsh(@opt_spec)
835             #
836             # Given an @opt_spec in the same format as describe_options, returns a list of
837             # strings in _arguments spec format for use in a zsh completion function.
838             # Each string describes one option flag. The 'completion' constraint key is
839             # supported with the same values as _completion_for_bash.
840             sub _completion_for_zsh {
841 1     1   1071 my (@specs) = @_;
842              
843 1         3 my @args;
844 1         4 for my $p (_parse_specs_for_completion(@specs)) {
845 2   50     8 my $safe_desc = $p->{desc} // '';
846 2         7 $safe_desc =~ s/\[/\\[/g;
847 2         6 $safe_desc =~ s/\]/\\]/g;
848 2         5 $safe_desc =~ s/'/'\\''/g;
849              
850 2         3 for my $name (@{ $p->{names} }) {
  2         8  
851 2 50       8 my $flag = length($name) == 1 ? "-$name" : "--$name";
852 2 50       6 if ($p->{takes_value}) {
853             my $action = defined $p->{completion}
854             ? _zsh_completion_action($p->{completion})
855 0 0       0 : '';
856 0         0 push @args, qq('${flag}=[${safe_desc}]: :${action}');
857             } else {
858 2         7 push @args, qq('${flag}[${safe_desc}]');
859             }
860             push @args, qq('--no-${name}[disable ${name}]')
861 2 50 33     20 if $p->{negatable} && length($name) > 1;
862             }
863             }
864              
865 1         8 return @args;
866             }
867              
868             sub _completion_names {
869 0 0   0   0 if (my $names = $ENV{GETOPT_LONG_DESCRIPTIVE_COMPLETION_NAME}) {
870 0         0 return split /,/, $names;
871             }
872 0         0 return prog_name();
873             }
874              
875             sub _bash_completion_script {
876 0     0   0 my @names = _completion_names();
877 0         0 (my $fn_name = "_$names[0]_completion") =~ s/[^a-zA-Z0-9_]/_/g;
878              
879 0         0 my $data = _completion_for_bash(@_);
880              
881 0         0 my $script = "$fn_name() {\n";
882 0         0 $script .= " local cur prev\n";
883 0         0 $script .= " COMPREPLY=()\n";
884 0         0 $script .= ' cur="${COMP_WORDS[COMP_CWORD]}"' . "\n";
885 0         0 $script .= ' prev="${COMP_WORDS[COMP_CWORD-1]}"' . "\n";
886              
887 0 0       0 if (@{ $data->{prev_cases} }) {
  0         0  
888 0         0 $script .= " case \"\$prev\" in\n";
889 0         0 for my $case (@{ $data->{prev_cases} }) {
  0         0  
890 0         0 $script .= " $case->{pattern})\n";
891 0         0 $script .= " $case->{action}\n";
892 0         0 $script .= " return\n";
893 0         0 $script .= " ;;\n";
894             }
895 0         0 $script .= " esac\n";
896             }
897              
898 0         0 my $flags = $data->{flags};
899 0         0 $script .= " COMPREPLY=(\$(compgen -W \"$flags\" -- \"\$cur\"))\n";
900 0         0 $script .= "}\n";
901 0         0 $script .= "complete -F $fn_name $_\n" for @names;
902              
903 0         0 return $script;
904             }
905              
906             sub _zsh_completion_script {
907 0     0   0 my @names = _completion_names();
908 0         0 (my $fn_name = "_$names[0]") =~ s/[^a-zA-Z0-9_]/_/g;
909              
910 0         0 my @args = _completion_for_zsh(@_);
911              
912 0         0 my $script = "#compdef " . join(' ', @names) . "\n";
913 0         0 $script .= "$fn_name() {\n";
914 0         0 $script .= " local -a arguments\n";
915 0         0 $script .= " arguments=(\n";
916 0         0 $script .= " $_\n" for @args;
917 0         0 $script .= " )\n";
918 0         0 $script .= " _arguments \$arguments\n";
919 0         0 $script .= "}\n";
920 0         0 $script .= "$fn_name\n";
921              
922 0         0 return $script;
923             }
924              
925             {
926             package
927             Getopt::Long::Descriptive::_PV_Error;
928 3     3   61 sub error { $_[0]->{error} }
929             sub throw {
930 3     3   9 my ($class, $error_msg) = @_;
931 3         10 my $self = { error => $error_msg };
932 3         8 bless $self, $class;
933 3         15 die $self;
934             }
935             }
936              
937             #pod =head1 CUSTOMIZING
938             #pod
939             #pod Getopt::Long::Descriptive uses L to build and
940             #pod export the C routine. By writing a new class that extends
941             #pod Getopt::Long::Descriptive, the behavior of the constructed C
942             #pod routine can be changed.
943             #pod
944             #pod The following methods can be overridden:
945             #pod
946             #pod =head2 usage_class
947             #pod
948             #pod my $class = Getopt::Long::Descriptive->usage_class;
949             #pod
950             #pod This returns the class to be used for constructing a Usage object, and defaults
951             #pod to Getopt::Long::Descriptive::Usage.
952             #pod
953             #pod =head1 SEE ALSO
954             #pod
955             #pod =for :list
956             #pod * L
957             #pod * L
958             #pod
959             #pod =cut
960              
961             1; # End of Getopt::Long::Descriptive
962              
963             __END__