Debian Codegraph @

lib/App/Yath/Option.pm

raw
1 package App::Yath::Option;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use Carp qw/confess/;
8
9 use Test2::Harness::Util::HashBase qw{
10 <title
11 <field <name <type <trace
12 <ignore_for_build
13
14 <prefix <short <alt
15
16 <pre_command <from_plugin <from_command
17
18 <pre_process
19 <adds_options
20
21 <default <normalize <action <negate <autofill
22 <env_vars <clear_env_vars
23
24 +applicable
25
26 <builds
27 <category
28 <description
29 <short_examples <long_examples
30 };
31
32 my %TYPES = (
33 b => 1,
34 c => 1,
35 s => 1,
36 m => 1,
37 d => 1,
38 D => 1,
39 h => 1,
40 H => 1,
41 );
42 sub valid_type { $TYPES{$_[-1]} }
43
44 my %LONG_TO_SHORT_TYPES = (
45 bool => 'b',
46 boolean => 'b',
47
48 count => 'c',
49 counter => 'c',
50 counting => 'c',
51
52 scalar => 's',
53 string => 's',
54 number => 's',
55
56 multi => 'm',
57 multiple => 'm',
58 list => 'm',
59 array => 'm',
60
61 default => 'd',
62 def => 'd',
63
64 'multi-def' => 'D',
65 'multiple-default' => 'D',
66 'list-default' => 'D',
67 'array-default' => 'D',
68
69 'hash' => 'h',
70 'hash-list' => 'H',
71 );
72 sub canon_type { $LONG_TO_SHORT_TYPES{$_[-1]} }
73
74 my %REQUIRES_ARG = (s => 1, m => 1, h => 1, H => 1);
75 sub requires_arg { $REQUIRES_ARG{$_[0]->{+TYPE}} }
76
77 my %ALLOWS_ARG = (d => 1, D => 1);
78 sub allows_arg { $ALLOWS_ARG{$_[0]->{+TYPE}} || $REQUIRES_ARG{$_[0]->{+TYPE} } }
79
80 sub init {
81 my $self = shift;
82
83 confess "You must specify 'title' or both 'field' and 'name'"
84 unless $self->{+TITLE} || ($self->{+FIELD} && $self->{+NAME});
85
86 confess "The 'prefix' attribute is required"
87 unless $self->{+PREFIX};
88
89 confess "The 'alt' attribute must be an array-ref"
90 if $self->{+ALT} && ref($self->{+ALT}) ne 'ARRAY';
91
92 if (my $title = $self->{+TITLE}) {
93 $self->{+FIELD} //= $title;
94 $self->{+NAME} //= ($self->{+FROM_PLUGIN} && $self->{+PREFIX}) ? "$self->{+PREFIX}-$title" : $title;
95 }
96
97 $self->{+FIELD} =~ s/-/_/g;
98 $self->{+NAME} =~ s/_/-/g;
99
100 if (my $class = $self->{+BUILDS}) {
101 confess "class '$class' does not have a '$self->{+FIELD}' method"
102 unless $class->can($self->{+FIELD}) || $self->{+IGNORE_FOR_BUILD};
103 }
104
105 $self->{+TYPE} //= 'b';
106 $self->{+TYPE} = $self->canon_type($self->{+TYPE}) // $self->{+TYPE} if length($self->{+TYPE}) > 1;
107 confess "Invalid type '$self->{+TYPE}'" unless $self->valid_type($self->{+TYPE});
108
109 if ($self->{+TYPE} eq 'd' || $self->{+TYPE} eq 'D') {
110 $self->{+AUTOFILL} //= 1;
111 }
112 elsif(defined $self->{+AUTOFILL}) {
113 confess "'autofill' not supported for this type ('$self->{+TYPE}')";
114 }
115
116 if (my $def = $self->{+DEFAULT}) {
117 my $ref = ref($def);
118 confess "'default' must be a simple scalar, or a coderef, got a '$ref'" if $ref && $ref ne 'CODE';
119 }
120
121 for my $key (NORMALIZE(), ACTION()) {
122 my $val = $self->{$key} or next;
123 my $ref = ref($val) || 'not a ref';
124 next if $ref eq 'CODE';
125 confess "'$key' must be undef, or a coderef, got '$ref'";
126 }
127
128 $self->{+TRACE} //= [caller(1)];
129 $self->{+CATEGORY} //= 'NO CATEGORY - FIX ME';
130 $self->{+DESCRIPTION} //= 'NO DESCRIPTION - FIX ME';
131
132 for my $key (sort keys %$self) {
133 confess "'$key' is not a valid option attribute"
134 unless $self->can(uc($key));
135 }
136
137 return $self;
138 }
139
140 sub applicable {
141 my $self = shift;
142 my ($options) = @_;
143 my $cb = $self->{+APPLICABLE} or return 1;
144 return $self->$cb($options);
145 }
146
147 sub long_args {
148 my $self = shift;
149
150 return ($self->{+NAME}, @{$self->{+ALT} || []});
151 }
152
153 sub option_slot {
154 my $self = shift;
155 my ($settings) = @_;
156
157 confess "A settings instance is required" unless $settings;
158 return $settings->define_prefix($self->{+PREFIX})->vivify_field($self->{+FIELD});
159 }
160
161 sub get_default {
162 my $self = shift;
163
164 for my $var (@{$self->{+ENV_VARS} // []}) {
165 my ($neg) = $var =~ s/^(!)//;
166 next unless exists $ENV{$var};
167 return !$ENV{$var} if $neg;
168 return $ENV{$var};
169 }
170
171 if (defined $self->{+DEFAULT}) {
172 my $def = $self->{+DEFAULT};
173
174 return $self->$def() if ref($def);
175
176 return $def;
177 }
178
179 return 0
180 if $self->{+TYPE} eq 'c'
181 || $self->{+TYPE} eq 'b';
182
183 return []
184 if $self->{+TYPE} eq 'm'
185 || $self->{+TYPE} eq 'D';
186
187 return {}
188 if $self->{+TYPE} eq 'h'
189 || $self->{+TYPE} eq 'H';
190
191 return undef;
192 }
193
194 sub get_normalized {
195 my $self = shift;
196 my ($raw) = @_;
197
198 return $self->{+NORMALIZE}->($raw)
199 if $self->{+NORMALIZE};
200
201 return $raw ? 1 : 0
202 if $self->{+TYPE} eq 'b';
203
204 if (lc($self->{+TYPE}) eq 'h') {
205 my ($key, $val) = split /=/, $raw, 2;
206
207 if ($self->{+TYPE} eq 'H') {
208 $val //= '';
209 $val = [split /,/, $val];
210 return [$key, $val];
211 }
212
213 return [$key, $val // 1];
214 }
215
216 return $raw;
217 }
218
219 my %HANDLERS = (
220 c => sub { ${$_[0]}++ },
221 m => sub { push @{${$_[0]} //= []} => $_[1] && ref($_[1]) eq 'ARRAY' ? @{$_[1]} : $_[1] },
222 D => sub { push @{${$_[0]} //= []} => $_[1] && ref($_[1]) eq 'ARRAY' ? @{$_[1]} : $_[1] },
223 h => sub {
224 my $hash = ${$_[0]} //= {};
225 my $key = $_[1]->[0];
226 my $val = $_[1]->[1];
227
228 push @{$hash->{'@'} //= []} => $key unless $hash->{$key};
229 $hash->{$key} = $val;
230 },
231 H => sub {
232 my $hash = ${$_[0]} //= {};
233 my $key = $_[1]->[0];
234 my $vals = $_[1]->[1];
235
236 push @{$hash->{'@'} //= []} => $key unless $hash->{$key};
237 push @{$hash->{$key} //= []} => @$vals;
238 },
239 );
240
241 sub handle {
242 my $self = shift;
243 my ($raw, $settings, $options, $list) = @_;
244
245 confess "A settings instance is required" unless $settings;
246 confess "An options instance is required" unless $options;
247
248 my $slot = $self->option_slot($settings);
249 my $norm = $self->get_normalized($raw);
250
251 my $handler = $HANDLERS{$self->{+TYPE}} //= sub { ${$_[0]} = $_[1] };
252
253 return $self->{+ACTION}->($self->{+PREFIX}, $self->{+FIELD}, $raw, $norm, $slot, $settings, $handler, $options)
254 if $self->{+ACTION};
255
256 return $handler->($slot, $norm);
257 }
258
259 sub handle_negation {
260 my $self = shift;
261 my ($settings, $options) = @_;
262
263 confess "A settings instance is required" unless $settings;
264 confess "An options instance is required" unless $options;
265
266 my $slot = $self->option_slot($settings);
267
268 return $self->{+NEGATE}->($self->{+PREFIX}, $self->{+FIELD}, $slot, $settings, $options)
269 if $self->{+NEGATE};
270
271 return $$slot = 0
272 if $self->{+TYPE} eq 'b'
273 || $self->{+TYPE} eq 'c';
274
275 return @{$$slot //= []} = ()
276 if $self->{+TYPE} eq 'm'
277 || $self->{+TYPE} eq 'D';
278
279 return %{$$slot //= {}} = ()
280 if $self->{+TYPE} eq 'h'
281 || $self->{+TYPE} eq 'H';
282
283 return $$slot = undef;
284 }
285
286 sub trace_string {
287 my $self = shift;
288 my $trace = $self->{+TRACE} or return "[UNKNOWN]";
289 return "$trace->[1] line $trace->[2]";
290 }
291
292 my %TYPE_LONG_ARGS = (
293 b => [''],
294 c => [''],
295 s => [' ARG', '=ARG'],
296 m => [' ARG', '=ARG'],
297 d => ['[=ARG]'],
298 D => ['[=ARG]'],
299 h => [' KEY=VAL', '=KEY=VAL'],
300 H => [' KEY=VAL1,VAL2,...', '=KEY=VAL1,VAL2,...'],
301 );
302
303 my %TYPE_SHORT_ARGS = (
304 b => [''],
305 c => [''],
306 s => [' ARG', '=ARG'],
307 m => [' ARG', '=ARG'],
308 d => ['[=ARG]', '[ARG]'],
309 D => ['[=ARG]', '[ARG]'],
310 h => [' KEY=VAL', '=KEY=VAL'],
311 H => [' KEY=VAL1,VAL2,...', '=KEY=VAL1,VAL2,...'],
312 );
313
314 my %TYPE_NOTES = (
315 'c' => "Can be specified multiple times",
316 'm' => "Can be specified multiple times",
317 'D' => "Can be specified multiple times",
318 'h' => "Can be specified multiple times",
319 'H' => "Can be specified multiple times. If the same key is listed multiple times the value lists will be appended together.",
320 );
321
322 sub cli_docs {
323 my $self = shift;
324
325 my @forms = (map { "--$self->{+NAME}$_" } @{$self->{+LONG_EXAMPLES} || $TYPE_LONG_ARGS{$self->{+TYPE}}});
326
327 for my $alt (@{$self->{+ALT} || []}) {
328 push @forms => (map { "--$alt$_" } @{$self->{+LONG_EXAMPLES} || $TYPE_LONG_ARGS{$self->{+TYPE}}});
329 }
330
331 push @forms => map { "-$self->{+SHORT}$_" } @{$self->{+SHORT_EXAMPLES} || $TYPE_SHORT_ARGS{$self->{+TYPE}}}
332 if $self->{+SHORT};
333
334 push @forms => "--no-$self->{+NAME}";
335
336 my @out;
337
338 require App::Yath::Util;
339 require Test2::Util::Term;
340
341 my $width = Test2::Util::Term::term_size() - 20;
342 $width = 80 unless $width && $width >= 80;
343
344 push @out => App::Yath::Util::fit_to_width($width, ", ", \@forms);
345
346 my $desc = App::Yath::Util::fit_to_width($width, " ", $self->{+DESCRIPTION});
347 $desc =~ s/^/ /gm;
348 push @out => $desc;
349
350 push @out => "\n Can also be set with the following environment variables: " . join(", ", @{$self->{+ENV_VARS}}) if $self->{+ENV_VARS};
351
352 push @out => "\n Note: " . $TYPE_NOTES{$self->{+TYPE}} if $TYPE_NOTES{$self->{+TYPE}};
353
354 return join "\n" => @out;
355 }
356
357 sub pod_docs {
358 my $self = shift;
359
360 my @forms = (map { "--$self->{+NAME}$_" } @{$self->{+LONG_EXAMPLES} || $TYPE_LONG_ARGS{$self->{+TYPE}}});
361 for my $alt (@{$self->{+ALT} || []}) {
362 push @forms => (map { "--$alt$_" } @{$self->{+LONG_EXAMPLES} || $TYPE_LONG_ARGS{$self->{+TYPE}}});
363 }
364 push @forms => map { "-$self->{+SHORT}$_" } @{$self->{+SHORT_EXAMPLES} || $TYPE_SHORT_ARGS{$self->{+TYPE}}}
365 if $self->{+SHORT};
366 push @forms => "--no-$self->{+NAME}";
367
368 my @out = map { "=item $_" } @forms;
369
370 push @out => $self->{+DESCRIPTION};
371
372 push @out => "Can also be set with the following environment variables: " . join(", ", map { "C<$_>" } @{$self->{+ENV_VARS}}) if $self->{+ENV_VARS};
373
374 push @out => $TYPE_NOTES{$self->{+TYPE}} if $TYPE_NOTES{$self->{+TYPE}};
375
376 return join("\n\n" => @out) . "\n";
377 }
378
379 1;
380
381 __END__
382
383 =pod
384
385 =encoding UTF-8
386
387 =head1 NAME
388
389 App::Yath::Option - Representation of a yath option.
390
391 =head1 DESCRIPTION
392
393 This class represents a single command line option for yath.
394
395 =head1 SYNOPSIS
396
397 You usually will not be creating option instances directly. Usually you will
398 use App::Yath::Options which provides sugar, and helps make sure options get to
399 the right place.
400
401 use App::Yath::Options;
402
403 # You can specify a single option:
404 option color => (
405 prefix => 'display',
406 category => "Display Options",
407 description => "Turn color on, default is true if STDOUT is a TTY.",
408 default => sub { -t STDOUT ? 1 : 0 },
409 );
410
411 # If you are specifying multiple options you can use an option_group to
412 # define common parameters.
413 option_group {prefix => 'display', category => "Display Options"} => sub {
414 option color => (
415 description => "Turn color on, default is true if STDOUT is a TTY.",
416 default => sub { -t STDOUT ? 1 : 0 },
417 );
418
419 option verbose => (
420 short => 'v',
421 type => 'c',
422 description => "Be more verbose",
423 default => 0,
424 );
425 };
426
427 =head1 ATTRIBUTES
428
429 These can be provided at object construction, or are generated internally.
430
431 =head2 CONSTRUCTION ONLY
432
433 =over 4
434
435 =item applicable => sub { ... }
436
437 This is callback is used by the C<applicable()> method.
438
439 option foo => (
440 ...,
441 applicable => sub {
442 my ($opt, $options) = @_;
443 ...
444 return $bool;
445 },
446 );
447
448 =back
449
450 =head2 READ-ONLY
451
452 =head3 REQUIRED
453
454 =over 4
455
456 =item $class->new(prefix => 'my_prefix')
457
458 =item $scalar = $opt->prefix()
459
460 A prefix is required. All options have their values inserted into the settings
461 structure, an instance of L<Test2::Harness::Settings>. The structure is
462 C<< $settings->PREFIX->OPTION >>.
463
464 If you do not specify a C<name> attribute then the default name will be
465 C<PREFIX-TITLE>. The name is the main command line argument, so
466 C<--PREFIX-TITLE> is the default name.
467
468 =item $class->new(type => $type)
469
470 =item $type = $opt->type()
471
472 All options must have a type, if non is specified the default is C<'b'> aka
473 boolean.
474
475 Here are all the possible types, along with their aliases. You may use the type
476 character, or any of the aliases to specify that type.
477
478 =over 4
479
480 =item b bool boolean
481
482 True of false values, will be normalized to 0 or 1 in most cases.
483
484 =item c count counter counting
485
486 Counter, starts at 0 and then increments every time the option is used.
487
488 =item s scalar string number
489
490 Requires an argument which is treated as a scalar value. No type checking is
491 done by the option itself, though you can check it using C<action> or
492 C<normalize> callbacks which are documented under those attributes.
493
494 =item m multi multiple list array
495
496 Requires an argument which is treated as a scalar value. Can be used multiple
497 times. All arguments provided are appended to an array.
498
499 =item d def default
500
501 Argument is optional, scalar when provided. C<--opt=arg> to provide an
502 argument, C<--opt arg> will not work, C<arg> will be seen as its own item on
503 the command line. Can be specified without an arg C<--opt> to signify a default
504 argument should be used (set via the C<action> callback, not the C<default>
505 attribute which is a default value regardless of if the option is used.)
506
507 Real world example from the debug options (simplified for doc purposes):
508
509 option summary => (
510 type => 'd',
511 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.",
512
513 long_examples => ['', '=/path/to/summary.json'],
514
515 # New way to specify an auto-fill value for when no =VAL is provided.
516 # If you do not specify this the default autofill is '1' for legacy support.
517 autofill => 'VALUE',
518
519 # Old way to autofill a value (default is 1 for auto-fill)
520 # Using autofill is significantly better.
521 # You can also use action for additional behavior along with autofill,
522 # but the default will be your auto-fill value, not '1'.
523 action => sub {
524 my ($prefix, $field, $raw, $norm, $slot, $settings) = @_;
525
526 # $norm will be '1' if option was used without an argument, so we
527 # just use the provided value when it is not 1'.
528 return $$slot = $norm unless $norm eq '1';
529
530 # $norm was 1, so this is our no-arg "default" behavior
531
532 # Do nothing if a value is already set
533 return if $$slot;
534
535 # Set the default value of 'summary.json'
536 return $$slot = 'summary.json';
537 },
538 );
539 };
540
541 =item D multi-def multiple-default list-default array-default
542
543 This is a combination of C<d> and C<m>. You can use the opt multiple times to
544 list multiple values, and you can call it without args to add a set of
545 "default" values (not to be confused with THE default attribute, which is used
546 even if the option never appears on the command line.)
547
548 Real world example (simplified for doc purposes):
549
550 option dev_libs => (
551 type => 'D',
552 short => 'D',
553 name => 'dev-lib',
554
555 category => 'Developer',
556 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.',
557
558 long_examples => ['', '=lib'],
559 short_examples => ['', '=lib', 'lib'],
560
561 # New way to specify the auto-fill values. This may be a single scalar,
562 # or an arrayref.
563 autofill => [ 'lib', 'blib/lib', 'blib/arch' ],
564
565 # Old way to specify the auto-fill values.
566 action => sub {
567 my ($prefix, $field, $raw, $norm, $slot, $settings) = @_;
568
569 # If no argument was provided use the 'lib', 'blib/lib', and 'blib/arch' defaults.
570 # If an argument was provided, use it.
571 push @{$$slot} => ($norm eq '1') ? ('lib', 'blib/lib', 'blib/arch') : ($norm);
572 },
573 );
574
575 =item h hash
576
577 The hash type. Each time the option is used it is to add a single key/value pair
578 to the hash. Use an C<=> sign to split the key and value. The option can be
579 used multiple times. A value is required.
580
581 yath --opt foo=bar --opt baz=bat
582
583 =item H hash-list
584
585 Similar to the 'h' type except the key/value pair expects a comma separated
586 list for the value, and it will be placed under the key as an arrayref.
587
588 yath --opt foo=a,b,c --opt bar=1,2,3
589
590 The yath command above would produce this structure:
591
592 {
593 foo => ['a', 'b', 'c'],
594 bar => ['1', '2', '3'],
595 }
596
597 =back
598
599 =item $class->new(title => 'my_title')
600
601 =item $title = $opt->title()
602
603 You B<MUST> specify either a title, or BOTH a name and field. If you only
604 specify a title it will be used to generate the name and field.
605
606 If your title is C<'foo-bar_baz'> then your field will be C<'foo_bar_baz'> and
607 your name will be C<'$PREFIX-foo-bar-baz'>.
608
609 Basically title is used to generate a sane field and/or name if neither are
610 specified. For field all dashes are changed to underscores. The field is used
611 as a key in the settings: C<< $settings->prefix->field >>. For the name all
612 underscores are changed to dashes, if the option is provided by a plugin then
613 C<'prefix-'> is prepended as well. The name is used for the command line
614 argument C<'--name'>.
615
616 If you do not want/like the name and field generated from a title then you can
617 specify a name or title directly.
618
619 =item $class->new(name => 'my-name')
620
621 =item $name = $opt->name()
622
623 You B<MUST> specify either a title, or BOTH a name and field. If you only
624 specify a title it will be used to generate the name and field.
625
626 This name is used as your primary command line argument. If your name is C<foo>
627 then your command line argument is C<--foo>.
628
629 =item $class->new(field => 'my_field')
630
631 =item $field = $opt->field()
632
633 You B<MUST> specify either a title, or BOTH a name and field. If you only
634 specify a title it will be used to generate the name and field.
635
636 The field is used in the settings hash. If your field is C<foo> then your
637 settings path is C<< $setting->prefix->foo >>.
638
639 =back
640
641 =head3 OPTIONAL
642
643 =over 4
644
645 =item $class->new(action => sub ...)
646
647 =item $coderef = $opt->action()
648
649 option foo => (
650 ...,
651 action => sub {
652 my ($prefix, $field_name, $raw_value, $normalized_value, $slot_ref, $settings, $handler, $options) = @_;
653
654 # If no action is specified the following is all that is normally
655 # done. Having an action means this is not done, so if you want the
656 # value stored you must call this or similar.
657 $handler->($slot, $normalized_value);
658 },
659 );
660
661 =over 4
662
663 =item $prefix
664
665 The prefix for the option, specified when the option was defined.
666
667 =item $field_name
668
669 The field for the option, specified when the option was defined.
670
671 =item $raw_value
672
673 The value/argument provided at the command line C<--foo bar> would give us
674 C<"bar">. This is BEFORE any processing/normalizing is done.
675
676 For options that do not take arguments, or where arguments are optional and none are provided, this
677 will be '1'.
678
679 =item $normalized_value
680
681 If a normalize callback was provided this will be the result of putting the
682 $raw_value through the normalize callback.
683
684 =item $slot_ref
685
686 This is a scalar reference to the settings slot that holds the option value(s).
687
688 The default behavior when no action is specified is usually one of these:
689
690 $$slot_ref = $normalized_value;
691 push @{$$slot_ref} => $normalized_value;
692
693 However, to save yourself trouble you can use the C<$handler> instead (see below).
694
695 =item $settings
696
697 The L<Test2::Harness::Settings> instance.
698
699 =item $handler
700
701 A callback that "does the right thing" as far as setting the value in the
702 settings hash. This is what is used when you do not set an action callback.
703
704 $handler->($slot, $normalized_value);
705
706 =item $options
707
708 The L<App::Yath::Options> instance this options belongs to. This is mainly
709 useful if you have an option that may add even more options (such as the
710 C<--plugin> option can do). Note that if you do this you should also set the
711 C<adds_options> attribute to true, if you do not then the options list will not
712 be refreshed and your new options may not show up.
713
714 =back
715
716 =item $class->new(adds_options => $bool)
717
718 =item $bool = $opt->adds_options()
719
720 If this is true then it means using this option could result in more options
721 being available (example: Loading a plugin).
722
723 =item $class->new(alt => ['alt1', 'alt2', ...])
724
725 =item $arrayref = $opt->alt()
726
727 Provide alternative names for the option. These are aliases that can be used to
728 achieve the same thing on the command line. This is mainly useful for
729 backcompat if an option is renamed.
730
731 =item $class->new(builds => 'My::Class')
732
733 =item $my_class = $opt->builds()
734
735 If this option is used in the construction of another object (such as the group
736 it belongs to is composed of options that translate 1-to-1 to fields in another
737 object to build) then this can be used to specify that. The ultimate effect is
738 that an exception will be thrown if that class does not have the correct
739 attribute. This is a safety net to catch errors early if field names change, or
740 are missing between this representation and the object being composed.
741
742 =item $class->new(category => 'My Category')
743
744 =item $category = $opt->category()
745
746 This is used to sort/display help and POD documentation for your option. If you
747 do not provide a category it is set to C<'NO CATEGORY - FIX ME'>. The default
748 value makes sure everyone knows that you do not know what you are doing :-).
749
750 =item $class->new(clear_env_vars => $bool)
751
752 =item $bool = $opt->clear_env_vars()
753
754 This option is only useful when paired with the C<env_vars> attribute.
755
756 Example:
757
758 option foo => (
759 ...
760 env_vars => ['foo', 'bar', 'baz'],
761 clear_env_vars => 1,
762 ):
763
764 In this case you are saying option foo can be set to the value of C<$ENV{foo}>,
765 C<$ENV{bar}>, or C<$ENV{baz}> vars if any are defined. The C<clear_env_vars>
766 tell it to then delete the environment variables after they are used to set the
767 option. This is useful if you want to use the env var to set an option, but do
768 not want any tests to be able to see the env var after it is used to set the
769 option.
770
771 =item $class->new(default => $scalar)
772
773 =item $class->new(default => sub { return $default })
774
775 =item $scalar_or_coderef = $opt->default()
776
777 This sets a default value for the field in the settings hash, the default is
778 set before any command line processing is done, so if the option is never used
779 in the command line the default value will be there.
780
781 Be sure to use the correct default value for your type. A scalar for 's', an
782 arrayref for 'm', etc.
783
784 Note, for any non-scalar type you want to use a subref to define the value:
785
786 option foo => (
787 ...
788 type => 'm',
789 default => sub { [qw/a b c/] },
790 );
791
792 =item $class->new(description => "Fee Fie Foe Fum")
793
794 =item $multiline_string = $opt->description()
795
796 Description of your option. This is used in help output and POD. If you do not
797 provide a value the default is C<'NO DESCRIPTION - FIX ME'>.
798
799 =item $class->new(env_vars => \@LIST)
800
801 =item $arrayref = $opt->env_vars()
802
803 If set, this should be an arrayref of environment variable names. If any of the
804 environment variables are defined then the settings will be updated as though
805 the option was provided on the command line with that value.
806
807 Example:
808
809 option foo => (
810 prefix => 'blah',
811 type => 's',
812 env_vars => ['FOO', 'BAR'],
813 );
814
815 Then command line:
816
817 FOO="xxx" yath test
818
819 Should be the same as
820
821 yath test --foo "xxx"
822
823 You can also ask to have the environment variables cleared after they are checked:
824
825 option foo => (
826 prefix => 'blah',
827 type => 's',
828 env_vars => ['FOO', 'BAR'],
829 clear_env_vars => 1, # This tells yath to clear the env vars after they
830 are used.
831 );
832
833 If you would like the option set to the opposite of the environment variable
834 you can prefix it with a C<'!'> character:
835
836 option foo =>(
837 ...
838 env_vars => ['!FOO'],
839 );
840
841 In this case these are equivalent:
842
843 FOO=0 yath test
844 yath test --foo=1
845
846 Note that this only works when the variable is defined. If C<$ENV{FOO}> is not
847 defined then the variable is not used.
848
849 =item $class->new(from_command => 'App::Yath::Command::COMMAND')
850
851 =item $cmd_class = $opt->from_command()
852
853 If your option was defined for a specific command this will be set. You do not
854 normally set this yourself, the tools in L<App::Yath::Options> usually handle
855 that for you.
856
857 =item $class->new(from_plugin => 'App::Yath::Plugin::PLUGIN')
858
859 =item $plugin_class = $opt->from_plugin()
860
861 If your option was defined for a specific plugin this will be set. You do not
862 normally set this yourself, the tools in L<App::Yath::Options> usually handle
863 that for you.
864
865 =item $class->new(long_examples => [' foo', '=bar', ...])
866
867 =item $arrayref = $opt->long_examples()
868
869 Used for documentation purposes. If your option takes arguments then you can
870 give examples here. The examples should not include the option itself, so
871 C<--foo bar> would be wrong, you should just do C< bar>.
872
873 =item $class->new(negate => sub { ... })
874
875 =item $coderef = $opt->negate()
876
877 If you want a custom handler for negation C<--no-OPT> you can provide one here.
878
879 option foo => (
880 ...
881 negate => sub {
882 my ($prefix, $field, $slot, $settings, $options) = @_;
883
884 ...
885 },
886 );
887
888 The variables are the same as those in the C<action> callback.
889
890 =item $class->new(normalize => sub { ... })
891
892 =item $coderef = $opt->normalize()
893
894 The normalize attribute holds a callback sub that takes the raw value as input
895 and returns the normalized form.
896
897 option foo => (
898 ...,
899 normalize => sub {
900 my $raw = shift;
901
902 ...
903
904 return $norm;
905 },
906 );
907
908 =item $class->new(pre_command => $bool)
909
910 =item $bool = $opt->pre_command()
911
912 Options are either command-specific, or pre-command. Pre-command options are
913 ones yath processes even if it has not determined what command is being used.
914 Good examples are C<--dev-lib> and C<--plugin>.
915
916 yath --pre-command-opt COMMAND --command-opt
917
918 Most of the time this should be false, very few options qualify as pre-command.
919
920 =item $class->new(pre_process => sub { ... })
921
922 =item $coderef = $opt->pre_process()
923
924 This is essentially a BEGIN block for options. This callback is called as soon
925 as the option is parsed from the command line, well before the value is
926 normalized and added to settings. A good use for this is if your option needs
927 to inject additional L<App::Yath::Option> instances into the
928 L<App::Yath::Options> instance.
929
930 option foo => (
931 ...
932
933 pre_process => sub {
934 my %params = @_;
935
936 my $opt = $params{opt};
937 my $options = $params{options};
938 my $action = $params{action};
939 my $type = $params{type};
940 my $val = $params{val};
941
942 ...;
943 },
944 );
945
946 Explanation of parameters:
947
948 =over 4
949
950 =item $params{opt}
951
952 The op instance
953
954 =item $params{options}
955
956 The L<App::Yath::Options> instance.
957
958 =item $params{action}
959
960 A string, usually either "handle" or "handle_negation"
961
962 =item $params{type}
963
964 A string, usually C<"pre-command"> or C<"command ($CLASS)"> where the second
965 has the command package in the parentheses.
966
967 =item $params{val}
968
969 The value being set, if any. For options that do not take arguments, or in the
970 case of negation this key may not exist.
971
972 =back
973
974 =item $class->new(short => $single_character_string)
975
976 =item $single_character_string = $opt->short()
977
978 If you want your option to be usable as a short option (single character,
979 single dash C<-X>) then you can provide the character to use here. If the
980 option does not require an argument then it can be used along with other
981 no-argument short options: C<-xyz> would be equivalent to C<-x -y -z>.
982
983 There are only so many single-characters available, so options are restricted
984 to picking only 1.
985
986 B<Please note:> Yath reserves the right to add any single-character short
987 options in the main distribution, if they conflict with third party
988 plugins/commands then the third party must adapt and change its options. As
989 such it is not recommended to use any short options in third party addons.
990
991 =item $class->new(short_examples => [' foo', ...])
992
993 =item $arrayref = $opt->short_examples()
994
995 Used for documentation purposes. If your option takes arguments then you can
996 give examples here. The examples should not include the option itself, so
997 C<-f bar> would be wrong, you should just do C< bar>.
998
999 This attribute is not used if you do not provide a C<short> attribute.
1000
1001 =item $class->new(trace => [$package, $file, $line])
1002
1003 =item $arrayref = $opt->trace()
1004
1005 This is almost always auto-populated for you via C<caller()>. It should be an
1006 arrayref with a package, filename and line number. This is used if there is a
1007 conflict between parameter names and/or short options. If such a situation
1008 arises the file/line number of all conflicting options will be reported so it
1009 can be fixed.
1010
1011 =back
1012
1013 =head1 METHODS
1014
1015 =over 4
1016
1017 =item $bool = $opt->allows_arg()
1018
1019 True if arguments can be provided to the option (based on type). This does not
1020 mean the option MUST accept arguments. 'D' type options can accept arguments,
1021 but can also be used without arguments.
1022
1023 =item $bool = $opt->applicable($options)
1024
1025 If an option provides an applicability callback this will use it to determine
1026 if the option is applicable given the L<App::Yath::Options> instance.
1027
1028 If no callback was provided then this returns true.
1029
1030 =item $character = $opt->canon_type($type_name)
1031
1032 Given a long alias for an option type this will return the single-character
1033 canonical name. This will return undef for any unknown strings. This will not
1034 translate single character names to themselves, so C<< $opt->canon_type('s') >>
1035 will return undef while C<< $opt->canon_type('string') >> will return C<'s'>.
1036
1037 =item $val = $opt->get_default()
1038
1039 This will return the proper default value for the option. If a custom default
1040 was provided it will be returned, otherwise the correct generic default for the
1041 option type will be used.
1042
1043 Here is a snippet showing the defaults for types:
1044
1045 # First check env vars and return any values from there
1046 ...
1047 # Then check for a custom default and use it.
1048 ...
1049
1050 return 0
1051 if $self->{+TYPE} eq 'c'
1052 || $self->{+TYPE} eq 'b';
1053
1054 return []
1055 if $self->{+TYPE} eq 'm'
1056 || $self->{+TYPE} eq 'D';
1057
1058 return {}
1059 if $self->{+TYPE} eq 'h'
1060 || $self->{+TYPE} eq 'H';
1061
1062 # All others get undef
1063 return undef;
1064
1065 =item $val $opt->get_normalized($raw)
1066
1067 This converts a raw value to a normalized one. If a custom C<normalize>
1068 attribute was set then it will be used, otherwise it is normalized in
1069 accordance to the type.
1070
1071 This is where booleans are turned into 0 or 1, hashes are split, hash-lists are
1072 split further, etc.
1073
1074 =item $opt->handle($raw, $settings, $options, $list)
1075
1076 This method handles setting the value in $settings. You should not normally
1077 need to call this yourself.
1078
1079 =item $opt->handle_negation()
1080
1081 This method is used to handle a negated option. You should not normally need to
1082 call this yourself.
1083
1084 =item @list = $opt->long_args()
1085
1086 Returns the name and any aliases.
1087
1088 =item $ref = $opt->option_slot($settings)
1089
1090 Get the settings->prefix->field reference. This creates the setting field if
1091 necessary.
1092
1093 =item $bool = $opt->requires_arg()
1094
1095 Returns true if this option requires an argument when used.
1096
1097 =item $string = $opt->trace_string()
1098
1099 return a string like C<"somefile.pm line 42"> based on where the option was
1100 defined.
1101
1102 =item $bool = $opt->valid_type($character)
1103
1104 Check if a single character type is valid.
1105
1106 =back
1107
1108 =head2 DOCUMENTATION GENERATION
1109
1110 =over 4
1111
1112 =item $string = $opt->cli_docs()
1113
1114 Get the option documentation in a format that works for the C<yath help
1115 COMMAND> command.
1116
1117 =item $string = $opt->pod_docs()
1118
1119 Get the option documentation in POD format.
1120
1121 =item ....
1122
1123 .. option details ...
1124
1125 =back
1126
1127 =head1 SOURCE
1128
1129 The source code repository for Test2-Harness can be found at
1130 F<http://github.com/Test-More/Test2-Harness/>.
1131
1132 =head1 MAINTAINERS
1133
1134 =over 4
1135
1136 =item Chad Granum E<lt>[email protected]<gt>
1137
1138 =back
1139
1140 =head1 AUTHORS
1141
1142 =over 4
1143
1144 =item Chad Granum E<lt>[email protected]<gt>
1145
1146 =back
1147
1148 =head1 COPYRIGHT
1149
1150 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
1151
1152 This program is free software; you can redistribute it and/or
1153 modify it under the same terms as Perl itself.
1154
1155 See F<http://dev.perl.org/licenses/>
1156
1157 =cut