blib/lib/App/karr/Role/CliArgs.pm

filter: Statementstmt 6.5% 5 / 76 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 14.2% 1 / 7 Podpod 100% 3 / 3 totaltotal 6.2% 9 / 144 CC 29 SCAR 43.9
CC
29
Cov
4%
_classify_argv
156.0
normalize_option_argv
72.0
_abbreviation_takes_value
42.0
CRAP 80.5
« blib/lib/App/karr/Role/PickRules.pm ↑ Summary blib/lib/App/karr/Cmd/Repair.pm »
1 # ABSTRACT: Role providing option-aware CLI positional-argument parsing
2  
3 package App::karr::Role::CliArgs;
4 28 our $VERSION = '0.602';
5 28 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7  
8 # Walk argv once and record what part each token plays: an option flag, the
9 # value an option consumed, the bare "--" separator, or a positional. Both
10 # readers below ask the same question of the same table, so it is answered in
11 # one place and filtered afterwards -- positional_args keeps the positionals,
12 # normalize_option_argv rewrites the flags.
13 #
14 # The walk exists to extract the real positional arguments from the argv
15 # MooX::Cmd echoes back into execute(). Because MooX::Options runs with
16 # protect_argv (its default), the array handed to execute() still holds every
17 # original token in order:
18 # recognised option flags, the values they consumed, and --opt=value forms
19 # included (e.g. `move --claim tester 1 in-progress` arrives verbatim as
20 # [--claim, tester, 1, in-progress]). This gives cobra-style freedom to place
21 # flags before, between, or after positionals -- we just have to subtract the
22 # option tokens back out.
23 #
24 # We do that by walking the argv against the command's own %{_options_data}:
25 # a dash token is an option; if that option takes a value (has a 'format') and
26 # is given in space form (no inline '='), it also swallows the following token
27 # as its value -- even a flag-shaped value like `--append-body --weird`.
28 # Everything not eaten as an option or an option value is a positional, in
29 # order. Option-name matching mirrors how the token reaches us: leading dashes
30 # stripped, '-' folded to '_' to hit the underscore keys in _options_data, plus
31 # a reverse map of short aliases (e.g. -a => append_body, -t => timestamp).
32 # A token that is not a full name falls through to _abbreviation_takes_value
33 # below, because an abbreviation of a value-taking option consumes its value
34 # just as the full spelling does (ticket #247).
35 #
36 # A bare "--" is the POSIX end-of-options separator: everything after it is a
37 # positional, however option-shaped it looks. Getopt::Long already honours it
38 # when parsing (so `karr create -- --json` never tries to parse --json as a
39 # flag), but protect_argv hands the ORIGINAL argv -- separator included -- back
40 # to execute(), so without this branch the walk below re-read the escaped tokens
41 # as options and dropped them, leaving no positional at all. That was ticket
42 # #72: an option-shaped title could only be passed via --title.
43 0 ▶sub _classify_argv {
Subroutine _classify_argv: not called CC=12 SCAR=50.5
44 0 my ($self, $args_ref) = @_;
45  
46 0 my %options_data = $self->_options_data;
47 0 my %by_name;
48 # %long_by_alias is the DECLARED short spelling of an option, not a prefix
49 # rule: normalize_option_argv needs a `--long` carrier when it has to hand
50 # a flag-shaped value over inline, and `-a=VALUE` is not one (Getopt::Long
51 # reads the `=` as the first character of the value for a short option).
52 # Resolving a declared alias is not the abbreviation question
53 # _abbreviation_takes_value refuses to answer -- that one asks WHICH option
54 # a prefix names, and it is still not asked anywhere here.
55 my %long_by_alias;
56 0 for my $name (keys %options_data) {
57 0 $by_name{$name} = $options_data{$name};
58 0 my $short = $options_data{$name}{short};
59 0 ▶ next unless defined $short;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $short 0 0 0
60 0 for my $alias (split /\|/, $short) {
61 0 $by_name{$alias} = $options_data{$name};
62 0 $long_by_alias{$alias} = $name;
63 }
64 }
65  
66 0 my @classified;
67 0 my @args = @$args_ref;
68 0 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 0 0 0
69 0 my $arg = shift @args;
70 0 ▶ if ($arg eq '--') {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg eq "--") 0 0 0
71 0 push @classified, [ $arg, 'separator' ];
72 0 push @classified, map { [ $_, 'positional' ] } @args;
73 0 last;
74 }
75 0 ▶ if ($arg =~ /^-/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg =~ /^-/) 0 0 0
76 0 (my $name = $arg) =~ s/^-+//; # drop leading dashes
77 0 my $has_inline = $name =~ s/=.*//s; # --opt=value carries its value
78 0 $name =~ tr/-/_/; # match underscore keys
79 0 my $data = $by_name{$name};
80 my $takes_value =
81 $data
82 0 ▶ ? ( defined $data->{format} ? 1 : 0 )
Branch: 2 branches
BranchTrueFalseTotal
$data ? : 0 0 0
defined $data->{'format'} ? : 0 0 0
83 : $self->_abbreviation_takes_value( $name, \%options_data );
84 0 push @classified, [ $arg, 'option', $long_by_alias{$name} ];
85 0 ▶ push @classified, [ shift(@args), 'value' ]
Branch: 1 branch
BranchTrueFalseTotal
if $takes_value and not $has_inline and @args 0 0 0
Condition0%0/6
$takes_value and not $has_inline and @args
!ll&&!rl&&r
000
$takes_value and not $has_inline
!ll&&!rl&&r
000
MC/DC0%0/3
$takes_value and not $has_inline and @args
$takes_value not $has_inline @args
Truth table0%0/4
A and not(B) and C
A= $takes_valueB= not $has_inlineC= @args
ABCresult
0XX0
10X0
1100
1111
86 if $takes_value && !$has_inline && @args;
87 0 next;
88 }
89 0 push @classified, [ $arg, 'positional' ];
90 }
91 0 return @classified;
92 }
93  
94 0 ▶sub positional_args {
Subroutine positional_args: not called CC=1 SCAR=6.9
Pod documented
95 0 my ($self, $args_ref) = @_;
96  
97 0 return map { $_->[0] }
98 0 grep { $_->[1] eq 'positional' } $self->_classify_argv($args_ref);
99 }
100  
101  
102 # Spell every option flag in argv the way Getopt::Long will be told to expect
103 # it: underscores, not dashes. F<bin/karr> runs this over argv before MooX::Cmd
104 # dispatches, because MooX::Options cannot be relied on to do it for a flag that
105 # follows another flag (ticket #256).
106 #
107 # MooX::Options is what makes the dashed spelling work at all: nothing declares
108 # --claimed-by, the attribute is claimed_by, and
109 # MooX::Options::Role::_options_fix_argv (4.103, line 148) folds '-' to '_' in
110 # every option name it walks past before Getopt::Long is called. The walk misses
111 # exactly one position. Having recognised an option, it takes the next token as
112 # that option's value unconditionally (line 171-172, `defined $original_long_option
113 # && ( defined( my $arg_value = shift @ARGV ) )`) and re-emits it verbatim --
114 # no fold, no short-option split. For an option that really takes a value that
115 # is right and harmless. For a BOOLEAN the next token is the next flag, which
116 # therefore reaches Getopt::Long still dashed, under a name the generated
117 # specification does not have:
118 #
119 # karr list --claimed-by NAME works
120 # karr list --json --claimed-by NAME Unknown option: claimed-by (exit 2)
121 # karr list --not-blocked --compact works
122 # karr list --compact --not-blocked Unknown option: not-blocked (exit 2)
123 #
124 # Nothing is wrong with the second spelling of either pair; the flag in front of
125 # it is. All nineteen karr options whose attribute name has an underscore were
126 # reachable only in the orders that happen to avoid that position -- --add-tag,
127 # --append-body, --depends-on, --write-to, --show-no-board and fourteen more.
128 #
129 # The question asked here is the weaker one that #247 settled on: not what an
130 # option means, only whether it takes a value. Folding a flag's own dashes is
131 # always safe -- _options_fix_argv folds the very same characters one step later
132 # for every flag it does reach, so an unknown --bogus-opt still reports
133 # "Unknown option: bogus_opt" exactly as before -- and the thing that must NOT
134 # be folded is a value that merely looks like a flag (`karr edit 1 --body
135 # --we-ird` stores --we-ird). _classify_argv already separates those two, so
136 # this is a walk over its answer: flags are folded, and a flag-shaped value is
137 # handed to its own option inline, which is the half ticket #259 added and
138 # which the loop below explains where it happens. A leading `no-` is left
139 # standing so that the negation prefix keeps reaching _options_fix_argv as
140 # such, for the day a karr option is declared negatable.
141 #
142 # This can go when _options_fix_argv puts the token it swallows through the same
143 # rewriting as the token it recognised -- i.e. when the MooX::Options this
144 # distribution requires no longer has the unconditional shift at line 171. 4.103
145 # is the current release and still does; nothing here needs to change if it is
146 # fixed, the fold simply becomes a second, identical fold.
147 0 ▶sub normalize_option_argv {
Subroutine normalize_option_argv: not called CC=8 SCAR=42.8
Pod documented
148 0 my ($self, $args_ref) = @_;
149  
150 0 my @classified = $self->_classify_argv($args_ref);
151 0 my @out;
152 0 for my $i ( 0 .. $#classified ) {
153 0 my ( $token, $kind, $long ) = @{ $classified[$i] };
154  
155 0 ▶ if ( $kind eq 'option' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "option") 0 0 0
156 0 push @out, $self->_underscore_option_name($token);
157 0 next;
158 }
159  
160 # The other half of the same upstream shift (ticket #259). A value
161 # that merely looks like a flag is safe in space form only while
162 # _options_fix_argv reaches the option in front of it; when something
163 # it recognises stands one place earlier it swallows THAT option as
164 # its own value, and this token arrives in flag position and is
165 # folded -- `karr edit 1 --json -a --dashed-note` stored
166 # --dashed_note. Handing the value over inline settles it in every
167 # position: `--opt=VALUE` is one token, _options_fix_argv splits it
168 # itself and re-emits the half after the `=` verbatim, and a swallowed
169 # `--opt=VALUE` reaches Getopt::Long as the assignment it already was.
170 #
171 # Which option this is has not been asked -- _classify_argv decided
172 # this token is a value, which is #247's weaker question, and the
173 # carrier is the option's own spelling. Only a DECLARED short alias is
174 # resolved, because `-a=VALUE` is not an assignment to Getopt::Long;
175 # an abbreviation keeps its own spelling (`--prio=--weird`), so no
176 # prefix rule is reimplemented here.
177 0 ▶ if ( $kind eq 'value' && $token =~ /\A-/ && @out ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "value" and $token =~ /\A-/ and @out) 0 0 0
Condition0%0/6
$kind eq "value" and $token =~ /\A-/ and @out
!ll&&!rl&&r
000
$kind eq "value" and $token =~ /\A-/
!ll&&!rl&&r
000
MC/DC0%0/3
$kind eq "value" and $token =~ /\A-/ and @out
$kind eq "value" $token =~ /\A-/ @out
Truth table0%0/4
A and B and C
A= $kind eq "value"B= $token =~ /\A-/C= @out
ABCresult
0XX0
10X0
1100
1111
178 0 ▶ my $carrier = defined $classified[ $i - 1 ][2]
Branch: 1 branch
BranchTrueFalseTotal
defined $classified[$i - 1][2] ? : 0 0 0
179 ? '--' . $classified[ $i - 1 ][2]
180 : $out[-1];
181 0 ▶ if ( $carrier =~ /\A--/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($carrier =~ /\A--/) 0 0 0
182 0 $out[-1] = $carrier . '=' . $token;
183 0 next;
184 }
185 }
186  
187 0 push @out, $token;
188 }
189 0 return @out;
190 }
191  
192  
193 0 ▶sub _underscore_option_name {
Subroutine _underscore_option_name: not called CC=3 SCAR=24.8
194 0 my ($self, $token) = @_;
195  
196 0 ▶ return $token unless $token =~ /\A--(no-)?([^=]*)(.*)\z/s;
Branch: 1 branch
BranchTrueFalseTotal
unless $token =~ /\A--(no-)?([^=]*)(.*)\z/s 0 0 0
197 0 my ($negation, $name, $rest) = ($1, $2, $3);
198 0 $name =~ tr/-/_/;
199 0 ▶ return '--' . (defined $negation ? $negation : '') . $name . $rest;
Branch: 1 branch
BranchTrueFalseTotal
defined $negation ? : 0 0 0
200 }
201  
202 # Does a dash token that is not a full option name consume the token after it?
203 #
204 # Before ticket #247 the answer was always no, on the reasoning that karr's
205 # abbreviatable flags consume nothing anyway. That was true once; --title,
206 # --priority, --body, --claim and --note have taken values for a long time, so
207 # `karr edit 1 --prio high` handed "high" to the positionals and
208 # check_positional_args then reported the caller's value as the surplus
209 # argument -- pointing at the value while the mistake sat in the abbreviation
210 # in front of it.
211 #
212 # The question deliberately answered here is weaker than "which option is
213 # this?", because karr must not carry a second implementation of anybody's
214 # abbreviation rules. Prefix resolution happens twice upstream and neither
215 # copy is ours: MooX::Options::Role::_options_fix_argv rewrites a prefix that
216 # matches exactly one option to its full name before Getopt::Long is called,
217 # and Getopt::Long resolves (or rejects, "Option ti is ambiguous (timestamp,
218 # title)") whatever is left. So by the time argv is echoed back into
219 # execute(), every abbreviation still present resolved to exactly one option
220 # and an ambiguous one exited 2 long before -- which means we only have to ask
221 # whether the options this token could possibly abbreviate agree about taking
222 # a value, never which of them won. Both engines match on a plain,
223 # case-sensitive prefix (--PRIORITY is "Unknown option" here), so a prefix test
224 # is the whole of it.
225 #
226 # No candidate at all is the unchanged non-consuming answer: an inline-value
227 # short (-anote, which MooX::Options splits itself), the --h/--help/--man/
228 # --usage family that describe_options adds outside %{_options_data}, or a
229 # typo, which was rejected upstream before it could reach us. Candidates that
230 # disagree cannot occur -- that is the ambiguous spelling, and it never got
231 # here -- and answer no, keeping the pre-#247 behaviour for a shape that would
232 # otherwise have no defined answer.
233 0 ▶sub _abbreviation_takes_value {
Subroutine _abbreviation_takes_value: not called CC=6 SCAR=37.4
234 0 my ( $self, $name, $options_data ) = @_;
235  
236 0 my @candidates = grep { index( $_, $name ) == 0 } keys %$options_data;
237 0 ▶ return 0 unless @candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @candidates 0 0 0
238  
239 0 ▶ my $takes_value = defined $options_data->{ $candidates[0] }{format} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $$options_data{$candidates[0]}{'format'} ? : 0 0 0
240 0 for my $candidate (@candidates) {
241 return 0
242 0 ▶ if ( defined $options_data->{$candidate}{format} ? 1 : 0 ) != $takes_value;
Branch: 2 branches
BranchTrueFalseTotal
if (defined $options_data->{$candidate}{"format"} ? 1 : 0) != $takes_value 0 0 0
defined $options_data->{$candidate}{'format'} ? : 0 0 0
243 }
244 0 return $takes_value;
245 }
246  
247 # Reject surplus positional arguments before a command does any work, matching
248 # kanban-md's cobra Args validators (ExactArgs/RangeArgs/MaximumNArgs) which
249 # refuse extra positionals ahead of RunE. The comma list stays the one and only
250 # batch syntax; there is no space-separated id batch. Counting is done against
251 # positional_args (the real positionals with option tokens subtracted out), not
252 # a leading run of non-dash tokens, so `archive 1 --json 99` correctly rejects
253 # the trailing "99" instead of silently dropping it.
254 0 ▶sub check_positional_args {
Subroutine check_positional_args: not called CC=4 SCAR=30.0
Pod documented
255 0 my ($self, $args_ref, $max) = @_;
256  
257 0 my @positional = $self->positional_args($args_ref);
258 0 ▶ return if @positional <= $max;
Branch: 1 branch
BranchTrueFalseTotal
if @positional <= $max 0 0 0
259  
260 0 my @extra = @positional[$max .. $#positional];
261 0 my %config = $self->_options_config;
262 0 my $usage = $config{usage_string};
263  
264 die sprintf "unexpected extra argument%s: %s\n%s",
265 (@extra == 1 ? '' : 's'),
266 0 ▶ join(', ', map { "'$_'" } @extra),
Branch: 2 branches
BranchTrueFalseTotal
@extra == 1 ? : 0 0 0
$usage ? : 0 0 0
267 ($usage ? "$usage\n" : '');
268 }
269  
270  
271 28 1;
272  
273 __END__
« blib/lib/App/karr/Role/PickRules.pm ↑ Summary blib/lib/App/karr/Cmd/Repair.pm »