1App::Yath::Option(3) User Contributed Perl Documentation App::Yath::Option(3)
2
3
4
6 App::Yath::Option - Representation of a yath option.
7
9 This class represents a single command line option for yath.
10
12 You usually will not be creating option instances directly. Usually you
13 will use App::Yath::Options which provides sugar, and helps make sure
14 options get to the right place.
15
16 use App::Yath::Options;
17
18 # You can specify a single option:
19 option color => (
20 prefix => 'display',
21 category => "Display Options",
22 description => "Turn color on, default is true if STDOUT is a TTY.",
23 default => sub { -t STDOUT ? 1 : 0 },
24 );
25
26 # If you are specifying multiple options you can use an option_group to
27 # define common parameters.
28 option_group {prefix => 'display', category => "Display Options"} => sub {
29 option color => (
30 description => "Turn color on, default is true if STDOUT is a TTY.",
31 default => sub { -t STDOUT ? 1 : 0 },
32 );
33
34 option verbose => (
35 short => 'v',
36 type => 'c',
37 description => "Be more verbose",
38 default => 0,
39 );
40 };
41
43 These can be provided at object construction, or are generated
44 internally.
45
46 CONSTRUCTION ONLY
47 applicable => sub { ... }
48 This is callback is used by the "applicable()" method.
49
50 option foo => (
51 ...,
52 applicable => sub {
53 my ($opt, $options) = @_;
54 ...
55 return $bool;
56 },
57 );
58
59 READ-ONLY
60 REQUIRED
61
62 $class->new(prefix => 'my_prefix')
63 $scalar = $opt->prefix()
64 A prefix is required. All options have their values inserted into
65 the settings structure, an instance of Test2::Harness::Settings.
66 The structure is "$settings->PREFIX->OPTION".
67
68 If you do not specify a "name" attribute then the default name will
69 be "PREFIX-TITLE". The name is the main command line argument, so
70 "--PREFIX-TITLE" is the default name.
71
72 $class->new(type => $type)
73 $type = $opt->type()
74 All options must have a type, if non is specified the default is
75 'b' aka boolean.
76
77 Here are all the possible types, along with their aliases. You may
78 use the type character, or any of the aliases to specify that type.
79
80 b bool boolean
81 True of false values, will be normalized to 0 or 1 in most
82 cases.
83
84 c count counter counting
85 Counter, starts at 0 and then increments every time the option
86 is used.
87
88 s scalar string number
89 Requires an argument which is treated as a scalar value. No
90 type checking is done by the option itself, though you can
91 check it using "action" or "normalize" callbacks which are
92 documented under those attributes.
93
94 m multi multiple list array
95 Requires an argument which is treated as a scalar value. Can be
96 used multiple times. All arguments provided are appended to an
97 array.
98
99 d def default
100 Argument is optional, scalar when provided. "--opt=arg" to
101 provide an argument, "--opt arg" will not work, "arg" will be
102 seen as its own item on the command line. Can be specified
103 without an arg "--opt" to signify a default argument should be
104 used (set via the "action" callback, not the "default"
105 attribute which is a default value regardless of if the option
106 is used.)
107
108 Real world example from the debug options (simplified for doc
109 purposes):
110
111 option summary => (
112 type => 'd',
113 description => "Write out a summary json file, if no path is provided 'summary.json' will be used. The .json extension is added automatically if omitted.",
114
115 long_examples => ['', '=/path/to/summary.json'],
116
117 action => sub {
118 my ($prefix, $field, $raw, $norm, $slot, $settings) = @_;
119
120 # $norm will be '1' if option was used without an argument, so we
121 # just use the provided value when it is not 1'.
122 return $$slot = $norm unless $norm eq '1';
123
124 # $norm was 1, so this is our no-arg "default" behavior
125
126 # Do nothing if a value is already set
127 return if $$slot;
128
129 # Set the default value of 'summary.json'
130 return $$slot = 'summary.json';
131 },
132 );
133 };
134
135 D multi-def multiple-default list-default array-default
136 This is a combination of "d" and "m". You can use the opt
137 multiple times to list multiple values, and you can call it
138 without args to add a set of "default" values (not to be
139 confused with THE default attribute, which is used even if the
140 option never appears on the command line.)
141
142 Real world example (simplified for doc purposes):
143
144 option dev_libs => (
145 type => 'D',
146 short => 'D',
147 name => 'dev-lib',
148
149 category => 'Developer',
150 description => 'Add paths to @INC before loading ANYTHING. This is what you use if you are developing yath or yath plugins to make sure the yath script finds the local code instead of the installed versions of the same code. You can provide an argument (-Dfoo) to provide a custom path, or you can just use -D without and arg to add lib, blib/lib and blib/arch.',
151
152 long_examples => ['', '=lib'],
153 short_examples => ['', '=lib', 'lib'],
154
155 action => sub {
156 my ($prefix, $field, $raw, $norm, $slot, $settings) = @_;
157
158 # If no argument was provided use the 'lib', 'blib/lib', and 'blib/arch' defaults.
159 # If an argument was provided, use it.
160 push @{$$slot} => ($norm eq '1') ? ('lib', 'blib/lib', 'blib/arch') : ($norm);
161 },
162 );
163
164 h hash
165 The hash type. Each time the option is used it is to add a
166 single key/value pair to the hash. Use an "=" sign to split the
167 key and value. The option can be used multiple times. A value
168 is required.
169
170 yath --opt foo=bar --opt baz=bat
171
172 H hash-list
173 Similar to the 'h' type except the key/value pair expects a
174 comma separated list for the value, and it will be placed under
175 the key as an arrayef.
176
177 yath --opt foo=a,b,c --opt bar=1,2,3
178
179 The yath command obove would produce this structure:
180
181 {
182 foo => ['a', 'b', 'c'],
183 bar => ['1', '2', '3'],
184 }
185
186 $class->new(title => 'my_title')
187 $title = $opt->title()
188 You MUST specify either a title, or BOTH a name and field. If you
189 only specify a title it will be used to generate the name and
190 field.
191
192 If your title is 'foo-bar_baz' then your field will be
193 'foo_bar_baz' and your name will be '$PREFIX-foo-bar-baz'.
194
195 Basically title is used to generate a sane field and/or name if
196 niether are specified. For field all dashes are changed to
197 underscores. The field is used as a key in the settings:
198 "$settings->prefix->field". For the name all underscores are
199 changed to dashes, if the option is provided by a plugin then
200 'prefix-' is prepended as well. The name is used for the command
201 line argument '--name'.
202
203 If you do not want/like the name and field generated from a title
204 then you can specify a name or title directly.
205
206 $class->new(name => 'my-name')
207 $name = $opt->name()
208 You MUST specify either a title, or BOTH a name and field. If you
209 only specify a title it will be used to generate the name and
210 field.
211
212 This name is used as your primary command line argument. If your
213 name is "foo" then your command line argument is "--foo".
214
215 $class->new(field => 'my_field')
216 $field = $opt->field()
217 You MUST specify either a title, or BOTH a name and field. If you
218 only specify a title it will be used to generate the name and
219 field.
220
221 The field is used in the settings hash. If your field is "foo" then
222 your settings path is "$setting->prefix->foo".
223
224 OPTIONAL
225
226 $class->new(action => sub ...)
227 $coderef = $opt->action()
228 option foo => (
229 ...,
230 action => sub {
231 my ($prefix, $field_name, $raw_value, $normalized_value, $slot_ref, $settings, $handler, $options) = @_;
232
233 # If no action is specified the following is all that is normally
234 # done. Having an action means this is not done, so if you want the
235 # value stored you must call this or similar.
236 $handler->($slot, $normalized_value);
237 },
238 );
239
240 $prefix
241 The prefix for the option, specified when the option was
242 defined.
243
244 $field_name
245 The field for the option, specified whent the option was
246 defined.
247
248 $raw_value
249 The value/argument provided at the command line "--foo bar"
250 would give us "bar". This is BEFORE any processing/normalizing
251 is done.
252
253 For options that do not take arguments, or where argumentes are
254 optional and none are provided, this will be '1'.
255
256 $normalized_value
257 If a normalize callback was provided this will be the result of
258 putting the $raw_value through the normalize callback.
259
260 $slot_ref
261 This is a scalar reference to the settings slot that holds the
262 option value(s).
263
264 The default behavior when no action is specified is usually one
265 of these:
266
267 $$slot_ref = $normalized_value;
268 push @{$$slot_ref} => $normalized_value;
269
270 However, to save yourself trouble you can use the $handler
271 instead (see below).
272
273 $settings
274 The Test2::Harness::Settings instance.
275
276 $handler
277 A callback that "does the right thing" as far as setting the
278 value in the settings hash. This is what is used when you do
279 not set an action callback.
280
281 $handler->($slot, $normalized_value);
282
283 $options
284 The App::Yath::Options instance this options belongs to. This
285 is mainly useful if you have an option that may add even more
286 options (such as the "--plugin" option can do). Note that if
287 you do this you should also set the "adds_options" attribute to
288 true, if you do not then the options list will not be refreshed
289 and your new options may not show up.
290
291 $class->new(adds_options => $bool)
292 $bool = $opt->adds_options()
293 If this is true then it means using this option could result in
294 more options being available (example: Loading a plugin).
295
296 $class->new(alt => ['alt1', 'alt2', ...])
297 $arrayref = $opt->alt()
298 Provide alternative names for the option. These are aliases that
299 can be used to achieve the same thing on the command line. This is
300 mainly useful for backcompat if an option is renamed.
301
302 $class->new(builds => 'My::Class')
303 $my_class = $opt->builds()
304 If this option is used in the construction of another object (such
305 as the group it belongs to is composed of options that translate
306 1-to-1 to fields in another object to build) then this can be used
307 to specify that. The ultimate effect is that an exception will be
308 thrown if that class does not have the correct attribute. This is a
309 safety net to catch errors early if field names change, or are
310 missing between this representation and the object being composed.
311
312 $class->new(category => 'My Category')
313 $category = $opt->category()
314 This is used to sort/display help and POD documentation for your
315 option. If you do not provide a category it is set to 'NO CATEGORY
316 - FIX ME'. The default value makes sure everyone knows that you do
317 not know what you are doing :-).
318
319 $class->new(clear_env_vars => $bool)
320 $bool = $opt->clear_env_vars()
321 This option is only useful when paired with the "env_vars"
322 attribute.
323
324 Example:
325
326 option foo => (
327 ...
328 env_vars => ['foo', 'bar', 'baz'],
329 clear_env_vars => 1,
330 ):
331
332 In this case you are saying option foo can be set to the value of
333 $ENV{foo}, $ENV{bar}, or $ENV{baz} vars if any are defined. The
334 "clear_env_vars" tell it to then delete the environment variables
335 after they are used to set the option. This is useful if you want
336 to use the env var to set an option, but do not want any tests to
337 be able to see the env var after it is used to set the option.
338
339 $class->new(default => $scalar)
340 $class->new(default => sub { return $default })
341 $scalar_or_coderef = $opt->default()
342 This sets a default value for the field in the settings hash, the
343 default is set before any command line processing is done, so if
344 the option is never used in the command line the default value will
345 be there.
346
347 Be sure to use the correct default value for your type. A scalar
348 for 's', an arrayref for 'm', etc.
349
350 Note, for any non-scalar type you want to use a subref to define
351 the value:
352
353 option foo => (
354 ...
355 type => 'm',
356 default => sub { [qw/a b c/] },
357 );
358
359 $class->new(description => "Fe Fi Fo Fum")
360 $multiline_string = $opt->description()
361 Description of your option. This is used in help output and POD. If
362 you do not provide a value the default is 'NO DESCRIPTION - FIX
363 ME'.
364
365 $class->new(env_vars => \@LIST)
366 $arrayref = $opt->env_vars()
367 If set, this should be an arrayref of environment variable names.
368 If any of the environment variables are defined then the settings
369 will be updated as though the option was provided onthe command
370 line with that value.
371
372 Example:
373
374 option foo => (
375 prefix => 'blah',
376 type => 's',
377 env_vars => ['FOO', 'BAR'],
378 );
379
380 Then command line:
381
382 FOO="xxx" yath test
383
384 Should be the same as
385
386 yath test --foo "xxx"
387
388 You can also ask to have the environment variables cleared after
389 they are checked:
390
391 option foo => (
392 prefix => 'blah',
393 type => 's',
394 env_vars => ['FOO', 'BAR'],
395 clear_env_vars => 1, # This tells yath to clear the env vars after they
396 are used.
397 );
398
399 If you would like the option set to the opposite of the envarinment
400 variable you can prefix it with a '!' character:
401
402 option foo =>(
403 ...
404 env_vars => ['!FOO'],
405 );
406
407 In this case these are equivelent:
408
409 FOO=0 yath test
410 yath test --foo=1
411
412 Note that this only works when the variable is defined. If
413 $ENV{FOO} is not defined then the variable is not used.
414
415 $class->new(from_command => 'App::Yath::Command::COMMAND')
416 $cmd_class = $opt->from_command()
417 If your option was defined for a specific command this will be set.
418 You do not normally set this yourself, the tools in
419 App::Yath::Options usually handle that for you.
420
421 $class->new(from_plugin => 'App::Yath::Plugin::PLUGIN')
422 $plugin_class = $opt->from_plugin()
423 If your option was defined for a specific plugin this will be set.
424 You do not normally set this yourself, the tools in
425 App::Yath::Options usually handle that for you.
426
427 $class->new(long_examples => [' foo', '=bar', ...])
428 $arrayref = $opt->long_examples()
429 Used for documentation purposes. If your option takes arguments
430 then you can give examples here. The examples should not include
431 the option itself, so "--foo bar" would be wrong, you should just
432 do " bar".
433
434 $class->new(negate => sub { ... })
435 $coderef = $opt->negate()
436 If you want a custom handler for negation "--no-OPT" you can
437 provide one here.
438
439 option foo => (
440 ...
441 negate => sub {
442 my ($prefix, $field, $slot, $settings, $options) = @_;
443
444 ...
445 },
446 );
447
448 The variables are the same as those in the "action" callback.
449
450 $class->new(normalize => sub { ... })
451 $coderef = $opt->normalize()
452 The normalize attribute holds a callback sub that takes the raw
453 value as input and returns the normalized form.
454
455 option foo => (
456 ...,
457 normalize => sub {
458 my $raw = shift;
459
460 ...
461
462 return $norm;
463 },
464 );
465
466 $class->new(pre_command => $bool)
467 $bool = $opt->pre_command()
468 Options are either command-specific, or pre-command. Pre-command
469 options are ones yath processes even if it has not determined what
470 comamnd is being used. Good examples are "--dev-lib" and
471 "--plugin".
472
473 yath --pre-command-opt COMMAND --command-opt
474
475 Most of the time this should be false, very few options qualify as
476 pre-command.
477
478 $class->new(pre_process => sub { ... })
479 $coderef = $opt->pre_process()
480 This is essentially a BEGIN block for options. This callback is
481 called as soon as the option is parsed from the command line, well
482 before the value is normalized and added to settings. A good use
483 for this is if your option needs to inject additional
484 App::Yath::Option instances into the App::Yath::Options instance.
485
486 option foo => (
487 ...
488
489 pre_process => sub {
490 my %params = @_;
491
492 my $opt = $params{opt};
493 my $options = $params{options};
494 my $action = $params{action};
495 my $type = $params{type};
496 my $val = $params{val};
497
498 ...;
499 },
500 );
501
502 Explanation of paremeters:
503
504 $params{opt}
505 The op instance
506
507 $params{options}
508 The App::Yath::Options instance.
509
510 $params{action}
511 A string, usually either "handle" or "handle_negation"
512
513 $params{type}
514 A string, usually "pre-command" or "command ($CLASS)" where the
515 second has the command package in the parentheses.
516
517 $params{val}
518 The value being set, if any. For options that do not take
519 arguments, or in the case of negation this key may not exist.
520
521 $class->new(short => $single_character_string)
522 $single_character_string = $opt->short()
523 If you want your option to be usable as a short option (single
524 character, single dash "-X") then you can provide the character to
525 use here. If the option does not require an argument then it can be
526 used along with other no-argument short options: "-xyz" would be
527 equivilent to "-x -y -z".
528
529 There are only so many single-characters available, so options are
530 restricted to picking only 1.
531
532 Please note: Yath reserves the right to add any single-character
533 short options in the main distribution, if they conflict with third
534 party plugins/commands then the third party must adapt and change
535 its options. As such it is not recommended to use any short options
536 in third party addons.
537
538 $class->new(short_examples => [' foo', ...])
539 $arrayref = $opt->short_examples()
540 Used for documentation purposes. If your option takes arguments
541 then you can give examples here. The examples should not include
542 the option itself, so "-f bar" would be wrong, you should just do "
543 bar".
544
545 This attribute is not used if you do not provide a "short"
546 attribute.
547
548 $class->new(trace => [$package, $file, $line])
549 $arrayref = $opt->trace()
550 This is almost always auto-populated for you via "caller()". It
551 should be an arrayref with a package, filename and line number.
552 This is used if there is a conflict between parameter names and/or
553 short options. If such a situation arises the file/line number of
554 all conflicting options will be reported so it can be fixed.
555
557 $bool = $opt->allows_arg()
558 True if arguments can be provided to the option (based on type).
559 This does not mean the option MUST accept arguments. 'D' type
560 options can accept arguments, but can also be used without
561 arguments.
562
563 $bool = $opt->applicable($options)
564 If an option provides an applicability callback this will use it to
565 determine if the option is applicable given the App::Yath::Options
566 instance.
567
568 If no callback was provided then this returns true.
569
570 $character = $opt->canon_type($type_name)
571 Given a long alias for an option type this will return the single-
572 character canonical name. This will return undef for any unknown
573 strings. This will not translate single character names to
574 themselves, so "$opt->canon_type('s')" will return undef while
575 "$opt->canon_type('string')" will return 's'.
576
577 $val = $opt->get_default()
578 This will return the proper default value for the option. If a
579 custom default was provided it will be returned, otherwise the
580 correct generic default for the option type will be used.
581
582 Here is a snippet showing the defaults for types:
583
584 # First check env vars and return any values from there
585 ...
586 # Then check for a custom default and use it.
587 ...
588
589 return 0
590 if $self->{+TYPE} eq 'c'
591 || $self->{+TYPE} eq 'b';
592
593 return []
594 if $self->{+TYPE} eq 'm'
595 || $self->{+TYPE} eq 'D';
596
597 return {}
598 if $self->{+TYPE} eq 'h'
599 || $self->{+TYPE} eq 'H';
600
601 # All others get undef
602 return undef;
603
604 $val $opt->get_normalized($raw)
605 This converts a raw value to a normalized one. If a custom
606 "normalize" attribute was set then it will be used, otherwise it is
607 normalized in accordance to the type.
608
609 This is where booleans are turned into 0 or 1, hashes are split,
610 hash-lists are split further, etc.
611
612 $opt->handle($raw, $settings, $options, $list)
613 This method handles setting the value in $settings. You should not
614 normally need to call this yourself.
615
616 $opt->handle_negation()
617 This method is used to handle a negated option. You should not
618 normally need to call this yourself.
619
620 @list = $opt->long_args()
621 Returns the name and any aliases.
622
623 $ref = $opt->option_slot($settings)
624 Get the settings->prefix->field reference. This creates the setting
625 field if necessary.
626
627 $bool = $opt->requires_arg()
628 Returns true if this option requires an argument when used.
629
630 $string = $opt->trace_string()
631 return a string like "somefile.pm line 42" based on where the
632 option was defined.
633
634 $bool = $opt->valid_type($character)
635 Check if a single character type is valid.
636
637 DOCUMENTATION GENERATION
638 $string = $opt->cli_docs()
639 Get the option documentation in a format that works for the "yath
640 help COMMAND" command.
641
642 $string = $opt->pod_docs()
643 Get the option documentation in POD format.
644
645 =item ....
646
647 .. option details ...
648
650 The source code repository for Test2-Harness can be found at
651 http://github.com/Test-More/Test2-Harness/.
652
654 Chad Granum <exodist@cpan.org>
655
657 Chad Granum <exodist@cpan.org>
658
660 Copyright 2020 Chad Granum <exodist7@gmail.com>.
661
662 This program is free software; you can redistribute it and/or modify it
663 under the same terms as Perl itself.
664
665 See http://dev.perl.org/licenses/
666
667
668
669perl v5.36.0 2022-09-08 App::Yath::Option(3)