Debian Codegraph @

README

raw
1 NAME
2
3 Getopt::Yath - Option processing yath style.
4
5 DESCRIPTION
6
7 This is the getopt processor yath uses. It should work perfectly fine
8 outside of yath as well.
9
10 SYNOPSIS
11
12 DEFINING OPTIONS
13
14 package My::Package;
15 use Getopt::Yath;
16
17 # Include options from other modules that use Getopt::Yath
18 include_options(
19 'Some::Options::Package',
20 ...,
21 );
22
23 # an option group is basically a way to specify common parameters for all
24 # options defined in the codeblock.
25 option_group {category => 'Human readable category', group => 'settings_group'} => sub {
26
27 # In addition to the fields specified here, all the fields from the
28 # 'option_group' above are included:
29 option verbose => (
30 type => 'Bool', # This is a boolean type, it does not take an argument
31
32 # Optional fields
33 short => 'v', # Allow -v in addition to --verbose
34 default => 0, # What value to use if none is specified (booleans default to 0 anyway)
35 from_env_vars => ['VERBOSE'], # If the $VERBOSE environment variable is set, this will be set to true.
36 set_env_vars => ['VERBOSE'], # If this is set to true it will also set the $VERBOSE environment variable
37
38 description => "This turns on verbose output",
39 );
40
41 option username => (
42 type => 'Scalar', # Scalar type, requires an argument
43
44 # Optional
45 short => 'U', # Allow: -U Bob
46 alt => ['user', 'uname'], # Allow: --user Bob, --uname Bob
47 from_env_vars => ['USER'], # Get the value from the $USER env var if it is not provided.
48 default => sub { "bob" . rand(100) }, # If none is specified, and the env var is empty, generate a default.
49
50 description => "This sets your username",
51 );
52
53 # Other options
54 ...
55 };
56
57 PARSING OPTIONS
58
59 my $parsed = parse_options(
60 ['-v', '--user', 'fred', 'not_an_opt', '--', '--will-not-process'], # Normally you might pass in \@ARGV
61 skip_non_opts => 1, # Skip non-opts, that is any argument that does not start with a '-' it will just skip.
62 stops => ['--'], # Stop processing
63 no_set_env => 1, # Do not actually change %ENV
64 groups => { ':{' => '}:' }, # Arguments between the :{ and }: will be captured into an arrayref, they can be used as option values, or stand-alone
65 );
66
67 $parsed is a Getopt::Yath::State object:
68
69 $parsed->cleared; # {} - Options that were cleared with --no-opt
70 $parsed->skipped; # ['not_an_opt'] - Skipped non options
71 $parsed->settings; # Blessed as Getopt::Yath::Settings
72 # ->settings_group (Blessed as Getopt::Yath::Settings::Group)
73 # ->verbose == 1
74 # ->username == 'fred'
75 $parsed->stop; # '--' - We stopped at '--', if there was no '--' this would be undef
76 $parsed->remains; # ['--will-not-process'] - Stuff after the '--' that we did not process
77 $parsed->modules; # {'My::Package' => 2} - Any module that provided options that were seen
78 $parsed->env; # {'VERBOSE' => 1} - Environment variables that would have been set
79
80 GENERATING COMMAND LINE HELP OUTPUT:
81
82 sub help {
83 print options()->docs('cli');
84 }
85
86 help();
87
88 Produces:
89
90 Human readable category
91 --username ARG, --username=ARG, --user ARG, --user=ARG, --uname ARG
92 --uname=ARG, -U ARG, -U=ARG, --no-username
93 This sets your username
94
95 Can also be set with the following environment variables: USER
96
97 --verbose, -v, --no-verbose
98 This turns on verbose output
99
100 Can also be set with the following environment variables: VERBOSE
101
102 The following environment variables will be set after arguments are processed: VERBOSE
103
104 GENERATING POD:
105
106 sub pod {
107 print options()->docs('pod', head => 2); # The '2' specifies what heading level to use
108 }
109
110 pod();
111
112 Produces:
113
114 =head2 Human readable category
115
116 =over 4
117
118 =item --username ARG
119
120 =item --username=ARG
121
122 =item --user ARG
123
124 =item --user=ARG
125
126 =item --uname ARG
127
128 =item --uname=ARG
129
130 =item -U ARG
131
132 =item -U=ARG
133
134 =item --no-username
135
136 This sets your username
137
138 Can also be set with the following environment variables: C<USER>
139
140
141 =item --verbose
142
143 =item -v
144
145 =item --no-verbose
146
147 This turns on verbose output
148
149 Can also be set with the following environment variables: C<VERBOSE>
150
151 The following environment variables will be set after arguments are processed: C<VERBOSE>
152
153
154 =back
155
156 EXPORTS
157
158 $opts = options()
159
160 This will return an Getopt::Yath::Instance object. This object holds
161 all the defined options, and does all the real work under the hood.
162
163 $parsed = parse_options(\@ARGV)
164
165 $parsed = parse_options(\@ARGV, %PARAMS)
166
167 This processes an arrayref of command line arguments and returns a
168 Getopt::Yath::State object. If there is a problem parsing, such as
169 invalid options in the array, exceptions will be thrown.
170
171 See Getopt::Yath::State for the full list of accessors on the
172 returned object.
173
174 Available parameters that affect parsing are:
175
176 stops => \@STOP_LIST
177
178 stops => ['--']
179
180 This is a list of string that if encountered should stop the
181 parsing process. The string encountered will be available via
182 $parsed->stop. Any unparsed arguments after the stop will be
183 available via $parsed->remains.
184
185 This is mostly useful for supporting the -- option.
186
187 groups => \%GROUP_BORDERS
188
189 groups => { ':{' => '}:' }
190
191 Arguments between the specified start and end tokens will be
192 grouped together into an arrayref.
193
194 stop_at_non_opts => BOOL
195
196 This will cause parsing to stop at any non-option. A non-option in
197 this case is any argument that does not start with a -.
198
199 The item stopped at will be available via $parsed->stop with the
200 remaining arguments available via $parsed->remains.
201
202 skip_non_opts => BOOL
203
204 This will skip any non-option encountered. A non-option is any
205 argument that does not start with -. All skipped items will be
206 available via $parsed->skipped.
207
208 skip_invalid_opts => BOOL
209
210 This will skip any invalid option encountered. This includes any
211 argument that starts with - but is not a valid option. All skipped
212 items will be available via $parsed->skipped.
213
214 stop_at_invalid_opts => BOOL
215
216 This will cause parsing to stop at any invalid option. This
217 includes any argument that starts with - but is not a valid option.
218
219 The item stopped at will be available via $parsed->stop with the
220 remaining arguments available via $parsed->remains.
221
222 no_set_env => BOOL
223
224 Set this to true to prevent any modifications to %ENV.
225
226 $parsed->env will contain the environment variable changes that
227 would have been made.
228
229 Note: The env accessor is always populated even if %ENV is modified
230 directly.
231
232 include_options('Options::Module::A', 'Options::Module::B', ...)
233
234 This allows you to build libraries of Getopt::Yath options and
235 include them as needed. Options from the specified libraries will be
236 merged into the current packages options.
237
238 option_group \%fields => sub { ... }
239
240 option_group {group => 'my_group'} => sub { option ...; ... }
241
242 Create a group of options with common parameters.
243
244 option TITLE => \%SPECIFICATION
245
246 option TITLE => (type => '+My::Type', ...)
247
248 option TITLE => (type => 'Getopt::Yath::Option::Type', ...)
249
250 option TITLE => (type => 'Type', ...)
251
252 This is used to define a single option. You must specify an option
253 NAME and 'type', which must be a valid Getopt::Yath::Option subclass.
254
255 The TITLE is used to produce default values for the 'field' and
256 'name' fields, both of which can be specified directly if the
257 automatic values are not sufficient. 'field' gets the value of title
258 with dashes replaced by underscores. 'name' gets the value of title
259 with underscores replaced with dashes.
260
261 Most of the time you can just list the type as the part after the
262 last :: in Getopt::Yath::Option::TYPE. You can also specify
263 Getopt::Yath::Option::TYPE or Getopt::Yath::Option::TYPE::SubType
264 directly. However if you need to use a module that is not in the
265 Getopt::Yath::Option:: namespace you will need to prefix the module
266 with a + to indicate that.
267
268 option_post_process sub { ... }
269
270 option_post_process $weight, sub { ... }
271
272 option_post_process $weight, $applicable, sub { ... }
273
274 Register a callback to run after all options have been parsed. The
275 callback receives the Getopt::Yath::Instance object and the parse
276 state hashref as arguments.
277
278 $weight controls execution order (lower weights run first, default is
279 0). $applicable is an optional coderef that determines whether this
280 post-processor should run; if provided it receives the post-process
281 entry, the instance, and the settings object. If used inside an
282 option_group block, the group's applicable is inherited when none is
283 specified.
284
285 option_post_process 100 => sub {
286 my ($instance, $state) = @_;
287 # Do something after all options are parsed
288 };
289
290 category_sort_map(%map)
291
292 Set the sort order for option categories in documentation output.
293 Categories with lower values are listed first. By default, "NO
294 CATEGORY - FIX ME" is sorted to 99999 (last).
295
296 category_sort_map(
297 'Display Options' => 1,
298 'Runner Options' => 2,
299 'Logging Options' => 3,
300 );
301
302 OPTION TYPES AND SPECIFICATIONS
303
304 REQUIRED WITH NO DEFAULTS
305
306 title
307
308 This is the first argument to option(). It is used to build the
309 default values for both field and name.
310
311 group => "group_name"
312
313 Name of the field to use in the options hash under which the option
314 will be listed:
315
316 $parsed->{options}->{$group}->{$field_name} = $val
317
318 type => 'TypeName'
319
320 type => 'Getopt::Yath::Option::TypeName'
321
322 type => '+My::Custom::Type'
323
324 This must be a valid Getopt::Yath::Option subclass:
325
326 Scalar
327
328 Takes a scalar value. A value is required. Can be used as --opt VAL
329 or --opt=val. --no-opt can be used to clear the value.
330
331 Bool
332
333 Is either on or off. --opt will turn it on. --no-opt will turn it
334 off. Default is off unless the default is parameter is provided.
335
336 Count
337
338 Is an integer value, default is to start at 0. --opt increments the
339 counter. --no-opt resets the counter. --opt=VAL can be used to
340 specify a desired count.
341
342 List
343
344 Can take multiple values. --opt VAL appends a value to the list.
345 --no-opt will empty the list. If a split_on parameter is provided
346 then a single use can set multiple values. For example if split_on
347 is set to , then --opt foo,bar is provided, then foo and bar will
348 both be added to the list.
349
350 Map
351
352 Expects all values to be key=value pairs and produces a hashref.
353 --opt foo=bar will set $h{foo} = 'bar'. If a split_on parameter is
354 provided then a single use can set multiple values. For example if
355 split_on is set to , then --opt foo=bar,baz=bat is provided, then
356 the result will have $h{foo} = 'bar'; $h{baz} = 'bat'.
357
358 Auto
359
360 This type has an 'autofill' value that is used if no argument is
361 provided to the parameter, IE --opt. But can also be given a
362 specific value using --opt=val. It DOES NOT support --opt VAL which
363 will most likely result in an exception.
364
365 AutoList
366
367 This is a combination of 'Auto' and 'List' types. The no-arg form
368 --opt will add the default values(s) to the list. The --opt=VAL
369 form will add additional values.
370
371 AutoMap
372
373 This is a combination of 'Auto' and 'Map' types. The no-arg form
374 --opt will add the default key+value pairs to the hash. The
375 --opt=KEY=VAL form will add additional values.
376
377 PathList
378
379 Like List, but values are treated as file paths and may contain
380 shell-style wildcards (globs) which are expanded. For example,
381 --opt 'lib/*.pm' will expand to all matching files.
382
383 AutoPathList
384
385 Like PathList with autofill support. The no-arg form --opt adds the
386 autofill paths, while --opt=path adds a specific path.
387
388 BoolMap
389
390 Match several --OPTION-XXX and --no-OPTION-XXX options based on a
391 regex pattern, populating a hashref where each matched key is given
392 a true or false value depending on the --no- prefix. Requires a
393 pattern attribute.
394
395 REQUIRED WITH SANE DEFAULTS
396
397 field => "field_name"
398
399 Name of the field to use in the group hash for the result of parsing
400 arguments.
401
402 $parsed->{options}->{$group}->{$field_name} = $val
403
404 Default is to take the title value and replace any dashes with
405 underscores.
406
407 name => "option-name"
408
409 Primary name for the option --option-name.
410
411 Default is to take the title value and replace any underscores with
412 dashes.
413
414 trace => [$caller, $file, $line]
415
416 This normally resolves to the place option() was called. You can
417 manually override it with a custom value, but you should rarely ever
418 need to.
419
420 category => "Human Readable documentation category"
421
422 When producing POD or command line documentation, options are put
423 into "categories" which should be the human readable version of the
424 group field.
425
426 Default is "NO CATEGORY - FIX ME".
427
428 description => "Explanation of what the option controls"
429
430 Document what the option controls or does.
431
432 Default is 'NO DESCRIPTION - FIX ME'.
433
434 OPTIONAL
435
436 short => 's'
437
438 Specify a short flag to use. This is how you provide single-dash
439 single-letter options.
440
441 -s
442
443 If no argument is required this form is available.
444
445 -s=VAL
446
447 If an argument is allowed this form is available
448
449 -sVAL
450
451 If an argument is allowed, and this form is not directly disabled
452 by the type (Types can override allows_shortval() to return false
453 to forbid this form. Currently Getopt::Yath::Option::Bool and
454 Getopt::Yath::Option::Count disable this form.
455
456 -sss
457
458 So far only the Getopt::Yath::Option::Count type makes use of this.
459 It allows you to add the flag multiple times after a single dash to
460 increment the count.
461
462 alt => \@LIST
463
464 alt => ['alt1', 'alt2']
465
466 Specify alternate or alias names that can be used to set or toggle a
467 field.
468
469 --alt1 --alt2 foo
470
471 prefix => "a-prefix"
472
473 Specify a prefix to attach to the name, and to any alternate names.
474 This is mainly useful when specifying an option group:
475
476 option_group {prefix => 'foo'} => sub {
477 option bar => (
478 type => "Bool",
479 );
480 };
481
482 This would then be used as --foo-bar
483
484 module => 'My::Module'
485
486 Specify the module the argument should be associated with. This
487 defaults to the caller, so usually you do not need to specify it.
488
489 This is mainly used in the case of plugins we only want to load if
490 the option is used.
491
492 no_module => BOOL
493
494 Default is 0. When this is set to true the module name is not used.
495
496 applicable => sub { my $options = shift; ... ? 1 : 0 }
497
498 This can be used to dynamically show/hide options. When this returns
499 false the option will not be available.
500
501 initialize => $scalar
502
503 initialize => sub { ... }
504
505 Initialize the value to this before any arguments are parsed. This is
506 mainly used so that Getopt::Yath::Option::Map can start with an empty
507 hash, and Getopt::Yath::Option::List can be initialized to an empty
508 arrayref.
509
510 This can be a simple scalar (string or number, not a reference), or
511 it may be a codeblock that returns anything you want. Only 1 item
512 should be returned, extra values will result in undefined behavior.
513 For a map this should return an empty hashref, for a list it should
514 return an empty arrayref.
515
516 clear => $scalar
517
518 clear => sub { ... }
519
520 Similar to initialize, but this is used when clearing the value. For
521 things like 'Map' this should return a hashref, etc.
522
523 default => $scalar
524
525 default => sub { ... }
526
527 Set a default to use if no value is provided at the command line.
528
529 This can be a simple scalar (string or number, not a reference), or
530 it may be a codeblock that returns anything you want.
531
532 Most options will only accept a single default value.
533 Getopt::Yath::Option::Map and Getopt::Yath::Option::List support a
534 list of defaults for setting key/value pairs, or adding items to an
535 array.
536
537 These are valid for anything:
538
539 default => 'foo',
540 default => 123,
541 default => sub { "hi" }
542
543 This is valid for an Getopt::Yath::Option::Map:
544
545 default => sub { return ('foo' => 'bar') }
546
547 This is valid for a Getopt::Yath::Option::List:
548
549 default => sub { return (1, 2, 3, 4) }
550
551 autofill => $scalar
552
553 autofill => sub { ... }
554
555 This is used for Getopt::Yath::Option::Auto and similar. This is the
556 value used if the command line option is provided, but no value is
557 provided with it.
558
559 This can be a simple scalar (string or number, not a reference), or
560 it may be a codeblock that returns anything you want.
561
562 Most options will only accept a single autofill value.
563 Getopt::Yath::Option::Map and Getopt::Yath::Option::List support a
564 list of autofill data for setting key/value pairs, or adding items to
565 an array.
566
567 These are valid for anything:
568
569 autofill => 'foo',
570 autofill => 123,
571 autofill => sub { "hi" }
572
573 This is valid for an Getopt::Yath::Option::Map:
574
575 autofill => sub { return ('foo' => 'bar') }
576
577 This is valid for a Getopt::Yath::Option::List:
578
579 autofill => sub { return (1, 2, 3, 4) }
580
581 normalize => sub { my ($input) = @_; ...; return $output }
582
583 If you wish to normalize or transform a value then you use this hook.
584 The sub will get the option and the input value as its arguments. You
585 should return the new value to set, or the input value if it does not
586 need to change.
587
588 trigger => sub { my ($opt, %params) = @_; ... }
589
590 This will be called any time the option is parsed from the command
591 line, or whenever the command line clears the option.
592
593 NOTE: It will not run when initial, autofill, or default values are
594 set.
595
596 The %params passed into the sub look like this:
597
598 (
599 # If this trigger is called because the value is cleared via --no-OPT:
600 action => 'clear',
601 val => undef,
602
603 # If a value is set because of --opt being parsed:
604 action => 'set',
605 val => [...],
606 ref => $ref,
607 state => $state,
608 options => $self,
609 settings => $settings,
610 group => $group,
611 );
612
613 Note that val is always passed in as an arrayref. For simple scalar
614 type options this will only ever have 1 value. For list or map types
615 it may have multiple values, also note that for such types the
616 trigger will only see the newly added values in the 'val' arrayref,
617 not the values already included, which is important as list and map
618 types can be built over several assignments.
619
620 from_env_vars => \@LIST
621
622 A list of environment variables that will be used to populate the
623 option's initial value. These will be checked in order, the first one
624 that is set is the one that will be used, others will not be checked
625 once a value is found. This will prevent the default value from being
626 used, but using the option on the command line will override it.
627
628 Note: that an environment variable can be prefixed with a ! to
629 indicate the value should be boolean-inverted. This means that an
630 option like quiet can have from_env_vars => ['!VERBOSE'] to be set to
631 true when the VERBOSE env var is false. This also works when setting
632 a variable, so you could have set_env_vars => ['!VERBOSE'].
633
634 clear_env_vars => \@LIST
635
636 A list of environment variables to clear after the options are all
637 populated. This is useful if you want to use an env var to set an
638 option, but want to make sure no child processes see the environment
639 variable.
640
641 set_env_vars => \@LIST
642
643 A list of environment variables that will be set to the value of this
644 option (if it is set) when argument processing is complete.
645
646 Note: This is only supported in types that have a single value, maps
647 and lists are not supported.
648
649 Note: that an environment variable can be prefixed with a ! to
650 indicate the value should be boolean-inverted. This means that an
651 option like quiet can have from_env_vars => ['!VERBOSE'] to be set to
652 true when the VERBOSE env var is false. This also works when setting
653 a variable, so you could have set_env_vars => ['!VERBOSE'].
654
655 short_examples => \@LIST
656
657 short_examples => ['', 'ARG', '=ARG']
658
659 short_examples => [' ARG', '=ARG']
660
661 Override the default list of arguments when generating docs. This is
662 used for the short form (single dash followed by a single letter and
663 then a value -Ilib, -I lib, -I=lib, -v, -vv, -vvv...) documentation.
664
665 long_examples => \@LIST
666
667 long_examples => ['', '=ARG']
668
669 long_examples => [' ARG', '=ARG']
670
671 Override the default list of arguments when generating docs. This is
672 used for the long form (double-dash and option name and then a value
673 --include, --include=lib, --include lib) documentation.
674
675 SOURCE
676
677 The source code repository for Getopt-Yath can be found at
678 http://github.com/Test-More/Getopt-Yath/.
679
680 MAINTAINERS
681
682 Chad Granum <[email protected]>
683
684 AUTHORS
685
686 Chad Granum <[email protected]>
687
688 COPYRIGHT
689
690 Copyright Chad Granum <[email protected]>.
691
692 This program is free software; you can redistribute it and/or modify it
693 under the same terms as Perl itself.
694
695 See http://dev.perl.org/licenses/
696