CLI/Role/CommandSet.pm

filter: Statementstmt 98.2% 164 / 167 Branchbran 82.1% 46 / 56 Conditioncond 69.5% 16 / 23 MC/DCmcdc 46.6% 7 / 15 Subroutinesub 96.4% 27 / 28 Podpod 100% 12 / 12 totaltotal 90.3% 272 / 301 CC 40 SCAR 14.8
CC
40
Cov
92%
_get_command_list
12.1
readline
6.0
_trigger__command_list
5.1
CRAP 4.4
« CLI/L10N/nl.pm ↑ Summary CLI/Argument/Tree.pm »
1 #=============================================================================
2 #
3 # Module: Term::CLI::CommandSet
4 #
5 # Description: Class for sets of (sub-)commands in Term::CLI
6 #
7 # Author: Steven Bakker (SBAKKER), <sbakker@cpan.org>
8 # Created: 05/02/18
9 #
10 # Copyright (c) 2018-2022 Steven Bakker
11 #
12 # This module is free software; you can redistribute it and/or modify
13 # it under the same terms as Perl itself. See "perldoc perlartistic."
14 #
15 # This software is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 #
19 #=============================================================================
20  
21 package Term::CLI::Role::CommandSet 0.061000;
22  
23 7 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 7 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
27 7 ▶use Scalar::Util qw( reftype );
Subroutine BEGIN: called CC=1 SCAR=0.0
28 7 ▶use Term::CLI::L10N qw( loc );
Subroutine BEGIN: called CC=1 SCAR=0.0
29 7 ▶use Term::CLI::Util qw( find_obj_name_matches );
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 7 use Types::Standard 1.000005 qw(
32 ArrayRef
33 Bool
34 CodeRef
35 InstanceOf
36 ConsumerOf
37 Maybe
38 7 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 7 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 7 ▶use namespace::clean 0.25;
Subroutine BEGIN: called CC=1 SCAR=0.0
42  
43 7 my $ERROR_STATUS = -1;
44  
45 7 requires qw( parent root_node );
46  
47 7 has '+parent' => (
48 is => 'rwp',
49 weak_ref => 1,
50 isa => Maybe[ ConsumerOf ['Term::CLI::Role::CommandSet'] ],
51 );
52  
53 has _command_list => (
54 is => 'rw',
55 isa => Maybe [ArrayRef|CodeRef],
56 init_arg => 'commands',
57 writer => '_set_command_list',
58 trigger => 1,
59 coerce => sub {
60 14 ▶ my ($arg) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.0
61 14 ▶ if (ref $arg && reftype $arg eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $arg and builtin::reftype($arg) eq "ARRAY") 13 1 14
Condition66%2/3
ref $arg and builtin::reftype($arg) eq "ARRAY"
!ll&&!rl&&r
0113
MC/DC50%1/2
ref $arg and builtin::reftype($arg) eq "ARRAY"
ref $arg builtin::reftype($arg) eq "ARRAY"
Truth table66%2/3
A and B
A= ref $argB= builtin::reftype($arg) eq "ARRAY"
ABresult
0X0
100
111
62 # clone and sort array.
63 13 return [ sort { $a->name cmp $b->name } @{$arg} ];
64 }
65 1 return $arg;
66 }
67 7 );
68  
69 7 has callback => (
70 is => 'rw',
71 isa => Maybe [CodeRef],
72 predicate => 1
73 );
74  
75 has require_sub_command => (
76 is => 'ro',
77 isa => Bool,
78 54 ▶ default => sub { 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
79 7 );
80  
81 # $self->_set_command_list($ref) => $self->_trigger__command_list($ref);
82 #
83 # Trigger to run whenever the object's _commands array ref is set.
84 #
85 sub _trigger__command_list { ## no critic (ProhibitUnusedPrivateSubroutines)
86 14 ▶ my ( $self, $cmd_list ) = @_;
Subroutine _trigger__command_list: called CC=5 SCAR=16.2
87  
88 14 ▶ return if !$cmd_list;
Branch: 1 branch
BranchTrueFalseTotal
unless $cmd_list 0 14 14
89  
90 # Set the parent for each command object.
91 14 ▶ if (ref $cmd_list && reftype $cmd_list eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cmd_list and builtin::reftype($cmd_list) eq "ARRAY") 13 1 14
Condition66%2/3
ref $cmd_list and builtin::reftype($cmd_list) eq "ARRAY"
!ll&&!rl&&r
0113
MC/DC50%1/2
ref $cmd_list and builtin::reftype($cmd_list) eq "ARRAY"
ref $cmd_list builtin::reftype($cmd_list) eq "ARRAY"
Truth table66%2/3
A and B
A= ref $cmd_listB= builtin::reftype($cmd_list) eq "ARRAY"
ABresult
0X0
100
111
92 13 for my $cmd_obj ( @{$cmd_list} ) {
93 27 $cmd_obj->_set_parent($self);
94 }
95 }
96 14 return;
97 }
98  
99 # Get the command list reference, expand a CODE ref if necessary.
100 sub _get_command_list {
101 255 ▶ my ($self) = @_;
Subroutine _get_command_list: called CC=8 SCAR=24.9
102  
103 255 my $command_list = $self->_command_list;
104  
105 255 ▶ return undef if !ref $command_list;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $command_list 61 194 255
106  
107 194 ▶ return $command_list if reftype $command_list eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if builtin::reftype($command_list) eq "ARRAY" 193 1 194
108  
109 1 ▶ if (reftype $command_list ne 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::reftype($command_list) ne "CODE") 0 1 1
110 0 croak "internal error: 'command' ($command_list) is ",
111 "neither a CodeRef nor an ArrayRef!";
112 }
113  
114 1 $command_list = $command_list->($self);
115  
116 1 ▶ if (!ref $command_list || reftype $command_list ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $command_list or builtin::reftype($command_list) ne "ARRAY") 0 1 1
Condition33%1/3
not ref $command_list or builtin::reftype($command_list) ne "ARRAY"
l!l&&r!l&&!r
001
MC/DC0%0/2
not ref $command_list or builtin::reftype($command_list) ne "ARRAY"
not ref $command_list builtin::reftype($command_list) ne "ARRAY"
Truth table33%1/3
not(A) or B
A= not ref $command_listB= builtin::reftype($command_list) ne "ARRAY"
ABresult
1X1
011
000
117 0 ▶ croak "'command' CodeRef should return an ARRAY ref, not ",
Branch: 2 branches
BranchTrueFalseTotal
ref $command_list ? : 0 0 0
defined $command_list ? : 0 0 0
118 ref $command_list ? reftype( $command_list ) :
119 defined $command_list ? "'$command_list'" :
120 '(undef)';
121 }
122  
123 1 return $self->_set_command_list($command_list);
124 }
125  
126 sub commands {
127 14 ▶ my ($self) = @_;
Subroutine commands: called CC=2 SCAR=7.0
Pod documented
128 14 ▶ my $command_list = $self->_get_command_list // [];
Condition50%1/2
$self->_get_command_list // []
l!l
140
MC/DC0%0/1
$self->_get_command_list // []
$self->_get_command_list
Truth table50%1/2
A
A= $self->_get_command_list
Aresult
11
00
129 14 return @{ $command_list };
130 }
131  
132 sub command_names {
133 24 ▶ my ($self) = @_;
Subroutine command_names: called CC=2 SCAR=6.9
Pod documented
134 24 ▶ my $command_list = $self->_get_command_list or return;
Branch: 1 branch
BranchTrueFalseTotal
my $command_list = $self->_get_command_list or return 1 23 24
135 23 my @l = map { $_->name } @{$command_list};
136 23 return @l;
137 }
138  
139 sub has_commands {
140 104 ▶ my ($self) = @_;
Subroutine has_commands: called CC=2 SCAR=6.9
Pod documented
141 104 ▶ my $command_list = $self->_get_command_list or return !1;
Branch: 1 branch
BranchTrueFalseTotal
my $command_list = $self->_get_command_list or 57 47 104
142 47 return scalar( @{$command_list} ) > 0;
143 }
144  
145 sub add_command {
146 3 ▶ my ( $self, @commands ) = @_;
Subroutine add_command: called CC=3 SCAR=11.0
Pod documented
147  
148 3 my $cmd_list = $self->_get_command_list;
149  
150 3 ▶ if (!$cmd_list) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cmd_list) 1 2 3
151 1 $cmd_list = \@commands;
152 1 $self->_set_command_list($cmd_list);
153 1 return $self;
154 }
155  
156 2 for my $cmd_obj ( @commands ) {
157 15 $cmd_obj->_set_parent( $self );
158 }
159  
160 2 push @{$cmd_list}, @commands;
161 2 @{$cmd_list} = sort { $a->name cmp $b->name } @{$cmd_list};
162  
163 2 return $self;
164 }
165  
166 sub delete_command {
167 1 ▶ my ( $self, @commands ) = @_;
Subroutine delete_command: called CC=5 SCAR=16.1
Pod documented
168  
169 1 ▶ my $cmd_list = $self->_get_command_list or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cmd_list = $self->_get_command_list or return 0 1 1
170  
171 1 ▶ my %to_delete = map { (ref $_ ? $_->name : $_ ) => 1 } @commands;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 1 1
172  
173 1 my @deleted;
174  
175 1 for my $index (reverse 0..$#{$cmd_list}) {
176 15 my $cmd_obj = $cmd_list->[$index];
177 15 ▶ if ( $to_delete{$cmd_obj->name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($to_delete{$cmd_obj->name}) 1 14 15
178 1 my $cmd_obj = splice @{$cmd_list}, $index, 1;
179 1 $cmd_obj->_set_parent(undef);
180 1 push @deleted, $cmd_obj;
181 }
182 }
183 1 return @deleted;
184 }
185  
186 sub find_matches {
187 2 ▶ my ( $self, $text ) = @_;
Subroutine find_matches: called CC=1 SCAR=0.0
Pod documented
188 2 return find_obj_name_matches($text, $self->_get_command_list);
189 }
190  
191 sub find_command {
192 107 ▶ my ( $self, $text ) = @_;
Subroutine find_command: called CC=4 SCAR=13.9
Pod documented
193  
194 107 my @matches = find_obj_name_matches(
195 $text, $self->_get_command_list, exact => 1 );
196  
197 107 ▶ return $self->set_error( loc( "unknown command '[_1]'", $text ) )
Branch: 1 branch
BranchTrueFalseTotal
if @matches == 0 8 99 107
198 if @matches == 0;
199  
200 99 ▶ return $matches[0] if @matches == 1 || $matches[0]->name eq $text;
Branch: 1 branch
BranchTrueFalseTotal
if @matches == 1 or $matches[0]->name eq $text 98 1 99
Condition66%2/3
@matches == 1 or $matches[0]->name eq $text
l!l&&r!l&&!r
9801
MC/DC50%1/2
@matches == 1 or $matches[0]->name eq $text
@matches == 1 $matches[0]->name eq $text
Truth table66%2/3
A or B
A= @matches == 1B= $matches[0]->name eq $text
ABresult
1X1
011
000
201  
202 return $self->set_error(
203 loc("ambiguous command '[_1]' (matches: [_2])",
204 $text,
205 1 join( ', ', map { $_->name } @matches )
206 )
207 );
208 }
209  
210 sub try_callback {
211 94 ▶ my ( $self, %args ) = @_;
Subroutine try_callback: called CC=3 SCAR=11.0
Pod documented
212  
213 94 ▶ if ( $self->has_callback && defined $self->callback ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_callback and defined $self->callback) 29 65 94
Condition100%3/3
$self->has_callback and defined $self->callback
!ll&&!rl&&r
313429
MC/DC100%2/2
$self->has_callback and defined $self->callback
$self->has_callback defined $self->callback
Truth table100%3/3
A and B
A= $self->has_callbackB= defined $self->callback
ABresult
0X0
100
111
214 29 return $self->callback->( $self, %args );
215 }
216 65 return %args;
217 }
218  
219 # CLI->_set_completion_attribs();
220 #
221 # Set some attributes in the Term::ReadLine object related to
222 # custom completion.
223 #
224 sub _set_completion_attribs {
225 47 ▶ my ($self) = @_;
Subroutine _set_completion_attribs: called CC=1 SCAR=0.0
226 47 my $root = $self->root_node;
227 47 my $term = $root->term;
228  
229  
230 # set Completion for current object
231 47 ▶ $term->Attribs->{completion_function} = sub { $self->complete_line( @_ ) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
232  
233 # Default: '"
234 47 $term->Attribs->{completer_quote_characters} = $root->quote_characters;
235  
236 # Default: \n\t\\"'`@$><=;|&{( and <space>
237 47 $term->Attribs->{completer_word_break_characters} = $root->word_delimiters;
238  
239 # Default: <space>
240 $term->Attribs->{completion_append_character} =
241 47 substr( $root->word_delimiters, 0, 1 );
242  
243 47 return;
244 }
245  
246 # See POD X<complete_line>
247 sub complete_line {
248 37 ▶ my ( $self, $text, $line, $start ) = @_;
Subroutine complete_line: called CC=5 SCAR=16.1
Pod documented
249  
250 37 my $root = $self->root_node;
251  
252 37 $self->_set_completion_attribs;
253  
254 37 my $quote_char = $self->term->completion_quote_character;
255  
256 37 my @words;
257  
258 37 ▶ if ( $start > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($start > 0) 35 2 37
259 35 ▶ if ( length $quote_char ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $quote_char) 1 34 35
260  
261 # ReadLine thinks the $text to be completed is quoted.
262 # The quote character will precede the $start of $text.
263 # Make sure we do not include it in the text to break
264 # into words...
265 1 $start--;
266 }
267 35 ( my $err, @words ) =
268 $root->_split_line( substr( $line, 0, $start ) );
269 }
270  
271 37 my @list;
272  
273 37 $text = $root->unescape_input($text, $quote_char);
274  
275 37 ▶ if ( @words == 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if (@words == 0) { } 2 35 37
elsif (my $cmd = $self->find_command($words[0])) { } 34 1 35
276 2 @list = map { $_->name } $self->find_matches( $text );
277 }
278 elsif ( my $cmd = $self->find_command( $words[0] ) ) {
279 34 shift @words;
280 34 @list = $cmd->complete(
281 $text => {
282 processed => [{
283 element => $cmd,
284 value => $cmd->name,
285 }],
286 unprocessed => \@words,
287 options => {},
288 }
289 );
290 }
291  
292 # Escape spaces/delimiters in reply again if necessary.
293 37 return map { $self->escape_input($_, $quote_char) } @list;
294 }
295  
296 sub readline { ## no critic (ProhibitBuiltinHomonyms)
297 3 ▶ my ( $self, %args ) = @_;
Subroutine readline: called CC=6 SCAR=18.0
Pod documented
298  
299 3 my $root = $self->root_node;
300  
301 3 ▶ my $prompt = $args{prompt} // $self->prompt;
Condition66%2/3
$args{"prompt"} // $self->prompt
l!l&&r!l&&!r
210
MC/DC0%0/2
$args{"prompt"} // $self->prompt
$args{"prompt"} $self->prompt
Truth table66%2/3
A // B
A= $args{"prompt"}B= $self->prompt
ABresult
1X1
011
000
302 3 ▶ my $skip = exists $args{skip} ? $args{skip} : $root->skip;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'skip'} ? : 1 2 3
303  
304 3 $self->_set_completion_attribs;
305  
306 3 my $input;
307 3 ▶ while ( defined( $input = $root->term->readline($prompt) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($input = $root->term->readline($prompt))) 6 0 6
308 6 ▶ next if defined $skip && $input =~ $skip;
Branch: 1 branch
BranchTrueFalseTotal
if defined $skip and $input =~ /$skip/u 3 3 6
Condition100%3/3
defined $skip and $input =~ /$skip/u
!ll&&!rl&&r
123
MC/DC100%2/2
defined $skip and $input =~ /$skip/u
defined $skip $input =~ /$skip/u
Truth table100%3/3
A and B
A= defined $skipB= $input =~ /$skip/u
ABresult
0X0
100
111
309 3 last;
310 }
311 3 return $input;
312 }
313  
314 # OBJ->_split_line( $text );
315 #
316 # Attempt to split $text into words. Use a custom split function if
317 # necessary.
318 #
319 sub _split_line {
320 86 ▶ my ( $self, $text ) = @_;
Subroutine _split_line: called CC=1 SCAR=0.0
321 86 my $root_node = $self->root_node;
322 86 return $root_node->split_function->( $root_node, $text );
323 }
324  
325 39 ▶sub execute { return shift->execute_line(@_) } ## DEPRECATED
Subroutine execute: called CC=1 SCAR=0.0
Pod documented
326  
327 sub execute_line {
328 48 ▶ my ( $self, $cmd ) = @_;
Subroutine execute_line: called CC=4 SCAR=13.9
Pod documented
329  
330 48 my ( $error, @cmd ) = $self->_split_line($cmd);
331  
332 48 my %args = (
333 status => 0,
334 error => q{},
335 command_line => $cmd,
336 command_path => [$self],
337 unprocessed => \@cmd,
338 processed => [],
339 options => {},
340 arguments => [],
341 );
342  
343 48 $args{unparsed} = $args{unprocessed};
344  
345 48 ▶ return $self->try_callback( %args, status => $ERROR_STATUS,
Branch: 1 branch
BranchTrueFalseTotal
if length $error 1 47 48
346 error => $error )
347 if length $error;
348  
349 47 ▶ if ( @cmd == 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if (@cmd == 0) { } 1 46 47
elsif (my $cmd_ref = $self->find_command($cmd[0])) { } 45 1 46
350 1 $args{error} = loc("missing command");
351 1 $args{status} = $ERROR_STATUS;
352 }
353 elsif ( my $cmd_ref = $self->find_command( $cmd[0] ) ) {
354 45 my $cmd = shift @{$args{unprocessed}};
355 45 %args = $cmd_ref->execute_command(
356 %args,
357 processed => [ { element => $cmd_ref, value => $cmd } ],
358 );
359 }
360 else {
361 1 $args{error} = $self->error;
362 1 $args{status} = $ERROR_STATUS;
363 }
364  
365 44 return $self->try_callback(%args);
366 }
367  
368  
369 7 1;
370  
371 __END__
372  
373 =pod
374  
375 =head1 NAME
376  
377 Term::CLI::Role::CommandSet - Role for (sub-)commands in Term::CLI
378  
379 =head1 VERSION
380  
381 version 0.061000
382  
383 =head1 SYNOPSIS
384  
385 package Term::CLI::Command {
386  
387 use Moo;
388  
389 with('Term::CLI::Role::CommandSet');
390  
391 ...
392 };
393  
394 my $cmd = Term::CLI::Command->new( ... );
395  
396 $cmd->callback->( %args ) if $cmd->has_callback;
397  
398 if ( $cmd->has_commands ) {
399 my $cmd_ref = $cmd->find_command( $cmd_name );
400 die $cmd->error unless $cmd_ref;
401 }
402  
403 say "command names:", join(', ', $cmd->command_names);
404  
405 $cmd->callback->( $cmd, %args ) if $cmd->has_callback;
406  
407 %args = $cmd->try_callback( %args );
408  
409 =head1 DESCRIPTION
410  
411 Role for L<Term::CLI>(3p) elements that contain
412 a set of L<Term::CLI::Command>(3p) objects.
413  
414 This role is used by L<Term::CLI>(3p) and L<Term::CLI::Command>(3p).
415  
416 =head1 ATTRIBUTES
417  
418 This role defines two additional attributes:
419  
420 =over
421  
422 =item B<commands> =E<gt> { I<ArrayRef> | I<CodeRef> }
423  
424 Either an C<ArrayRef> containing C<Term::CLI::Command>
425 object instances that describe the sub-commands that the command takes,
426 a C<CodeRef> that returns such an C<ArrayRef>, or C<undef>.
427  
428 Note that the elements of the array are copied over to an internal
429 array, so modifications to the C<ArrayRef> will not be seen.
430  
431 In case a C<CodeRef> is specified, the C<CodeRef> will be called only
432 once, i.e. when the list of commands needs to be expanded. This allows
433 for delayed object creation, which can be useful in deeper levels of the
434 command hierarchy to reduce startup time.
435  
436 See also the L<commands|/commands> accessor below.
437  
438 =item B<callback> =E<gt> I<CodeRef>
439  
440 Reference to a subroutine that should be called when the command
441 is executed, or C<undef>.
442  
443 =item B<require_sub_command> =E<gt> I<Bool>
444  
445 Default is 1 (true).
446  
447 If the list of C<commands> is not empty, it is normally required that the input
448 contains one of these sub-commands after the "parent" command word. However, it
449 may be desirable to allow the parent command to appear "naked", i.e. without a
450 sub-command.
451  
452 For such cases, set the C<require_sub_command> to a false value.
453  
454 See also L<Term::CLI::Role::CommandSet|Term::CLI::Role::CommandSet/ATTRIBUTES>.
455  
456 =back
457  
458 =head1 ACCESSORS AND PREDICATES
459  
460 =over
461  
462 =item B<commands>
463 X<commands>
464  
465 Returns an C<ArrayRef> containing C<Term::CLI::Command>
466 object instances that describe the sub-commands that the command takes,
467 or C<undef>.
468  
469 Note that, although a C<CodeRef> can be specified in the constructor, the
470 actual I<accessor> will never return the C<CodeRef>. Rather, it
471 will call the C<CodeRef> once and store the result in an C<ArrayRef>.
472  
473 =item B<has_callback>
474 X<has_callback>
475  
476 =item B<has_commands>
477 X<has_commands>
478  
479 Predicate functions that return whether or not any (sub-)commands
480 have been added to this object.
481  
482 =item B<callback> ( [ I<CODEREF> ] )
483 X<callback>
484  
485 I<CODEREF> to be called when the command is executed. The callback
486 is called as:
487  
488 OBJ->callback->(OBJ,
489 status => Int,
490 error => Str,
491 options => HashRef,
492 arguments => ArrayRef[Value],
493 command_line => Str,
494 command_path => ArrayRef[InstanceOf['Term::CLI::Command']],
495 );
496  
497 Where:
498  
499 =over
500  
501 =item I<CLI_REF>
502  
503 Reference to the current C<Term::CLI> object.
504  
505 =item C<status>
506  
507 Indicates the status of parsing/execution so far.
508 It has the following meanings:
509  
510 =over
511  
512 =item I<E<lt> 0>
513  
514 Negative status values indicate a parse error. This is a sign that no
515 action should be taken, but some error handling should be performed.
516 The actual parse error can be found under the C<error> key. A typical
517 thing to do in this case is for one of the callbacks in the chain (e.g.
518 the one on the C<Term::CLI> object) to print the error to F<STDERR>.
519  
520 =item I<0>
521  
522 The command line parses as valid and execution so far has been successful.
523  
524 =item I<E<gt> 0>
525  
526 Some error occurred in the execution of the action. Callback functions need
527 to set this by themselves.
528  
529 =back
530  
531 =item C<error>
532  
533 In case of a negative C<status>, this will contain the parse error. In
534 all other cases, it may or may not contain useful information.
535  
536 =item C<options>
537  
538 Reference to a hash containing all command line options.
539 Compatible with the options hash as set by L<Getopt::Long>(3p).
540  
541 =item C<arguments>
542  
543 Reference to an array containing all the arguments to the command.
544 Each value is a scalar value, possibly converted by
545 its corresponding L<Term::CLI::Argument>'s
546 L<validate|Term::CLI::Argument/validate> method (e.g. C<3e-1> may have
547 been converted to C<0.3>).
548  
549 =item C<unparsed> (DEPRECATED)
550  
551 =item C<unprocessed>
552  
553 Reference to an array containing all the words on the command line that
554 have not been parsed as arguments or sub-commands yet. In case of parse
555 errors, this often contains elements, and otherwise should be empty.
556  
557 =item C<command_line>
558  
559 The complete command line as given to the
560 L<Term::CLI::execute|Term::CLI/execute> method.
561  
562 =item C<command_path>
563  
564 Reference to an array containing the "parse tree", i.e. a list
565 of object references that represent the commands and sub-commands
566 that led up to this point:
567  
568 [
569 InstanceOf['Term::CLI'],
570 InstanceOf['Term::CLI::Command'],
571 ...
572 ]
573  
574 The first item in the C<command_path> list is always the top-level
575 L<Term::CLI> object.
576  
577 The I<OBJ_REF> will be somewhere in that list; it will be the last
578 one if it is the "leaf" command.
579  
580 =item C<processed>
581  
582 More elaborate "parse tree": a list of hashes that represent all the
583 elements on the command line that led up to this point, minus the
584 L<Term::CLI> object itself.
585  
586 [
587 {
588 element => InstanceOf['Term::CLI::Command'],
589 value => String
590 },
591 {
592 element => InstanceOf['Term::CLI::Argument'],
593 value => String
594 },
595 {
596 element => InstanceOf['Term::CLI::Argument'],
597 value => String
598 },
599 ...
600 ]
601  
602 =back
603  
604 The callback is expected to return a hash (list) containing at least the
605 same keys. The C<command_path>, C<arguments>, and C<options> should
606 be considered read-only.
607  
608 Note that a callback can be called even in the case of errors, so you
609 should always check the C<status> before doing anything.
610  
611 =item B<commands>
612 X<commands>
613  
614 Return the list of subordinate C<Term::CLI::Command> objects
615 (i.e. "sub-commands") sorted on C<name>.
616  
617 =back
618  
619 =head1 METHODS
620  
621 =over
622  
623 =item B<add_command> ( I<CMD_REF>, ... )
624 X<add_command>
625  
626 Add the given I<CMD_REF> command(s) to the list of (sub-)commands, setting
627 each I<CMD_REF>'s L<parent|/parent> in the process.
628  
629 =item B<command_names>
630 X<command_names>
631  
632 Return the list of (sub-)command names, sorted alphabetically.
633  
634 =item B<complete_line> ( I<TEXT>, I<LINE>, I<START> )
635 X<complete_line>
636  
637 Called when the user hits the I<TAB> key for completion.
638  
639 I<TEXT> is the text to complete, I<LINE> is the input line so
640 far, I<START> is the position in the line where I<TEXT> starts.
641  
642 The function will split the line in words and delegate the
643 completion to the first L<Term::CLI::Command> sub-command,
644 see L<Term::CLI::Command|Term::CLI::Command/complete>.
645  
646 =item B<delete_command> ( I<CMD>, ... )
647 X<delete_command>
648  
649 Remove the given I<CMD> command(s) from the list of (sub-)commands,
650 setting each object's L<parent|/parent> attribute to C<undef>.
651  
652 I<CMD> can be a string denoting a command name, or a
653 L<Term::CLI::Command|Term::CLI::Command> object reference; if it
654 is a reference, its C<name> will be used to locate the appropriate
655 (sub-)command.
656  
657 Return the list of objects that were removed.
658  
659 =item B<execute> ( I<Str> ) B<### DEPRECATED>
660 X<execute>
661  
662 =item B<execute_line> ( I<Str> )
663 X<execute_line>
664  
665 Parse and execute the command line consisting of I<Str>
666 (see the return value of L<readline|/readline> above).
667  
668 The command line is split into words using
669 the L<Term::CLI's split_function|Term::CLI/split_function>.
670 If that succeeds, then the resulting list of words is
671 parsed and executed, otherwise a parse error is generated
672 (i.e. the object's L<callback|Term::CLI::Role::CommandSet/callback>
673 function is called with a C<status> of C<-1> and a suitable C<error>
674 field).
675  
676 For specifying a custom word splitting method, see
677 L<Term::CLI's split_function|Term::CLI/split_function>.
678  
679 Example:
680  
681 while (my $line = $cli->readline(skip => qr/^\s*(?:#.*)?$/)) {
682 $cli->execute_line($line);
683 }
684  
685 The command line is parsed depth-first, and for every
686 L<Term::CLI::Command>(3p) encountered, that object's
687 L<callback|Term::CLI::Role::CommandSet/callback> function
688 is executed (see
689 L<callback in Term::CLI::Role::Command|Term::CLI::Role::CommandSet/callback>).
690  
691 The C<execute_line> function returns the results of the last called callback
692 function.
693  
694 =over
695  
696 =item *
697  
698 Suppose that the C<file> command has a C<show> sub-command that takes
699 an optional C<--verbose> option and a single file argument.
700  
701 =item *
702  
703 Suppose the input is:
704  
705 file show --verbose foo.txt
706  
707 =item *
708  
709 Then the parse tree looks like this:
710  
711 (cli-root)
712 |
713 +--> Command 'file'
714 |
715 +--> Command 'show'
716 |
717 +--> Option '--verbose'
718 |
719 +--> Argument 'foo.txt'
720  
721 =item *
722  
723 Then the callbacks will be called in the following order:
724  
725 =over
726  
727 =item 1.
728  
729 Callback for 'show'
730  
731 =item 2.
732  
733 Callback for 'file'
734  
735 =item 3.
736  
737 Callback for C<Term::CLI> object.
738  
739 =back
740  
741 =back
742  
743 The return value from each L<callback|Term::CLI::Role::CommandSet/callback>
744 (a hash in list form) is fed into the next callback function in the
745 chain. This allows for adding custom data to the return hash that will
746 be fed back up the parse tree (and eventually to the caller).
747  
748 =item B<find_matches> ( I<Str> )
749 X<find_matches>
750  
751 Return a list of all commands in this object that match the I<Str>
752 prefix.
753  
754 =item B<find_command> ( I<Str> )
755 X<find_command>
756  
757 Check whether I<Str> uniquely matches a command in this C<Term::CLI>
758 object. Returns a reference to the appropriate
759 L<Term::CLI::Command|Term::CLI::Command> object if successful; otherwise,
760 it sets the object's C<error> field and returns C<undef>.
761  
762 Example:
763  
764 my $sub_cmd = $cmd->find_command($prefix);
765 die $cmd->error unless $sub_cmd;
766  
767 =item B<readline> ( [ I<ATTR> =E<gt> I<VAL>, ... ] )
768 X<readline>
769  
770 Read a line from the input connected to L<term|/term>, using
771 the L<Term::ReadLine> interface.
772  
773 By default, it returns the line read from the input, or
774 an empty value if end of file has been reached (e.g.
775 the user hitting I<Ctrl-D>).
776  
777 The following I<ATTR> are recognised:
778  
779 =over
780  
781 =item B<skip> =E<gt> I<RegEx>
782  
783 Override the object's L<skip|/skip> attribute.
784  
785 Skip lines that match the I<RegEx> parameter. A common
786 call is:
787  
788 $text = CLI->readline( skip => qr{^\s+(?:#.*)$} );
789  
790 This will skip empty lines, lines containing whitespace, and
791 comments.
792  
793 =item B<prompt> =E<gt> I<Str>
794  
795 Override the prompt given by the L<prompt|/prompt> method.
796  
797 =back
798  
799 Examples:
800  
801 # Just read the next input line.
802 $line = $cli->readline;
803 exit if !defined $line;
804  
805 # Skip empty lines and comments.
806 $line = $cli->readline( skip => qr{^\s*(?:#.*)?$} );
807 exit if !defined $line;
808  
809 =item B<try_callback> ( I<ARGS> )
810 X<try_callback>
811  
812 Wrapper function that will call the object's C<callback> function if it
813 has been set, otherwise simply returns its arguments.
814  
815 =back
816  
817 =head1 SEE ALSO
818  
819 L<Term::CLI>(3p),
820 L<Term::CLI::Command>(3p).
821  
822 =head1 AUTHOR
823  
824 Steven Bakker E<lt>sbakker@cpan.orgE<gt>, 2018.
825  
826 =head1 COPYRIGHT AND LICENSE
827  
828 Copyright (c) 2018 Steven Bakker
829  
830 This module is free software; you can redistribute it and/or modify
831 it under the same terms as Perl itself. See "perldoc perlartistic."
832  
833 This software is distributed in the hope that it will be useful,
834 but WITHOUT ANY WARRANTY; without even the implied warranty of
835 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
836  
837 =begin __PODCOVERAGE
838  
839 =head1 THIS SECTION SHOULD BE HIDDEN
840  
841 This section is meant for methods that should not be considered
842 for coverage. This typically includes things like BUILD and DEMOLISH from
843 Moo/Moose. It is possible to skip these when using the Pod::Coverage class
844 (using C<also_private>), but this is not an option when running C<cover>
845 from the command line.
846  
847 The simplest trick is to add a hidden section with an item list containing
848 these methods.
849  
850 =over
851  
852 =item parent
853  
854 =item BUILD
855  
856 =item DEMOLISH
857  
858 =back
859  
860 =end __PODCOVERAGE
861  
862 =cut
« CLI/L10N/nl.pm ↑ Summary CLI/Argument/Tree.pm »