CLI.pm

filter: Statementstmt 82.9% 151 / 182 Branchbran 69.5% 32 / 46 Conditioncond 63.1% 12 / 19 MC/DCmcdc 33.3% 4 / 12 Subroutinesub 95.0% 38 / 40 Podpod 100% 7 / 7 totaltotal 79.7% 244 / 306 CC 31 SCAR 22.0
CC
31
Cov
79%
write_pager
59.8
BUILD
6.1
_default_split
5.0
CRAP 9.1
« CLI/Argument/Filename.pm ↑ Summary CLI/Argument/Number.pm »
1 #=============================================================================
2 #
3 # Module: Term::CLI
4 #
5 # Description: Class for CLI parsing
6 #
7 # Author: Steven Bakker (SBAKKER), <sbakker@cpan.org>
8 # Created: 31/01/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 0.061000;
22  
23 6 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 6 ▶use Text::ParseWords 3.27 qw( parse_line );
Subroutine BEGIN: called CC=1 SCAR=0.0
27 6 ▶use Term::CLI::ReadLine;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 6 ▶use FindBin 1.50;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 6 ▶use File::Which 1.09;
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 6 ▶use Term::CLI::L10N qw( loc );
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 6 ▶use List::Util qw( first );
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 # Load all Term::CLI classes so the user doesn't have to.
36  
37 6 ▶use Term::CLI::Argument::Bool;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 6 ▶use Term::CLI::Argument::Enum;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 6 ▶use Term::CLI::Argument::Filename;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 6 ▶use Term::CLI::Argument::Number;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 6 ▶use Term::CLI::Argument::Number::Float;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 6 ▶use Term::CLI::Argument::Number::Int;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 6 ▶use Term::CLI::Argument::String;
Subroutine BEGIN: called CC=1 SCAR=0.0
44  
45 6 ▶use Term::CLI::Command;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 6 ▶use Term::CLI::Command::Help;
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 6 use Types::Standard 1.000005 qw(
49 ArrayRef
50 CodeRef
51 InstanceOf
52 Maybe
53 RegexpRef
54 Str
55 Int
56 6 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
57  
58 6 my @PAGERS = (
59 [ qw(
60 less --no-lessopen --no-init
61 --dumb --quit-at-eof
62 --quit-if-one-screen
63 --RAW-CONTROL-CHARS
64 )
65 ],
66 ['more'],
67 ['pg'],
68 );
69  
70 6 ▶use Moo 1.000001;
Subroutine BEGIN: called CC=1 SCAR=0.0
71 6 ▶use namespace::clean 0.25;
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 6 extends 'Term::CLI::Base';
74  
75 6 with qw(
76 Term::CLI::Role::CommandSet
77 Term::CLI::Role::State
78 );
79  
80 6 my $DFL_HIST_SIZE = 1000;
81  
82 # Provide a default for 'name'.
83 6 ▶has '+name' => ( default => sub {$FindBin::Script} );
Subroutine __ANON__: called CC=1 SCAR=0.0
84  
85 has 'pager' => (
86 is => 'rw',
87 isa => ArrayRef [Str],
88 default => sub {
89 11 ▶ first { defined which( $_->[0] ) } @PAGERS;
Subroutine __ANON__: called CC=1 SCAR=0.0
90 },
91 6 );
92  
93 6 has cleanup => (
94 is => 'rw',
95 isa => Maybe [CodeRef],
96 predicate => 1
97 );
98  
99 has prompt => (
100 is => 'rw',
101 isa => Str,
102 4 ▶ default => sub {'~> '}
Subroutine __ANON__: called CC=1 SCAR=0.0
103 6 );
104  
105 has split_function => (
106 is => 'rw',
107 isa => CodeRef,
108 7 ▶ default => sub { \&_default_split }
Subroutine __ANON__: called CC=1 SCAR=0.0
109 6 );
110  
111 6 has skip => (
112 is => 'rw',
113 isa => RegexpRef,
114 );
115  
116 6 has history_file => (
117 is => 'rw',
118 isa => Str
119 );
120  
121 has history_lines => (
122 is => 'rw',
123 isa => Int,
124 6 ▶ default => sub {$DFL_HIST_SIZE},
Subroutine __ANON__: called CC=1 SCAR=0.0
125 6 trigger => 1,
126 );
127  
128 7 ▶has word_delimiters => ( is => 'rw', isa => Str, default => sub {" \n\t"} );
Subroutine __ANON__: called CC=1 SCAR=0.0
129 7 ▶has quote_characters => ( is => 'rw', isa => Str, default => sub {q("')} );
Subroutine __ANON__: called CC=1 SCAR=0.0
130  
131 sub BUILD {
132 7 ▶ my ( $self, $args ) = @_;
Subroutine BUILD: called CC=6 SCAR=18.1
Pod documented
133  
134 7 my @fh_list = ( \*STDIN, \*STDOUT );
135 7 ▶ if (exists $args->{filehandles}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{"filehandles"}) 2 5 7
136 2 ▶ @fh_list = @{ $args->{filehandles} // [] };
Condition50%1/2
$args->{"filehandles"} // []
l!l
20
MC/DC0%0/1
$args->{"filehandles"} // []
$args->{"filehandles"}
Truth table50%1/2
A
A= $args->{"filehandles"}
Aresult
11
00
137 }
138  
139 7 my $term = Term::CLI::ReadLine->new( $self->name, @fh_list );
140  
141 7 ▶ if ( my $sig_list = $args->{ignore_keyboard_signals} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sig_list = $args->{"ignore_keyboard_signals"}) 0 7 7
142 0 $term->ignore_keyboard_signals( @{$sig_list} );
143 }
144  
145 7 ▶ $term->Attribs->{char_is_quoted_p} = sub { $self->_is_escaped(@_) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
146  
147 7 $self->_set_completion_attribs;
148  
149 7 ▶ if ( !exists $args->{callback} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $args->{"callback"}) 5 2 7
150 5 $self->callback( \&_default_callback );
151 }
152  
153 7 ▶ if ( !exists $args->{history_file} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $args->{"history_file"}) 6 1 7
154 6 my $hist_file = $self->name;
155 6 $hist_file =~ s{^/}{}gx;
156 6 $hist_file =~ s{/$}{}gx;
157 6 $hist_file =~ s{/+}{-}gx;
158 6 $self->history_file("$::ENV{HOME}/.${hist_file}_history");
159 }
160  
161 # Ensure that the history_lines trigger is called.
162 # If history_lines is given as a parameter, the trigger
163 # *is* called, but it happens *before* the `$term` is
164 # initialised; and if no history_lines is given, the
165 # trigger is not called for the default.
166 7 $self->history_lines( $self->history_lines );
167 7 return;
168 }
169  
170 sub DEMOLISH {
171 7 ▶ my ($self) = @_;
Subroutine DEMOLISH: called CC=2 SCAR=7.6
Pod documented
172 7 ▶ if ( $self->has_cleanup ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_cleanup) 0 7 7
173 0 $self->cleanup->($self);
174 }
175 7 return;
176 }
177  
178 sub _trigger_history_lines { ## no critic (ProhibitUnusedPrivateSubroutines)
179 9 ▶ my ( $self, $arg ) = @_;
Subroutine _trigger_history_lines: called CC=2 SCAR=6.9
180  
181 # Terminal may not be initialiased yet...
182 9 ▶ return if !$self->term;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->term 1 8 9
183  
184 8 $self->term->StifleHistory($arg);
185 8 return;
186 }
187  
188 # %args = $self->_default_callback(%args);
189 #
190 # Default top-level callback if none is given.
191 # Simply check the status and print an error
192 # message if status < 0.
193 sub _default_callback {
194 2 ▶ my ( $self, %args ) = @_;
Subroutine _default_callback: called CC=2 SCAR=6.9
195  
196 2 ▶ if ( $args{status} < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"status"} < 0) 1 1 2
197 1 say STDERR loc("ERROR"), ": ", $args{error};
198 }
199 2 return %args;
200 }
201  
202 # ($error, @words) = $self->_default_split($text);
203 #
204 # Default function to split a string into words.
205 # Similar to "shellwords()", except that we use
206 # "parse_line" to support custom delimiters.
207 #
208 # Unfortunately, there's no way to specify custom
209 # quote characters.
210 #
211 sub _default_split {
212 86 ▶ my ( $self, $text ) = @_;
Subroutine _default_split: called CC=5 SCAR=16.1
213  
214 86 my $delim = $self->word_delimiters;
215  
216 86 $text =~ s/^ [$delim]+ //gxsm; # Strip leading delimiters.
217  
218 86 ▶ return (q{}) if length $text == 0; # Blank line.
Branch: 1 branch
BranchTrueFalseTotal
if length $text == 0 2 84 86
219  
220 84 my @words = parse_line( qr{ [$delim]+ }xms, 0, $text );
221  
222 84 ▶ return ( loc('unbalanced quotes in input') ) if !@words;
Branch: 1 branch
BranchTrueFalseTotal
unless @words 2 82 84
223  
224 # If the text ends in one or more delimiters, the last word will be
225 # "undef", but it's not an errror, so just eliminate it.
226 82 ▶ if ( @words > 0 && !defined $words[-1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@words > 0 and not defined $words[-1]) 30 52 82
Condition66%2/3
@words > 0 and not defined $words[-1]
!ll&&!rl&&r
05230
MC/DC50%1/2
@words > 0 and not defined $words[-1]
@words > 0 not defined $words[-1]
Truth table66%2/3
A and not(B)
A= @words > 0B= not defined $words[-1]
ABresult
0X0
100
111
227 30 pop @words;
228 }
229 82 return ( q{}, @words );
230 }
231  
232 sub unescape_input {
233 43 ▶ my ($self, $text, $quote_char) = @_;
Subroutine unescape_input: called CC=3 SCAR=11.0
Pod documented
234  
235 43 ▶ if ( !$quote_char || $quote_char ne q{'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $quote_char or $quote_char ne "'") 41 2 43
Condition100%3/3
not $quote_char or $quote_char ne "'"
l!l&&r!l&&!r
3832
MC/DC100%2/2
not $quote_char or $quote_char ne "'"
not $quote_char $quote_char ne "'"
Truth table100%3/3
not(A) or B
A= not $quote_charB= $quote_char ne "'"
ABresult
1X1
011
000
236 41 return $text =~ s{ \\ (.) }{$1}xgr;
237 }
238 2 return $text;
239 }
240  
241 sub escape_input {
242 68 ▶ my ($self, $text, $quote_char) = @_;
Subroutine escape_input: called CC=3 SCAR=11.0
Pod documented
243  
244 68 ▶ if ( !$quote_char ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($quote_char) 62 6 68
245 62 my $delim = $self->root_node->word_delimiters;
246 62 return $text =~ s{ ([$delim\'\"\\]) }{\\$1}xgr;
247 }
248 6 ▶ if ( $quote_char ne q{'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($quote_char ne "'") 4 2 6
249 4 return $text =~ s{ ([$quote_char\\]) }{\\$1}xgr;
250 }
251 2 return $text;
252 }
253  
254 # BOOL = CLI->_is_escaped($line, $index);
255 #
256 # The character at $index in $line is a possible word break
257 # character. Check if it is perhaps escaped.
258 #
259 sub _is_escaped {
260 12 ▶ my ( $self, $line, $index ) = @_;
Subroutine _is_escaped: called CC=4 SCAR=13.9
261 12 ▶ return 0 if not defined $index or $index <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $index or $index <= 0 3 9 12
Condition66%2/3
not defined $index or $index <= 0
l!l&&r!l&&!r
039
MC/DC50%1/2
not defined $index or $index <= 0
not defined $index $index <= 0
Truth table66%2/3
not(A) or B
A= not defined $indexB= $index <= 0
ABresult
1X1
011
000
262 9 ▶ return 0 if substr( $line, $index - 1, 1 ) ne q{\\};
Branch: 1 branch
BranchTrueFalseTotal
if substr($line, $index - 1, 1) ne "\\" 3 6 9
263 6 return !$self->_is_escaped( $line, $index - 1 );
264 }
265  
266 sub read_history {
267 2 ▶ my ( $self, $hist_file ) = @_;
Subroutine read_history: called CC=3 SCAR=11.0
Pod documented
268  
269 2 ▶ $hist_file //= $self->history_file;
Condition66%2/3
$hist_file //= $self->history_file
l!l&&r!l&&!r
110
MC/DC0%0/2
$hist_file //= $self->history_file
$hist_file $self->history_file
Truth table66%2/3
A //= B
A= $hist_fileB= $self->history_file
ABresult
1X1
011
000
270  
271 2 ▶ $self->term->ReadHistory($hist_file)
Branch: 1 branch
BranchTrueFalseTotal
$self->term->ReadHistory($hist_file) or return $self->set_error("${hist_file}: $!") 1 1 2
272 or return $self->set_error("$hist_file: $!");
273 1 $self->history_file($hist_file);
274 1 $self->clear_error;
275 1 return 1;
276 }
277  
278 sub write_history {
279 2 ▶ my ( $self, $hist_file ) = @_;
Subroutine write_history: called CC=3 SCAR=11.0
Pod documented
280  
281 2 ▶ $hist_file //= $self->history_file;
Condition66%2/3
$hist_file //= $self->history_file
l!l&&r!l&&!r
110
MC/DC0%0/2
$hist_file //= $self->history_file
$hist_file $self->history_file
Truth table66%2/3
A //= B
A= $hist_fileB= $self->history_file
ABresult
1X1
011
000
282  
283 2 ▶ $self->term->WriteHistory($hist_file)
Branch: 1 branch
BranchTrueFalseTotal
$self->term->WriteHistory($hist_file) or return $self->set_error("${hist_file}: $!") 1 1 2
284 or return $self->set_error("$hist_file: $!");
285 1 $self->history_file($hist_file);
286 1 $self->clear_error;
287 1 return 1;
288 }
289  
290 sub write_pager {
291 0 ▶ my ($self, %args) = @_;
Subroutine write_pager: not called CC=8 SCAR=40.9
Pod documented
292  
293 0 ▶ my $pager_cmd = $self->pager // [];
Condition0%0/2
$self->pager // []
l!l
00
MC/DC0%0/1
$self->pager // []
$self->pager
Truth table0%0/2
A
A= $self->pager
Aresult
11
00
294  
295 my $text =
296 ref $args{text} eq 'ARRAY'
297 0 ? join( q{}, @{ $args{text} } )
298 0 ▶ : $args{text};
Branch: 1 branch
BranchTrueFalseTotal
ref $args{'text'} eq 'ARRAY' ? : 0 0 0
299  
300 0 ▶ if (@$pager_cmd) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$pager_cmd) 0 0 0
301 6 ▶ no warnings 'exec'; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
302 0 local ( $SIG{PIPE} ) = 'IGNORE'; # Temporarily avoid accidents.
303  
304 0 my $pager_fh;
305 0 ▶ if (! open $pager_fh, '|-', @{$pager_cmd}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $pager_fh, "|-", @{$pager_cmd;}) 0 0 0
306 0 $args{status} = -1;
307 $args{error} =
308 0 loc( "cannot run '[_1]': [_2]", $$pager_cmd[0], $! );
309 0 return %args;
310 }
311  
312 0 print $pager_fh $text;
313 0 $pager_fh->close;
314  
315 0 $args{status} = $?;
316 0 ▶ $args{error} = $! if $args{status} != 0;
Branch: 1 branch
BranchTrueFalseTotal
if $args{"status"} != 0 0 0 0
317 0 return %args;
318 }
319  
320 0 my $pager_fh;
321 0 ▶ if (! open $pager_fh, '>&', \*STDOUT) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $pager_fh, ">&", \*STDOUT) 0 0 0
322 0 $args{status} = -1;
323 0 $args{error} = "cannot dup STDOUT: $!";
324 0 return %args;
325 }
326 0 print $pager_fh $text;
327 0 ▶ if ( !$pager_fh->close ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pager_fh->close) 0 0 0
328 0 $args{status} = -1;
329 0 $args{error} = $!;
330 }
331 0 return %args;
332 }
333  
334 6 1;
335  
336 __END__
337  
338 =pod
339  
340 =head1 NAME
341  
342 Term::CLI - CLI interpreter based on Term::ReadLine
343  
344 =head1 VERSION
345  
346 version 0.061000
347  
348 =head1 SYNOPSIS
349  
350 use Term::CLI;
351 use Term::CLI::Command;
352 use Term::CLI::Argument::Filename;
353 use Data::Dumper;
354  
355 my $cli = Term::CLI->new(
356 name => 'myapp',
357 prompt => 'myapp> ',
358 cleanup => sub {
359 my ($cli) = @_;
360 $cli->write_history;
361 or warn "cannot write history: ".$cli->error."\n";
362 },
363 callback => sub {
364 my ($self, %args) = @_;
365 print Data::Dumper->Dump([\%args], ['args']);
366 return %args;
367 },
368 commands => [
369 Term::CLI::Command->new(
370 name => 'copy',
371 options => [ 'verbose!' ],
372 arguments => [
373 Term::CLI::Argument::Filename->new(name => 'src'),
374 Term::CLI::Argument::Filename->new(name => 'dst'),
375 ],
376 callback => sub {
377 my ($self, %args) = @_;
378 print Data::Dumper->Dump([\%args], ['args']);
379 return (%args, status => 0);
380 }
381 )
382 ],
383 );
384  
385 $cli->read_history; # Read history from ~/.myapp_history
386 $cli->write_history; # Write history to ~/.myapp_history
387  
388 $cli->word_delimiters(';,');
389 # $cli will now recognise things like: 'copy;--verbose;a,b'
390  
391 $cli->word_delimiters(" \t\n");
392 # $cli will now recognise things like: 'copy --verbose a b'
393  
394 while ( my $input = $cli->readline(skip => qr/^\s*(?:#.*)?$/) ) {
395 $cli->execute_line($input);
396 }
397  
398 =head1 DESCRIPTION
399  
400 Implement an easy-to-use command line interpreter based on
401 L<Term::ReadLine>(3p). Although primarily aimed at use with
402 the L<Term::ReadLine::Gnu>(3p) implementation, it also supports
403 L<Term::ReadLine::Perl>(3p).
404  
405 First-time users may want to read L<Term::CLI::Tutorial>(3p)
406 and L<Term::CLI::Intro>(3p) first, and peruse the example
407 scripts in the source distribution's F<examples> and
408 F<tutorial> directories.
409  
410 =head2 I/O handles
411  
412 By default B<Term::CLI> will create a
413 L<Term::CLI::ReadLine|Term::CLI::ReadLine> object
414 (which creates a L<Term::ReadLine|Term::ReadLine> object)
415 that reads from F<STDIN> and writes to F<STDOUT>.
416  
417 This is notably different from the default behaviour of e.g.
418 GNU Readline which opens the TTY separately. This may cause
419 unexpected behaviour in case of UTF-8 I/O.
420  
421 By explicitly specifying F<STDIN> and F<STDOUT> as the I/O
422 handles, we force the underlying readline implementation to
423 use the same I/O encoding as the standard I/O handles. This
424 means that e.g. C<use open qw(:std :utf8)> will do what you
425 expect and enable UTF-8 input/output.
426  
427 See the C<filehandles> argument to L<new|/new> below for information
428 on how to change this.
429  
430 =head1 CLASS STRUCTURE
431  
432 =head2 Inherits from:
433  
434 L<Term::CLI::Base>(3p).
435  
436 =head2 Consumes:
437  
438 L<Term::CLI::Role::CommandSet|Term::CLI::Role::CommandSet>(3p),
439 L<Term::CLI::Role::State|Term::CLI::Role::State>(3p).
440  
441 =head1 CONSTRUCTORS
442  
443 =over
444  
445 =item B<new> ( B<attr> => I<VAL> ... )
446 X<new>
447  
448 Create a new B<Term::CLI> object and return a reference to it.
449  
450 Valid attributes:
451  
452 =over
453  
454 =item B<callback> =E<gt> I<CodeRef>
455  
456 Reference to a subroutine that should be called when the command
457 is executed, or C<undef>.
458  
459 =item B<filehandles> =E<gt> I<ArrayRef>
460  
461 File handles to use for input and output, resp. The array can be:
462  
463 undef
464 [ ]
465 [ IN_FH, OUT_FH ]
466  
467 If the value is either C<undef> or an empty list, then we rely
468 on the underlying readline's implementation to determine the
469 I/O handles (but see L<IE<sol>O handles|/I/O handles> above).
470  
471 =item B<cleanup> =E<gt> I<CodeRef>
472  
473 Reference to a subroutine that should be called when the object
474 is destroyed (i.e. in L<Moo> terminology, when C<DEMOLISH> is called).
475  
476 =item B<commands> =E<gt> I<ArrayRef>
477  
478 Reference to an array containing L<Term::CLI::Command> object
479 instances that describe the commands that B<Term::CLI> recognises,
480 or C<undef>.
481  
482 =item B<ignore_keyboard_signals> =E<gt> I<ArrayRef>
483  
484 Specify a list of signals for which the keyboard generation should be
485 turned off during a C<readline> operation.
486  
487 The list of signals should be a combination of C<INT>, C<QUIT>, or
488 C<TSTP>. See also
489 L<ignore_keyboard_signals|Term::CLI::ReadLine/ignore_keyboard_signals>
490 in L<Term::CLI::ReadLine>(3p). If this is not specified, C<QUIT>
491 keyboard generation is turned off by default.
492  
493 =item B<name> =E<gt> I<Str>
494  
495 The application name. This is used for e.g. the history file
496 and default command prompt.
497  
498 If not given, defaults to C<$FindBin::Script> (see L<FindBin>(3p)).
499  
500 =item B<pager> =E<gt> I<ArrayRef>[I<Str>]
501  
502 The C<pager> attribute is used by L<write_pager()|/write_pager>.
503  
504 The value should be a command line split on words, e.g.:
505  
506 OBJ->pager( [ 'cat', '-n', '-e' ] );
507  
508 If an empty list is provided, no external pager will
509 be used, and output is printed to F<STDOUT> directly.
510  
511 See also the L<pager|/pager> method.
512  
513 =item B<prompt> =E<gt> I<Str>
514  
515 Prompt to display when L<readline|/readline> is called. Defaults
516 to the application name with C<E<gt>> and a space appended.
517  
518 =item B<skip> =E<gt> I<RegEx>
519  
520 Set the object's L<skip|/skip> attribute, telling the
521 L<readline|/readline> method to ignore input lines
522 that match the given I<RegEx>.
523 A common call value is C<qr{^\s+(?:#.*)$}> to skip
524 empty lines, lines with only whitespace, and comments.
525  
526 =item B<history_file> =E<gt> I<Str>
527  
528 Specify the file to read/write input history to/from.
529 The default is I<name> + C<_history> in the user's
530 I<HOME> directory.
531  
532 =item B<history_lines> =E<gt> I<Int>
533  
534 Maximum number of lines to keep in the input history.
535 Default is 1000.
536  
537 =back
538  
539 =back
540  
541 =head1 INHERITED METHODS
542  
543 This class inherits all the attributes and accessors of
544 L<Term::CLI::Role::CommandSet>(3p) and L<Term::CLI::Base>(3p),
545 most notably:
546  
547 =head2 Accessors
548  
549 =over
550  
551 =item B<has_callback>
552 X<has_callback>
553  
554 See
555 L<has_callback in Term::CLI::Role::CommandSet|Term::CLI::Role::CommandSet/has_callback>.
556  
557 =item B<callback> ( [ I<CodeRef> ] )
558 X<callback>
559  
560 See
561 L<callback in Term::CLI::Role::CommandSet|Term::CLI::Role::CommandSet/callback>.
562  
563 =item B<has_commands>
564 X<has_commands>
565  
566 See
567 L<has_commands in Term::CLI::Role::CommandSet|Term::CLI::Role::CommandSet/has_commands>.
568  
569 =item B<commands> ( [ I<ArrayRef> ] )
570 X<commands>
571  
572 See
573 L<commands in Term::CLI::Role::CommandSet|Term::CLI::Role::CommandSet/commands>.
574  
575 I<ArrayRef> with B<Term::CLI::Command> object instances.
576  
577 =back
578  
579 =head2 Others
580  
581 =over
582  
583 =item B<has_cleanup>
584 X<has_cleanup>
585  
586 Predicate function that returns whether or not the C<cleanup> attribute has been set.
587  
588 =item B<cleanup> ( [ I<CodeRef> ] )
589  
590 Gets or sets a reference to a subroutine that should be called when the object
591 is destroyed (i.e. in L<Moo> terminology, when C<DEMOLISH> is called).
592  
593 The code is called with one parameter: the object to be destroyed. One typical
594 use of C<cleanup> is to ensure that the history gets saved upon exit:
595  
596 my $cli = Term::CLI->new(
597 ...
598 cleanup => sub {
599 my ($cli) = @_;
600 $cli->write_history
601 or warn "cannot write history: ".$cli->error."\n";
602 }
603 );
604  
605 =item B<find_command> ( I<Str> )
606 X<find_command>
607  
608 See
609 L<find_command in Term::CLI::Role::CommandSet|Term::CLI::Role::CommandSet/find_command>.
610  
611 =item B<find_matches> ( I<Str> )
612 X<find_matches>
613  
614 See
615 L<find_matches in Term::CLI::Role::CommandSet|Term::CLI::Role::CommandSet/find_matches>.
616  
617 =back
618  
619 =head1 METHODS
620  
621 =head2 Accessors
622  
623 =over
624  
625 =item B<name>
626 X<name>
627  
628 The application name.
629 See
630 L<name in Term::CLI::Base|Term::CLI::Base/name>.
631  
632 =item B<pager> ( [ I<ArrayRef>[I<Str>] ] )
633 X<pager>
634  
635 Get or set the pager to use for L<write_pager()|/write_pager>.
636  
637 If an empty list is provided, no external pager will
638 be used, and output is printed to F<STDOUT> directly.
639  
640 Example:
641  
642 $help_cmd->pager([]); # Print directly to STDOUT.
643 $help_cmd->pager([ 'cat', '-n' ]); # Number output lines.
644  
645 =item B<prompt> ( [ I<Str> ] )
646 X<prompt>
647  
648 Get or set the command line prompt to display to the user.
649  
650 =item B<term>
651 X<term>
652  
653 Return a reference to the underlying L<Term::CLI::ReadLine> object.
654 See
655 L<term in Term::CLI::Base|Term::CLI::Base/term>.
656  
657 =item B<quote_characters> ( [ I<Str> ] )
658 X<quote_characters>
659  
660 Get or set the characters that should considered quote characters
661 for the completion and parsing/execution routines.
662  
663 Default is C<'">, that is a single quote or a double quote.
664  
665 It's possible to change this, but this will interfere with the default
666 splitting function, so if you do want custom quote characters, you should
667 also override the L<split_function|/split_function>.
668  
669 =item B<split_function> ( [ I<CodeRef> ] )
670  
671 Get or set the function that is used to split a (partial) command
672 line into words. The default function uses
673 L<Text::ParseWords::parse_line|Text::ParseWords/parse_line>.
674 Note that this implies that it can take into account custom delimiters,
675 but I<not custom quote characters>.
676  
677 The I<CodeRef> is called as:
678  
679 ( ERROR, [ WORD, ... ] ) = CodeRef->( CLI_OBJ, TEXT )
680  
681 The function should return a list of at least one element, an
682 I<ERROR> string. Subsequent elements are the words resulting
683 from the split.
684  
685 I<ERROR> string should be empty (not C<undef>!) if splitting
686 was successful, otherwise it should contain a relevant error
687 message.
688  
689 =item B<word_delimiters> ( [ I<Str> ] )
690  
691 Get or set the characters that are considered word delimiters
692 in the completion and parsing/execution routines.
693  
694 Default is C< \t\n>, that is I<space>, I<tab>, and I<newline>.
695  
696 The first character in the string is also the character that is
697 appended to a completed word at the command line prompt.
698  
699 =back
700  
701  
702 =head2 Input Control
703  
704 The L<split_function|/split_function> has already been described
705 above.
706 However, we also need to deal with escape sequences in
707 (partial) input that may or may not be quoted.
708  
709 For word splitting this is handled by the
710 L<split_function|/split_function>,
711 but for command/argument completion we need to make sure the text
712 passed to the completion functions is the "proper" text.
713  
714 For example:
715  
716 $ ls foo\ b<TAB>
717  
718 The completion mechanism will be asked to complete C<foo\ b>.
719 However, since the string is unquoted, what we really want to complete
720 is C<foo b>. On the other hand, with:
721  
722 $ ls 'foo\ b<TAB>
723  
724 We would want to run completion on the literal C<foo\ b> (because it
725 is single-quoted).
726  
727 For this, we use L<unescape_input>.
728 Then, when completion is done, we run L<escape_input> on the results.
729  
730 =over
731  
732 =item B<escape_input>
733 X<escape_input>
734  
735 =item B<unescape_input>
736 X<unescape_input>
737  
738 $ESCAPED = $CLI->escape_input( $INPUT, $QUOTE_CHAR );
739 $UNESCAPED = $CLI->unescape_input( $INPUT, $QUOTE_CHAR );
740  
741 Add or remove backslash escape sequences in an input string.
742 This is used during command and argument completion.
743 I<$INPUT> is the string to operate on,
744 I<$QUOTE_CHAR> indicates how the input is quoted (if any);
745 if I<$QUOTE_CHAR> is I<undef> or an empty string,
746 then the I<$INPUT> is not surrounded by quotes.
747 Otherwise,
748 I<$QUOTE_CHAR> indicates which quotes are being used
749 (C<"> or C<'>).
750  
751 The B<unescape_input> is called right before word completion:
752  
753 INPUT | CALL | RESULT
754 -----------|----------------------------------------|--------------
755 <foo\ b> | $CLI->unescape_input(q{foo\ b}, undef) | q{foo b}
756 <"foo\ b> | $CLI->unescape_input(q{foo\ b}, q{"}) | q{foo b}
757 <'foo\ b> | $CLI->unescape_input(q{foo\ b}, q{'}) | q{foo\ b}
758  
759 The result is then run through the completion process,
760 after which B<escape_input> is called on the result(s):
761  
762 INPUT | CALL | RESULT
763 -----------|----------------------------------------|--------------
764 <foo\ bar> | $CLI->escape_input(q{foo\ bar}, undef) | q{foo\\\ bar}
765 <foo\ bar> | $CLI->escape_input(q{foo\ bar}, q{"}) | q{foo\\ bar}
766 <foo\ bar> | $CLI->escape_input(q{foo\ bar}, q{'}) | q{foo\ bar}
767  
768 The default functions do the following:
769  
770 | UNESCAPE | ESCAPE
771 --------------|------------------------|-----------------
772 unquoted | anything preceded by \ | \, space, quote
773 double quote | anything preceded by \ | \, double quote
774 single quote | nothing | nothing
775  
776 If you need special treatment,
777 you will have to sub-class B<Term::CLI> and overload these methods.
778  
779 =back
780  
781 =head2 Output Control
782  
783 =over
784  
785 =item B<write_pager>
786 X<write_pager>
787  
788 %status = $CLI->write_pager( text => TEXT, ... );
789  
790 Output the I<TEXT> through the L<pager|/pager> command, or
791 F<STDOUT> if the C<pager> attribute is not set.
792  
793 Returns the arguments it was given with the following fields set if
794 there was an error:
795  
796 =over
797  
798 =item C<status> =E<gt> I<Int>
799  
800 Non-zero value indicates an error.
801  
802 =item C<error> =E<gt> I<Str>
803  
804 Erorr diagnostic.
805  
806 =back
807  
808 =back
809  
810 =head2 History Control
811  
812 =over
813  
814 =item B<history_lines> ( [ I<Int> ] )
815  
816 Get or set the maximum number of lines to keep in the history.
817 Default is 1000.
818  
819 =item B<history_file> ( [ I<Str> ] )
820  
821 Set the default file to read from/write to.
822  
823 =item B<read_history> ( [ I<Str> ] )
824  
825 Try to read input history from the L<history_file()|/history_file>.
826 Returns 1 on success. On failure, it will set the L<error|/error>
827 field and return C<undef>.
828  
829 If I<Str> is given, it will try to read from that file instead. If that is
830 successful, the L<history_file()|/history_file> attribute will be set
831 to I<Str>.
832  
833 =item B<write_history> ( [ I<Str> ] )
834  
835 Try to write the input history to the L<history_file()|/history_file>.
836 Returns 1 on success. On failure, it will set the L<error|/error> field
837 and return C<undef>.
838  
839 If I<Str> is given, it will try to write to that file instead. If that is
840 successful, the L<history_file()|/history_file> attribute will be set
841 to I<Str>.
842  
843 =back
844  
845 =head1 SIGNAL HANDLING
846  
847 The B<Term::CLI> object (through L<Term::CLI::ReadLine>) will make sure that
848 signals are handled "correctly". This especially means that if a signal is
849 not ignored, the terminal is left in a "sane" state before any signal
850 handler is called or the program exits.
851  
852 See also
853 L<SIGNAL HANDLING in Term::CLI::ReadLine|Term::CLI::ReadLine/SIGNAL HANDLING>.
854  
855 =head1 SEE ALSO
856  
857 L<FindBin>(3p),
858 L<Moo>(3p),
859 L<Getopt::Long>(3p),
860 L<Term::CLI::Argument>(3p),
861 L<Term::CLI::Base>(3p),
862 L<Term::CLI::Command>(3p),
863 L<Term::CLI::Intro>(3p),
864 L<Term::CLI::ReadLine>(3p),
865 L<Term::CLI::Role::CommandSet>(3p),
866 L<Term::CLI::Tutorial>(3p),
867 L<Term::ReadLine::Gnu>(3p),
868 L<Term::ReadLine::Perl>(3p),
869 L<Term::ReadLine>(3p),
870 L<Text::ParseWords>(3p),
871 L<Types::Standard>(3p).
872  
873 Inspiration for the custom completion came from:
874 L<https://robots.thoughtbot.com/tab-completion-in-gnu-readline>.
875 This is an excellent tutorial into the completion mechanics
876 of the C<readline> library, and, by extension,
877 L<Term::ReadLine::Gnu>(3p).
878  
879 =head1 AUTHOR
880  
881 Steven Bakker E<lt>sbakker@cpan.orgE<gt>, 2018.
882  
883 =head1 COPYRIGHT AND LICENSE
884  
885 Copyright (c) 2018 Steven Bakker
886  
887 This module is free software; you can redistribute it and/or modify
888 it under the same terms as Perl itself. See "perldoc perlartistic."
889  
890 This software is distributed in the hope that it will be useful,
891 but WITHOUT ANY WARRANTY; without even the implied warranty of
892 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
893  
894 =begin __PODCOVERAGE
895  
896 =head1 THIS SECTION SHOULD BE HIDDEN
897  
898 This section is meant for methods that should not be considered
899 for coverage. This typically includes things like BUILD and DEMOLISH from
900 Moo/Moose. It is possible to skip these when using the Pod::Coverage class
901 (using C<also_private>), but this is not an option when running C<cover>
902 from the command line.
903  
904 The simplest trick is to add a hidden section with an item list containing
905 these methods.
906  
907 =over
908  
909 =item BUILD
910  
911 =item DEMOLISH
912  
913 =back
914  
915 =end __PODCOVERAGE
916  
917 =cut
« CLI/Argument/Filename.pm ↑ Summary CLI/Argument/Number.pm »