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