blib/lib/CLI/Helpers.pm

filter: Statementstmt 45.0% 150 / 333 Branchbran 34.7% 64 / 184 Conditioncond 26.0% 25 / 96 MC/DCmcdc 6.9% 4 / 58 Subroutinesub 69.2% 27 / 39 Podpod 100% 14 / 14 totaltotal 39.2% 284 / 724 SCAR 84.2
CC
139
Cov
39%
output
388.8
text_input
132.0
cli_helpers_initialize
76.2
CRAP 4527.0
↑ Summary
1 package CLI::Helpers;
2 # ABSTRACT: Subroutines for making simple command line scripts
3 # RECOMMEND PREREQ: App::Nopaste
4 # RECOMMEND PREREQ: Term::ReadLine::Gnu
5  
6 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use feature qw(state);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 2 ▶use Capture::Tiny qw(capture);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use Getopt::Long qw(GetOptionsFromArray :config pass_through);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use IO::Interactive qw( is_interactive );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use Module::Load qw(load);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use Ref::Util qw(is_ref is_arrayref is_hashref);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 ▶use Sys::Syslog qw(:standard);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 ▶use Term::ANSIColor 2.01 qw(color colored colorstrip);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use Term::ReadKey;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use Term::ReadLine;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶use YAML;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 2 our $VERSION = '2.0'; # VERSION
23  
24 # Capture ARGV at Load
25 2 my @ORIG_ARGS;
26 BEGIN {
27 2 ▶ @ORIG_ARGS = @ARGV;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 }
29  
30  
31 2 require Exporter;
32 2 our @ISA = qw(Exporter);
33  
34 2 my @output_tags = qw(output verbose debug debug_var cli_helpers_initialize);
35 2 my @input_tags = qw(prompt menu text_input confirm pwprompt);
36  
37 2 our @EXPORT_OK = ( @output_tags, @input_tags );
38 2 our %EXPORT_TAGS = (
39 all => [@output_tags,@input_tags],
40 input => \@input_tags,
41 output => \@output_tags,
42 );
43  
44 2 my $ARGV_AT_INIT = 0;
45 2 my $COPY_ARGV = 0;
46 2 our $_init_complete = 0;
47  
48 sub import {
49 1 ▶ my (@args) = @_;
Subroutine import: called CC=5 SCAR=17.0
50  
51 1 my @import = ();
52 # We need to process the config options
53 1 foreach my $arg ( @args ) {
54 3 ▶ if( $arg eq 'delay_argv' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($arg eq 'delay_argv') { } 1 2 3
elsif ($arg eq 'preprocess_argv') { } 0 2 2
elsif ($arg eq 'copy_argv') { } 0 2 2
55 1 $ARGV_AT_INIT = 0;
56 }
57 elsif( $arg eq 'preprocess_argv' ) {
58 0 $ARGV_AT_INIT = 1;
59 }
60 elsif( $arg eq 'copy_argv' ) {
61 0 $COPY_ARGV = 1;
62 }
63 # Not a config option, pass through
64 else {
65 2 push @import, $arg;
66 }
67 }
68  
69 1 CLI::Helpers->export_to_level( 1, @import );
70 }
71  
72 {
73 ## no critic (ProhibitNoWarnings)
74 2 ▶ no warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
75 INIT {
76 1 ▶ return if $_init_complete++;
Subroutine INIT: called CC=3 SCAR=12.0
Branch: 1 branch
BranchTrueFalseTotal
if $CLI::Helpers::_init_complete++ 0 1 1
77 1 ▶ cli_helpers_initialize() if $ARGV_AT_INIT;
Branch: 1 branch
BranchTrueFalseTotal
if $ARGV_AT_INIT 0 1 1
78 }
79 ## use critic
80 }
81  
82  
83 {
84 2 my @argv_original = ();
85 2 my $parsed_argv = 0;
86 sub _parse_options {
87 7 ▶ my ($opt_ref) = @_;
Subroutine _parse_options: called CC=6 SCAR=18.2
88 7 my @opt_spec = qw(
89 color!
90 verbose|v+
91 debug
92 debug-class=s
93 quiet
94 data-file=s
95 syslog!
96 syslog-facility=s
97 syslog-tag=s
98 syslog-debug!
99 tags=s
100 nopaste
101 nopaste-public
102 nopaste-service=s
103 );
104  
105 7 my $argv;
106 my %opt;
107 7 ▶ if( defined $opt_ref && is_arrayref($opt_ref) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt_ref and is_arrayref($opt_ref)) { } 5 2 7
Condition66%2/3
defined $opt_ref and is_arrayref($opt_ref)
!ll&&!rl&&r
205
MC/DC50%1/2
defined $opt_ref and is_arrayref($opt_ref)
defined $opt_ref is_arrayref($opt_ref)
Truth table66%2/3
A and B
A= defined $opt_refB= is_arrayref($opt_ref)
ABresult
0X0
100
111
108 # If passed an argv array, use that
109 5 ▶ $argv = $COPY_ARGV ? [ @{ $opt_ref } ] : $opt_ref;
Branch: 1 branch
BranchTrueFalseTotal
$COPY_ARGV ? : 0 5 5
110 }
111 else {
112 # Ensure multiple calls to cli_helpers_initialize() yield the same results
113 2 ▶ if ( $parsed_argv ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsed_argv) { } 1 1 2
114 ## no critic
115 1 @ARGV = @argv_original;
116 ## use critic
117 }
118 else {
119 1 @argv_original = @ARGV;
120 1 $parsed_argv++;
121 }
122 # Operate on @ARGV
123 2 ▶ $argv = $COPY_ARGV ? [ @ARGV ] : \@ARGV;
Branch: 1 branch
BranchTrueFalseTotal
$COPY_ARGV ? : 0 2 2
124 }
125 7 GetOptionsFromArray($argv, \%opt, @opt_spec );
126 7 return \%opt;
127 }
128 }
129  
130 2 my $DATA_HANDLE = undef;
131 sub _open_data_file {
132 0 ▶ my $data_file = shift;
Subroutine _open_data_file: not called CC=3 SCAR=24.8
133 eval {
134 0 ▶ open($DATA_HANDLE, '>', $data_file) or die "data file unwritable: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $DATA_HANDLE, ">", $data_file or die "data file unwritable: $!" 0 0 0
135 0 1;
136 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { open $DATA_HANDLE, ">", $data_file or die "data file unwritable: $!"; 1 } } or do { my $error = $@; output({"color", "red", "stderr", 1}, "Attempted to write to $data_file failed: $!") } 0 0 0
137 0 my $error = $@;
138 0 output({color=>'red',stderr=>1}, "Attempted to write to $data_file failed: $!");
139 };
140 }
141  
142  
143 # Set defaults
144 2 my %DEF = ();
145 2 my $TERM = undef;
146 2 my @STICKY = ();
147 2 my @NOPASTE = ();
148 2 my %TAGS = ();
149  
150  
151 sub cli_helpers_initialize {
152 7 ▶ my ($argv) = @_;
Subroutine cli_helpers_initialize: called CC=19 SCAR=43.3
Pod documented
153  
154 7 my $opts = _parse_options($argv);
155 7 ▶ _open_data_file($opts->{'data-file'}) if $opts->{'data-file'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"data-file"} 0 7 7
156  
157 # Initialize Global Definitions
158 %DEF = (
159 DEBUG => $opts->{debug} || 0,
160 DEBUG_CLASS => $opts->{'debug-class'} || 'main',
161 VERBOSE => $opts->{verbose} || 0,
162 KV_FORMAT => ': ',
163 QUIET => $opts->{quiet} || 0,
164 SYSLOG => $opts->{syslog} || 0,
165 SYSLOG_TAG => exists $opts->{'syslog-tag'} && length $opts->{'syslog-tag'} ? $opts->{'syslog-tag'} : basename($0),
166 SYSLOG_FACILITY => exists $opts->{'syslog-facility'} && length $opts->{'syslog-facility'} ? $opts->{'syslog-facility'} : 'local0',
167 SYSLOG_DEBUG => $opts->{'syslog-debug'} || 0,
168 0 ▶ TAGS => $opts->{tags} ? { map { $_ => 1 } split /,/, $opts->{tags} } : undef,
Condition50%1/2
$opts->{'nopaste'} || 0
l!l
07
MC/DC0%0/1
$opts->{'nopaste'} || 0
$opts->{'nopaste'}
Truth table50%1/2
A
A= $opts->{'nopaste'}
Aresult
11
00
169 NOPASTE => $opts->{nopaste} || 0,
170 NOPASTE_SERVICE => $opts->{'nopaste-service'},
171 7 ▶ NOPASTE_PUBLIC => $opts->{'nopaste-public'},
Branch: 3 branches
BranchTrueFalseTotal
exists $opts->{'syslog-tag'} && length $opts->{'syslog-tag'} ? : 0 7 7
exists $opts->{'syslog-facility'} && length $opts->{'syslog-facility'} ? : 0 7 7
$opts->{'tags'} ? : 0 7 7
Condition55%10/18
$opts->{'debug'} || 0
l!l
16
$opts->{'debug-class'} || 'main'
l!l
07
$opts->{'verbose'} || 0
l!l
43
$opts->{'quiet'} || 0
l!l
07
$opts->{'syslog'} || 0
l!l
07
exists $opts->{"syslog-tag"} and length $opts->{"syslog-tag"}
!ll&&!rl&&r
700
exists $opts->{"syslog-facility"} and length $opts->{"syslog-facility"}
!ll&&!rl&&r
700
$opts->{'syslog-debug'} || 0
l!l
07
MC/DC100%1/1
$opts->{'debug'} || 0
$opts->{'debug'}
MC/DC0%0/1
$opts->{'debug-class'} || 'main'
$opts->{'debug-class'}
MC/DC100%1/1
$opts->{'verbose'} || 0
$opts->{'verbose'}
MC/DC0%0/1
$opts->{'quiet'} || 0
$opts->{'quiet'}
MC/DC0%0/1
$opts->{'syslog'} || 0
$opts->{'syslog'}
MC/DC0%0/2
exists $opts->{"syslog-tag"} and length $opts->{"syslog-tag"}
exists $opts->{"syslog-tag"} length $opts->{"syslog-tag"}
MC/DC0%0/2
exists $opts->{"syslog-facility"} and length $opts->{"syslog-facility"}
exists $opts->{"syslog-facility"} length $opts->{"syslog-facility"}
MC/DC0%0/1
$opts->{'syslog-debug'} || 0
$opts->{'syslog-debug'}
Truth table100%2/2
A
A= $opts->{'debug'}
Aresult
11
00
Truth table50%1/2
A
A= $opts->{'debug-class'}
Aresult
11
00
Truth table100%2/2
A
A= $opts->{'verbose'}
Aresult
11
00
Truth table50%1/2
A
A= $opts->{'quiet'}
Aresult
11
00
Truth table50%1/2
A
A= $opts->{'syslog'}
Aresult
11
00
Truth table33%1/3
A and B
A= exists $opts->{"syslog-tag"}B= length $opts->{"syslog-tag"}
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= exists $opts->{"syslog-facility"}B= length $opts->{"syslog-facility"}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $opts->{'syslog-debug'}
Aresult
11
00
172 );
173 7 ▶ $DEF{COLOR} = $opts->{color} // git_color_check();
Condition33%1/3
$opts->{"color"} // git_color_check()
l!l&&r!l&&!r
007
MC/DC0%0/2
$opts->{"color"} // git_color_check()
$opts->{"color"} git_color_check()
Truth table33%1/3
A // B
A= $opts->{"color"}B= git_color_check()
ABresult
1X1
011
000
174  
175 7 debug("DEFINITIONS");
176 7 debug_var(\%DEF);
177  
178 # Setup the Syslog Subsystem
179 7 ▶ if( $DEF{SYSLOG} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DEF{"SYSLOG"}) 0 7 7
180 eval {
181 0 openlog($DEF{SYSLOG_TAG}, 'ndelay,pid', $DEF{SYSLOG_FACILITY});
182 0 1;
183 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { openlog($DEF{"SYSLOG_TAG"}, "ndelay,pid", $DEF{"SYSLOG_FACILITY"}); 1 } } or do { my $error = $@; $DEF{"SYSLOG"} = 0; output({"stderr", 1, "color", "red"}, "CLI::Helpers could not open syslog: $error") } 0 0 0
184 0 my $error = $@;
185 0 $DEF{SYSLOG}=0;
186 0 output({stderr=>1,color=>'red'}, "CLI::Helpers could not open syslog: $error");
187 };
188 }
189  
190 # Optionally Attempt Loading App::NoPaste
191 7 ▶ if( $DEF{NOPASTE} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DEF{"NOPASTE"}) 0 7 7
192 eval {
193 0 load 'App::Nopaste';
194 0 1;
195 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &load("App::Nopaste"); 1 } } or do { $DEF{"NOPASTE"} = 0; output({"stderr", 1, "color", "red", "sticky", 1}, "App::Nopaste is not installed, please cpanm App::Nopaste for --nopaste support") } 0 0 0
196 0 $DEF{NOPASTE} = 0;
197 0 output({stderr=>1,color=>'red',sticky=>1},
198 'App::Nopaste is not installed, please cpanm App::Nopaste for --nopaste support',
199 );
200 };
201 }
202  
203 7 return 1;
204 }
205  
206  
207 # Allow some messages to be fired at the end the of program
208 END {
209 # Show discovered tags
210 2 ▶ if( keys %TAGS ) {
Subroutine END: called CC=10 SCAR=39.8
Branch: 1 branch
BranchTrueFalseTotal
if (keys %TAGS) 0 2 2
211 output({color=>'cyan',stderr=>1},
212 sprintf "# Tags discovered: %s",
213 0 join(', ', map { "$_=$TAGS{$_}" } sort keys %TAGS)
214 );
215 }
216 # Show Sticky Output
217 2 ▶ if(@STICKY) {
Branch: 1 branch
BranchTrueFalseTotal
if (@STICKY) 0 2 2
218 0 foreach my $args (@STICKY) {
219 0 output(@{ $args });
220 }
221 }
222 # Do the Nopaste
223 2 ▶ if( @NOPASTE ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@NOPASTE) 0 2 2
224 0 my $command_string = join(" ", $0, @ORIG_ARGS);
225 0 unshift @NOPASTE, "\$ $command_string";
226 # Figure out what services to use
227 my $services = $DEF{NOPASTE_SERVICE} ? [ split /,/, $DEF{NOPASTE_SERVICE} ]
228 0 ▶ : $ENV{NOPASTE_SERVICES} ? [ split /,/, $ENV{NOPASTE_SERVICES} ]
Branch: 2 branches
BranchTrueFalseTotal
$DEF{'NOPASTE_SERVICE'} ? : 0 0 0
$ENV{'NOPASTE_SERVICES'} ? : 0 0 0
229 : undef;
230 my %paste = (
231 text => join("\n", @NOPASTE),
232 summary => $command_string,
233 desc => $command_string,
234 # Default to a Private Paste
235 0 ▶ private => $DEF{NOPASTE_PUBLIC} ? 0 : 1,
Branch: 1 branch
BranchTrueFalseTotal
$DEF{'NOPASTE_PUBLIC'} ? : 0 0 0
236 );
237 0 debug_var(\%paste);
238 0 ▶ if( $services ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($services) { } 0 0 0
239 0 output({color=>'cyan',stderr=>1}, "# NoPaste: "
240 . App::Nopaste->nopaste(%paste, services => $services)
241 );
242 }
243 else {
244 0 output({color=>'red',stderr=>1,clear=>1},
245 "!! In order to use --nopaste, you need to your environment variable",
246 "!! NOPASTE_SERVICES or pass --nopaste-service, e.g.:",
247 "!! export NOPASTE_SERVICES=Shadowcat,PastebinCom");
248 }
249 }
250 2 ▶ closelog() if $DEF{SYSLOG};
Branch: 1 branch
BranchTrueFalseTotal
if $DEF{"SYSLOG"} 0 2 2
251 }
252  
253  
254 2 ▶sub def { return exists $DEF{$_[0]} ? $DEF{$_[0]} : undef }
Subroutine def: called CC=2 SCAR=7.6
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
exists $DEF{$_[0]} ? : 2 0 2
255  
256  
257 sub git_color_check {
258 7 ▶ return unless is_interactive();
Subroutine git_color_check: called CC=5 SCAR=31.5
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless is_interactive() 7 0 7
259  
260 0 my @cmd = qw(git config --global --get color.ui);
261 my($stdout,$stderr,$rc) = capture {
262 0 ▶ system @cmd;
Subroutine __ANON__: not called CC=1 SCAR=6.9
263 0 };
264 0 ▶ if( $rc != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc != 0) 0 0 0
265 0 debug("git_color_check error: $stderr");
266 0 return 0;
267 }
268 0 debug("git_color_check out: $stdout");
269 0 ▶ if( $stdout =~ /auto/ || $stdout =~ /true/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stdout =~ /auto/ or $stdout =~ /true/) 0 0 0
Condition0%0/3
$stdout =~ /auto/ or $stdout =~ /true/
l!l&&r!l&&!r
000
MC/DC0%0/2
$stdout =~ /auto/ or $stdout =~ /true/
$stdout =~ /auto/ $stdout =~ /true/
Truth table0%0/3
A or B
A= $stdout =~ /auto/B= $stdout =~ /true/
ABresult
1X1
011
000
270 0 return 1;
271 }
272  
273 0 return 0;
274 }
275  
276  
277 sub colorize {
278 0 ▶ my ($color,$string) = @_;
Subroutine colorize: not called CC=3 SCAR=24.8
Pod documented
279  
280 0 ▶ if( defined $color && $DEF{COLOR} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $color and $DEF{"COLOR"}) 0 0 0
Condition0%0/3
defined $color and $DEF{"COLOR"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $color and $DEF{"COLOR"}
defined $color $DEF{"COLOR"}
Truth table0%0/3
A and B
A= defined $colorB= $DEF{"COLOR"}
ABresult
0X0
100
111
281 0 $string=colored([ $color ], $string);
282 }
283 0 return $string;
284 }
285  
286  
287 sub output {
288 16 ▶ my $opts = is_hashref($_[0]) ? shift @_ : {};
Subroutine output: called CC=38 SCAR=59.6
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
is_hashref($_[0]) ? : 11 5 16
289  
290 # Return unless we have something to work with;
291 16 ▶ return unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 16 16
292  
293 # Ensure we're all setup
294 16 ▶ cli_helpers_initialize() unless keys %DEF;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %DEF 0 16 16
295  
296 # Input/output Arrays
297 16 ▶ my @input = map { my $x=$_; chomp($x) if defined $x; $x; } @_;
Branch: 1 branch
BranchTrueFalseTotal
if defined $x 16 0 16
298 16 my @output = ();
299  
300 # Determine the color
301 16 ▶ my $color = exists $opts->{color} && defined $opts->{color} ? $opts->{color} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts->{'color'} && defined $opts->{'color'} ? : 0 16 16
Condition33%1/3
exists $opts->{"color"} and defined $opts->{"color"}
!ll&&!rl&&r
1600
MC/DC0%0/2
exists $opts->{"color"} and defined $opts->{"color"}
exists $opts->{"color"} defined $opts->{"color"}
Truth table33%1/3
A and B
A= exists $opts->{"color"}B= defined $opts->{"color"}
ABresult
0X0
100
111
302  
303 # Determine indentation
304 16 ▶ my $indent = exists $opts->{indent} ? " "x(2*$opts->{indent}) : '';
Branch: 1 branch
BranchTrueFalseTotal
exists $opts->{'indent'} ? : 0 16 16
305  
306 # If tagged, we only output if the tag is requested
307 16 ▶ if( $DEF{TAGS} && exists $opts->{tag} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DEF{"TAGS"} and exists $opts->{"tag"}) 0 16 16
Condition33%1/3
$DEF{"TAGS"} and exists $opts->{"tag"}
!ll&&!rl&&r
1600
MC/DC0%0/2
$DEF{"TAGS"} and exists $opts->{"tag"}
$DEF{"TAGS"} exists $opts->{"tag"}
Truth table33%1/3
A and B
A= $DEF{"TAGS"}B= exists $opts->{"tag"}
ABresult
0X0
100
111
308 # Skip this altogether
309 0 ▶ $TAGS{$opts->{tag}} ||= 0;
Condition0%0/2
$TAGS{$opts->{"tag"}} ||= 0
l!l
00
MC/DC0%0/1
$TAGS{$opts->{"tag"}} ||= 0
$TAGS{$opts->{"tag"}}
Truth table0%0/2
A
A= $TAGS{$opts->{"tag"}}
Aresult
11
00
310 0 $TAGS{$opts->{tag}}++;
311 0 ▶ return unless $DEF{TAGS}->{$opts->{tag}};
Branch: 1 branch
BranchTrueFalseTotal
unless $DEF{"TAGS"}{$opts->{"tag"}} 0 0 0
312 }
313  
314 # Determine if we're doing Key Value Pairs
315 16 ▶ my $DO_KV = (scalar(@input) % 2 == 0 ) && (exists $opts->{kv} && $opts->{kv} == 1) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
scalar(@input) % 2 == 0 && (exists $opts->{'kv'} && $opts->{'kv'} == 1) ? : 0 16 16
Condition16%1/6
scalar(@input) % 2 == 0 and (exists $opts->{"kv"} and $opts->{"kv"} == 1)
!ll&&!rl&&r
1600
exists $opts->{"kv"} and $opts->{"kv"} == 1
!ll&&!rl&&r
000
MC/DC0%0/3
scalar(@input) % 2 == 0 and (exists $opts->{"kv"} and $opts->{"kv"} == 1)
scalar(@input) % 2 == 0 exists $opts->{"kv"} $opts->{"kv"} == 1
Truth table25%1/4
A and B and C
A= scalar(@input) % 2 == 0B= exists $opts->{"kv"}C= $opts->{"kv"} == 1
ABCresult
0XX0
10X0
1100
1111
316  
317 16 ▶ if( $DO_KV ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DO_KV) { } 0 16 16
318 0 ▶ while( @input ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@input) 0 0 0
319 0 my $k = shift @input;
320 # We only colorize the value
321 0 my $v = shift @input;
322 0 ▶ $v ||= $DEF{KV_FORMAT} eq ': ' ? '~' : '';
Branch: 1 branch
BranchTrueFalseTotal
$DEF{'KV_FORMAT'} eq ': ' ? : 0 0 0
Condition0%0/3
$v ||= $DEF{"KV_FORMAT"} eq ": " ? "~" : ""
l!l&&r!l&&!r
000
MC/DC0%0/2
$v ||= $DEF{"KV_FORMAT"} eq ": " ? "~" : ""
$v $DEF{"KV_FORMAT"} eq ": " ? "~" : ""
Truth table0%0/3
A ||= B
A= $vB= $DEF{"KV_FORMAT"} eq ": " ? "~" : ""
ABresult
1X1
011
000
323 0 push @output, join($DEF{KV_FORMAT}, $k, colorize($color,$v));
324 }
325 }
326 else {
327 16 ▶ @output = map { defined $color ? colorize($color, $_) : $_; } @input;
Branch: 1 branch
BranchTrueFalseTotal
defined $color ? : 0 16 16
328 }
329  
330 # Out to the console
331 16 ▶ if( !$DEF{QUIET} || $opts->{IMPORTANT} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $DEF{"QUIET"} or $opts->{"IMPORTANT"}) 16 0 16
Condition33%1/3
not $DEF{"QUIET"} or $opts->{"IMPORTANT"}
l!l&&r!l&&!r
1600
MC/DC0%0/2
not $DEF{"QUIET"} or $opts->{"IMPORTANT"}
not $DEF{"QUIET"} $opts->{"IMPORTANT"}
Truth table33%1/3
not(A) or B
A= not $DEF{"QUIET"}B= $opts->{"IMPORTANT"}
ABresult
1X1
011
000
332 16 ▶ my $out_handle = $opts->{stderr} ? \*STDERR : \*STDOUT;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'stderr'} ? : 5 11 16
333 # Do clearing
334 16 ▶ print $out_handle "\n"x$opts->{clear} if exists $opts->{clear};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"clear"} 0 16 16
335 # Print output
336 16 print $out_handle "${indent}$_\n" for @output;
337 }
338  
339 # Handle data, which is raw
340 16 ▶ if(defined $DATA_HANDLE && $opts->{data}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $DATA_HANDLE and $opts->{'data'}) { } 0 16 16
elsif ($DEF{'SYSLOG'} and not $opts->{'no_syslog'}) { } 0 32 32
Condition33%1/3
defined $DATA_HANDLE and $opts->{"data"}
!ll&&!rl&&r
1600
MC/DC0%0/2
defined $DATA_HANDLE and $opts->{"data"}
defined $DATA_HANDLE $opts->{"data"}
Truth table33%1/3
A and B
A= defined $DATA_HANDLEB= $opts->{"data"}
ABresult
0X0
100
111
341 0 print $DATA_HANDLE "$_\n" for @input;
342 }
343 ▶ elsif( $DEF{SYSLOG} && !$opts->{no_syslog}) {
Condition33%1/3
$DEF{"SYSLOG"} and not $opts->{"no_syslog"}
!ll&&!rl&&r
1600
MC/DC0%0/2
$DEF{"SYSLOG"} and not $opts->{"no_syslog"}
$DEF{"SYSLOG"} not $opts->{"no_syslog"}
Truth table33%1/3
A and not(B)
A= $DEF{"SYSLOG"}B= not $opts->{"no_syslog"}
ABresult
0X0
100
111
344 my $level = exists $opts->{syslog_level} ? $opts->{syslog_level} :
345 0 ▶ exists $opts->{stderr} ? 'err' :
Branch: 2 branches
BranchTrueFalseTotal
exists $opts->{'syslog_level'} ? : 0 0 0
exists $opts->{'stderr'} ? : 0 0 0
346 'notice';
347  
348 # Warning for syslogging data file
349 unshift @output, "CLI::Helpers logging a data section, use --data-file to suppress this in syslog."
350 0 ▶ if $opts->{data};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"data"} 0 0 0
351  
352 # Now syslog the message
353 0 debug({no_syslog=>1,color=>'magenta'}, sprintf "[%s] Syslogging %d messages, with: %s", $level, scalar(@output), join(",", map { $_=>$opts->{$_} } keys %{ $opts }));
354 0 for( @output ) {
355 # One bad message means no more syslogging
356 eval {
357 0 syslog($level, colorstrip($_));
358 0 1;
359 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { syslog($level, colorstrip($_)); 1 } } or do { my $error = $@; $DEF{"SYSLOG"} = 0; output({"stderr", 1, "color", "red", "no_syslog", 1}, "syslog() failed: $error") } 0 0 0
360 0 my $error = $@;
361 0 $DEF{SYSLOG} = 0;
362 0 output({stderr=>1,color=>'red',no_syslog=>1}, "syslog() failed: $error");
363 };
364 }
365 }
366  
367 # Sticky messages don't just go away
368 16 ▶ if(exists $opts->{sticky}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts->{"sticky"}) 0 16 16
369 0 my %o = %{ $opts }; # Make a copy because we shifted this off @_
370 # So this doesn't happen in the END block again
371 0 delete $o{$_} for grep { exists $o{$_} } qw(sticky data);
372 0 $o{no_syslog} = 1;
373 0 push @STICKY, [ \%o, @input ];
374 }
375 16 ▶ if( $DEF{NOPASTE} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DEF{"NOPASTE"}) 0 16 16
376 0 push @NOPASTE, map { $indent . colorstrip($_) } @output;
377 }
378 }
379  
380  
381 sub verbose {
382 10 ▶ my $opts = is_hashref($_[0]) ? shift @_ : {};
Subroutine verbose: called CC=7 SCAR=19.5
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
is_hashref($_[0]) ? : 5 5 10
383 10 ▶ $opts->{level} = 1 unless exists $opts->{level};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts->{"level"} 5 5 10
384 10 ▶ $opts->{syslog_level} = $opts->{level} > 1 ? 'debug' : 'info';
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'level'} > 1 ? : 5 5 10
385 10 my @msgs=@_;
386  
387 # Ensure we're all configured
388 10 ▶ cli_helpers_initialize() unless keys %DEF;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %DEF 0 10 10
389  
390 10 ▶ if( !$DEF{DEBUG} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($DEF{"DEBUG"}) 8 2 10
391 8 ▶ return unless $DEF{VERBOSE} >= $opts->{level};
Branch: 1 branch
BranchTrueFalseTotal
unless $DEF{"VERBOSE"} >= $opts->{"level"} 5 3 8
392 }
393 5 output( $opts, @msgs );
394 }
395  
396  
397 sub debug {
398 19 ▶ my $opts = is_hashref($_[0]) ? shift @_ : {};
Subroutine debug: called CC=8 SCAR=21.1
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
is_hashref($_[0]) ? : 7 12 19
399 19 my @msgs=@_;
400  
401 # Ensure we're all configured
402 19 ▶ cli_helpers_initialize() unless keys %DEF;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %DEF 0 19 19
403  
404 # Smarter handling of debug output
405 19 ▶ return unless $DEF{DEBUG};
Branch: 1 branch
BranchTrueFalseTotal
unless $DEF{"DEBUG"} 16 3 19
406  
407 # Check against caller class
408 3 ▶ my $package = exists $opts->{_caller_package} ? $opts->{_caller_package} : (caller)[0];
Branch: 1 branch
BranchTrueFalseTotal
exists $opts->{'_caller_package'} ? : 1 2 3
409 3 ▶ return unless lc $DEF{DEBUG_CLASS} eq 'all' || $package eq $DEF{DEBUG_CLASS};
Branch: 1 branch
BranchTrueFalseTotal
unless lc $DEF{"DEBUG_CLASS"} eq "all" or $package eq $DEF{"DEBUG_CLASS"} 2 1 3
Condition66%2/3
lc $DEF{"DEBUG_CLASS"} eq "all" or $package eq $DEF{"DEBUG_CLASS"}
l!l&&r!l&&!r
012
MC/DC50%1/2
lc $DEF{"DEBUG_CLASS"} eq "all" or $package eq $DEF{"DEBUG_CLASS"}
lc $DEF{"DEBUG_CLASS"} eq "all" $package eq $DEF{"DEBUG_CLASS"}
Truth table66%2/3
A or B
A= lc $DEF{"DEBUG_CLASS"} eq "all"B= $package eq $DEF{"DEBUG_CLASS"}
ABresult
1X1
011
000
410  
411 # Check if we really want to debug syslog data
412 1 $opts->{syslog_level} = 'debug';
413 1 ▶ $opts->{no_syslog} //= !$DEF{SYSLOG_DEBUG};
Condition33%1/3
$opts->{"no_syslog"} //= !$DEF{"SYSLOG_DEBUG"}
l!l&&r!l&&!r
010
MC/DC0%0/2
$opts->{"no_syslog"} //= !$DEF{"SYSLOG_DEBUG"}
$opts->{"no_syslog"} !$DEF{"SYSLOG_DEBUG"}
Truth table33%1/3
A //= not(B)
A= $opts->{"no_syslog"}B= !$DEF{"SYSLOG_DEBUG"}
ABresult
1X1
011
000
414  
415 # Output
416 1 output( $opts, @msgs );
417 }
418  
419  
420 sub debug_var {
421 7 ▶ my $opts = {
Subroutine debug_var: called CC=5 SCAR=23.4
Pod documented
422 clear => 1, # Meant for the screen
423 no_syslog => 1, # Meant for the screen
424 _caller_package => (caller)[0], # Make sure this is set on entry
425 };
426 # Merge with options
427 7 ▶ if( is_hashref($_[0]) && defined $_[1] && is_ref($_[1]) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_hashref($_[0]) and defined $_[1] and is_ref($_[1])) 0 7 7
Condition33%2/6
is_hashref($_[0]) and defined $_[1] and is_ref($_[1])
!ll&&!rl&&r
700
is_hashref($_[0]) and defined $_[1]
!ll&&!rl&&r
070
MC/DC0%0/3
is_hashref($_[0]) and defined $_[1] and is_ref($_[1])
is_hashref($_[0]) defined $_[1] is_ref($_[1])
Truth table25%1/4
A and B and C
A= is_hashref($_[0])B= defined $_[1]C= is_ref($_[1])
ABCresult
0XX0
10X0
1100
1111
428 0 my $ref = shift;
429 0 foreach my $k (keys %{ $ref } ) {
430 0 $opts->{$k} = $ref->{$k};
431 };
432 }
433 7 debug($opts, Dump shift);
434 }
435  
436  
437 2 my %_allow_override = map { $_ => 1 } qw(debug verbose);
438 sub override {
439 0 ▶ my ($var,$value) = @_;
Subroutine override: not called CC=2 SCAR=17.9
Pod documented
440  
441 0 ▶ return unless exists $_allow_override{lc $var};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $_allow_override{lc $var} 0 0 0
442  
443 0 my $def_var = uc $var;
444 0 $DEF{$def_var} = $value;
445 }
446  
447  
448 2 my $_Confirm_Valid;
449 sub confirm {
450 0 ▶ my ($question) = @_;
Subroutine confirm: not called CC=5 SCAR=34.0
Pod documented
451  
452 # Initialize Globals
453 0 ▶ $_Confirm_Valid ||= {qw(y 1 yes 1 n 0 no 0)};
Condition0%0/2
$_Confirm_Valid ||= {"y", 1, "yes", 1, "n", 0, "no", 0}
l!l
00
MC/DC0%0/1
$_Confirm_Valid ||= {"y", 1, "yes", 1, "n", 0, "no", 0}
$_Confirm_Valid
Truth table0%0/2
A
A= $_Confirm_Valid
Aresult
11
00
454  
455 0 $question =~ s/\s*$/ [yN] /;
456 0 my $answer = undef;
457 0 ▶ until( defined $answer && exists $_Confirm_Valid->{$answer} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $answer and exists $_Confirm_Valid->{$answer}) 0 0 0
Condition0%0/3
defined $answer and exists $_Confirm_Valid->{$answer}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $answer and exists $_Confirm_Valid->{$answer}
defined $answer exists $_Confirm_Valid->{$answer}
Truth table0%0/3
A and B
A= defined $answerB= exists $_Confirm_Valid->{$answer}
ABresult
0X0
100
111
458 0 ▶ output({color=>'red',stderr=>1},"ERROR: must be one of 'y','n','yes','no'") if defined $answer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $answer 0 0 0
459 0 $answer = lc _get_input($question);
460 }
461 0 return $_Confirm_Valid->{$answer};
462 }
463  
464  
465 sub text_input {
466 0 ▶ my $question = shift;
Subroutine text_input: not called CC=11 SCAR=48.8
Pod documented
467 0 my %args = @_;
468  
469 # Prompt fixes
470 0 chomp($question);
471 0 ▶ my $terminator = $question =~ s/([^a-zA-Z0-9\)\]\}])\s*$// ? $1 : ':';
Branch: 1 branch
BranchTrueFalseTotal
$question =~ s/([^a-zA-Z0-9\)\]\}])\s*$// ? : 0 0 0
472 0 ▶ if(exists $args{default}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"default"}) 0 0 0
473 0 $question .= " (default=$args{default}) ";
474 }
475 0 $question .= "$terminator ";
476  
477 # Make sure there's a space before the prompt
478 0 $question =~ s/\s*$/ /;
479 0 ▶ my $validate = exists $args{validate} ? $args{validate} : {};
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'validate'} ? : 0 0 0
480  
481 0 my $text;
482 0 my $error = undef;
483 0 ▶ until( defined $text && !defined $error ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $text and not defined $error) 0 0 0
Condition0%0/3
defined $text and not defined $error
!ll&&!rl&&r
000
MC/DC0%0/2
defined $text and not defined $error
defined $text not defined $error
Truth table0%0/3
A and not(B)
A= defined $textB= not defined $error
ABresult
0X0
100
111
484 0 ▶ output({color=>'red',stderr=>1},"ERROR: $error") if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 0 0 0
485  
486 # Try to have the user answer the question
487 0 $text = _get_input($question => \%args);
488 0 $error = undef;
489  
490 # Check the default if the person just hit enter
491 0 ▶ if( exists $args{default} && length($text) == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"default"} and length $text == 0) 0 0 0
Condition0%0/3
exists $args{"default"} and length $text == 0
!ll&&!rl&&r
000
MC/DC0%0/2
exists $args{"default"} and length $text == 0
exists $args{"default"} length $text == 0
Truth table0%0/3
A and B
A= exists $args{"default"}B= length $text == 0
ABresult
0X0
100
111
492 0 return $args{default};
493 }
494 0 foreach my $v (keys %{$validate}) {
495 0 local $_ = $text;
496 0 ▶ if( $validate->{$v}->() > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($validate->{$v}->() > 0) 0 0 0
497 0 debug({indent=>1}," + Validated: $v");
498 0 next;
499 }
500 0 $error = $v;
501 0 last;
502 }
503 }
504 0 return $text;
505 }
506  
507  
508 sub menu {
509 0 ▶ my ($question,$opts) = @_;
Subroutine menu: not called CC=8 SCAR=42.8
Pod documented
510 0 my %desc = ();
511  
512 # Determine how to handle this list
513 0 ▶ if( is_arrayref($opts) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_arrayref($opts)) { } 0 0 0
elsif (is_hashref($opts)) { } 0 0 0
514 0 %desc = map { $_ => $_ } @{ $opts };
515 }
516 elsif( is_hashref($opts) ) {
517 0 %desc = %{ $opts };
518 }
519  
520 0 print "$question\n\n";
521 0 my %ref = ();
522 0 my $id = 0;
523 0 foreach my $key (sort keys %desc) {
524 0 $ref{++$id} = $key;
525 }
526  
527 0 my $choice;
528 0 ▶ until( defined $choice && exists $ref{$choice} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $choice and exists $ref{$choice}) 0 0 0
Condition0%0/3
defined $choice and exists $ref{$choice}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $choice and exists $ref{$choice}
defined $choice exists $ref{$choice}
Truth table0%0/3
A and B
A= defined $choiceB= exists $ref{$choice}
ABresult
0X0
100
111
529 0 ▶ output({color=>'red',stderr=>1},"ERROR: invalid selection") if defined $choice;
Branch: 1 branch
BranchTrueFalseTotal
if defined $choice 0 0 0
530 0 foreach my $id (sort { $a <=> $b } keys %ref) {
531 0 printf " %d. %s\n", $id, $desc{$ref{$id}};
532 }
533 0 print "\n";
534 0 $choice = _get_input("Selection (1-$id): ");
535 }
536 0 return $ref{$choice};
537 }
538  
539  
540 sub pwprompt {
541 0 ▶ my ($prompt, %args) = @_;
Subroutine pwprompt: not called CC=3 SCAR=24.8
Pod documented
542 0 ▶ $prompt ||= "Password: ";
Condition0%0/2
$prompt ||= "Password: "
l!l
00
MC/DC0%0/1
$prompt ||= "Password: "
$prompt
Truth table0%0/2
A
A= $prompt
Aresult
11
00
543 0 my @more_validate;
544 0 ▶ if (my $validate = $args{validate}){
Branch: 1 branch
BranchTrueFalseTotal
if (my $validate = $args{"validate"}) 0 0 0
545 0 @more_validate = %$validate;
546 }
547 return text_input($prompt,
548 noecho => 1,
549 0 ▶ validate => { "password length can't be zero." => sub { defined && length },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and length $_ 0 0 0
550 0 @more_validate,
551 },
552 );
553 }
554  
555  
556 sub prompt {
557 0 ▶ my ($prompt) = shift;
Subroutine prompt: not called CC=5 SCAR=34.0
Pod documented
558 0 my %args = @_;
559  
560 0 ▶ return confirm($prompt) if exists $args{yn};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"yn"} 0 0 0
561 0 ▶ return menu($prompt, $args{menu}) if exists $args{menu};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"menu"} 0 0 0
562 # Check for a password prompt
563 0 ▶ if( lc($prompt) =~ /passw(or)?d/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc($prompt) =~ /passw(or)?d/) 0 0 0
564 0 $args{noecho} = 1;
565 0 ▶ $args{validate} ||= {};
Condition0%0/2
$args{"validate"} ||= {}
l!l
00
MC/DC0%0/1
$args{"validate"} ||= {}
$args{"validate"}
Truth table0%0/2
A
A= $args{"validate"}
Aresult
11
00
566 0 ▶ $args{validate}->{"password length can't be zero."} = sub { defined && length };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and length $_ 0 0 0
567 }
568 0 return text_input($prompt,%args);
569 }
570  
571 sub _get_input {
572 0 ▶ my ($prompt,$args) = @_;
Subroutine _get_input: not called CC=8 SCAR=42.8
573  
574 0 state $interactive = is_interactive();
575 0 state $term;
576  
577 0 my $text = '';
578 0 ▶ if( $interactive ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interactive) { } 0 0 0
579 # Initialize Term
580 0 ▶ $term ||= Term::ReadLine->new($0);
Condition0%0/3
$term ||= "Term::ReadLine"->new($0)
l!l&&r!l&&!r
000
MC/DC0%0/2
$term ||= "Term::ReadLine"->new($0)
$term "Term::ReadLine"->new($0)
Truth table0%0/3
A ||= B
A= $termB= "Term::ReadLine"->new($0)
ABresult
1X1
011
000
581 0 ▶ $args ||= {};
Condition0%0/2
$args ||= {}
l!l
00
MC/DC0%0/1
$args ||= {}
$args
Truth table0%0/2
A
A= $args
Aresult
11
00
582 0 ▶ if( exists $args->{noecho} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{'noecho'}) { } 0 0 0
583 0 my $attrs = $term->Attribs;
584 0 ▶ if( $attrs->{shadow_redisplay} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{'shadow_redisplay'}) { } 0 0 0
585 0 my $restore = $attrs->{redisplay_function};
586 0 $attrs->{redisplay_function} = $attrs->{shadow_redisplay};
587 0 $text = $term->readline($prompt);
588 0 $attrs->{redisplay_function} = $restore;
589 }
590 else {
591 # Disable all the Term ReadLine magic
592 0 local $|=1;
593 0 print $prompt;
594 0 ReadMode('noecho');
595 0 $text = ReadLine();
596 0 ReadMode('restore');
597 0 print "\n";
598 0 chomp($text);
599 }
600 }
601 else {
602 0 $text = $term->readline($prompt);
603 0 ▶ $term->addhistory($text) if length $text && $text =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if length $text and $text =~ /\S/ 0 0 0
Condition0%0/3
length $text and $text =~ /\S/
!ll&&!rl&&r
000
MC/DC0%0/2
length $text and $text =~ /\S/
length $text $text =~ /\S/
Truth table0%0/3
A and B
A= length $textB= $text =~ /\S/
ABresult
0X0
100
111
604 }
605 }
606 else {
607 # Read one line from STDIN
608 0 $text = <>;
609 }
610 0 return $text;
611 }
612  
613  
614  
615 # Return True
616 2 1;
617  
618 __END__
619  
620 =pod
621  
622 =encoding UTF-8
623  
624 =head1 NAME
625  
626 CLI::Helpers - Subroutines for making simple command line scripts
627  
628 =head1 VERSION
629  
630 version 2.0
631  
632 =head1 SYNOPSIS
633  
634 Use this module to make writing intelligent command line scripts easier.
635  
636 #!/usr/bin/env perl
637 use CLI::Helpers qw(:all);
638  
639 output({color=>'green'}, "Hello, World!");
640 verbose({indent=>1,color=>'yellow'}, "Shiny, happy people!");
641 verbose({level=>2,kv=>1,color=>'red'}, a => 1, b => 2);
642 debug_var({ c => 3, d => 4});
643  
644 # Data
645 output({data=>1}, join(',', qw(a b c d)));
646  
647 # Wait for confirmation
648 die "ABORTING" unless confirm("Are you sure?");
649  
650 # Ask for a number
651 my $integer = prompt "Enter an integer:", validate => { "not a number" => sub { /^\d+$/ } }
652  
653 # Ask for next move
654 my %menu = (
655 north => "Go north.",
656 south => "Go south.",
657 );
658 my $dir = prompt "Where to, adventurous explorer?", menu => \%menu;
659  
660 # Ask for a favorite animal
661 my $favorite = menu("Select your favorite animal:", [qw(dog cat pig fish otter)]);
662  
663 Running:
664  
665 $ ./test.pl
666 Hello, World!
667 a,b,c,d
668 $ ./test.pl --verbose
669 Hello, World!
670 Shiny, Happy people!
671 a,b,c,d
672 $ ./test.pl -vv
673 Hello, World!
674 Shiny, Happy people!
675 a: 1
676 b: 2
677 a,b,c,d
678 $ ./test.pl --debug
679 Hello, World!
680 Shiny, Happy people!
681 a: 1
682 b: 2
683 ---
684 c: 3
685 d: 4
686 a,b,c,d
687  
688 $ ./test.pl --data-file=output.csv
689 Hello, World!
690 a,b,c,d
691 $ cat output.csv
692 a,b,c,d
693  
694 Colors would be automatically enabled based on the user's ~/.gitconfig
695  
696 =head1 OVERVIEW
697  
698 This module provides a library of useful functions for constructing simple command
699 line interfaces. It is able to extract information from the environment and your
700 ~/.gitconfig to display data in a reasonable manner.
701  
702 Using this module adds argument parsing using L<Getopt::Long> to your script. It
703 enables pass-through, so you can still use your own argument parsing routines or
704 Getopt::Long in your script.
705  
706 =head1 FUNCTIONS
707  
708 =head2 cli_helpers_initialize
709  
710 This is called automatically when C<preprocess_argv> is set. By default, it'll
711 be run the first time a definition is needed, usually the first call to
712 C<output()>. If called automatically, it will operate on C<@ARGV>. You can
713 optionally pass an array reference to this function and it'll operate that
714 instead.
715  
716 In most cases, you don't need to call this function directly. It must be
717 explicitly requested in the import.
718  
719 use CLI::Helpers qw( :output );
720  
721 ...
722 # I want access to ARGV before CLI::Helpers;
723 my %opts = get_important_things_from(\@ARGV);
724  
725 # Now, let CLI::Helpers take the rest, implicit
726 # call to cli_helpers_initialize()
727 output("ready");
728  
729 Alternatively, you could:
730  
731 use CLI::Helpers qw( :output preprocess_argv );
732  
733 ...
734 # Since CLI::Helpers opts are stripped from @ARGV,
735 # Getopt::Long::Descriptive won't complain about extra args
736 my ($opt,$usage) = describe_option( ... );
737  
738 # Now, let CLI::Helpers take the rest, implicit
739 # call to cli_helpers_initialize()
740 output("ready");
741  
742 Or if you'd prefer not to touch C<@ARGV> at all, you pass in an array ref:
743  
744 use CLI::Helpers qw( :output );
745  
746 my ($opt,$usage) = describe_option( ... );
747  
748 cli_helpers_initialize([ qw( --verbose ) ]);
749  
750 output("ready?");
751 verbose("you bet I am");
752  
753 =head2 def
754  
755 Not exported by default, returns the setting defined.
756  
757 =head2 git_color_check
758  
759 Not exported by default. Returns 1 if git is configured to output
760 using color of 0 if color is not enabled.
761  
762 =head2 colorize( $color => 'message to be output' )
763  
764 Not exported by default. Checks if color is enabled and applies
765 the specified color to the string.
766  
767 =head2 output( \%opts, @messages )
768  
769 Exported. Takes an optional hash reference and a list of
770 messages to be output.
771  
772 =head2 verbose( \%opts, @messages )
773  
774 Exported. Takes an optional hash reference of formatting options. Automatically
775 overrides the B<level> parameter to 1 if it's not set.
776  
777 =head2 debug( \%opts, @messages )
778  
779 Exported. Takes an optional hash reference of formatting options.
780 Does not output anything unless DEBUG is set.
781  
782 =head2 debug_var( \%opts, \%Variable )
783  
784 Exported. Takes an optional hash reference of formatting options.
785 Does not output anything unless DEBUG is set.
786  
787 =head2 override( variable => 1 )
788  
789 Exported. Allows a block of code to override the debug or verbose level. This
790 can be used during development to enable/disable the DEBUG/VERBOSE settings.
791  
792 =head2 confirm("prompt")
793  
794 Exported. Creates a Yes/No Prompt which accepts y/n or yes/no case insensitively
795 but requires one or the other.
796  
797 Returns 1 for 'yes' and 0 for 'no'
798  
799 =head2 text_input("prompt", validate => { "too short" => sub { length $_ > 10 } })
800  
801 Exported. Provides a prompt to the user for input. If validate is passed, it should be a hash reference
802 containing keys of error messages and values which are subroutines to validate the input available as $_.
803 If a validator fails, it's error message will be displayed, and the user will be re-prompted.
804  
805 Valid options are:
806  
807 =over 4
808  
809 =item B<default>
810  
811 Any string which will be used as the default value if the user just presses enter.
812  
813 =item B<validate>
814  
815 A hashref, keys are error messages, values are sub routines that return true when the value meets the criteria.
816  
817 =item B<noecho>
818  
819 Set as a key with any value and the prompt will turn off echoing responses as well as disabling all
820 ReadLine magic. See also B<pwprompt>.
821  
822 =back
823  
824 Returns the text that has passed all validators.
825  
826 =head2 menu("prompt", $ArrayOrHashRef)
827  
828 Exported. Used to create a menu of options from a list. Can be either a hash or array reference
829 as the second argument. In the case of a hash reference, the values will be displayed as options while
830 the selected key is returned. In the case of an array reference, each element in the list is displayed
831 the selected element will be returned.
832  
833 Returns selected element (HashRef -> Key, ArrayRef -> The Element)
834  
835 =head2 pwprompt("Prompt", options )
836  
837 Exported. Synonym for text_input("Password: ", noecho => 1); Also requires the password to be longer than 0 characters.
838  
839 =head2 prompt("Prompt", options )
840  
841 Exported. Wrapper function with rudimentary mimicry of IO::Prompt(er).
842 Uses:
843  
844 # Mapping back to confirm();
845 my $value = prompt "Are you sure?", yn => 1;
846  
847 # Mapping back to text_input();
848 my $value = prompt "Enter something:";
849  
850 # With Validator
851 my $value = prompt "Enter an integer:", validate => { "not a number" => sub { /^\d+$/ } }
852  
853 # Pass to menu();
854 my $value = prompt "Select your favorite animal:", menu => [qw(dog cat pig fish otter)];
855  
856 # If you request a password, autodisable echo:
857 my $passwd = prompt "Password: "; # sets noecho => 1, disables ReadLine history.
858  
859 See also: B<text_input>
860  
861 =head1 EXPORT
862  
863 This module uses L<Sub::Exporter> for flexible imports, the defaults provided by
864 :all are as follows.
865  
866 =head2 Exported Functions
867  
868 output ( \%options, @messages )
869 verbose ( \%options, @messages )
870 debug ( \%options, @messages )
871 debug_var ( \$var )
872 override( option => $value )
873  
874 menu ( "Question", \%Options or \@Options )
875 text_input ( "Question", validate => { "error message" => sub { length $_[0] } } )
876 confirm ( "Question" )
877  
878 prompt() Wrapper which mimics IO::Prompt a bit
879 pwprompt() Wrapper to get sensitive data
880  
881 =head2 Import Time Configurations
882  
883 It's possible to change the behavior of the import process.
884  
885 =over 2
886  
887 =item B<copy_argv>
888  
889 Instead of messing with C<@ARGV>, operate on a copy of C<@ARGV>.
890  
891 use CLI::Helpers qw( :output copy_argv );
892  
893 =item B<preprocess_argv>
894  
895 This causes the C<@ARGV> processing to happen during the C<INIT> phase, after
896 import but before runtime. This is usually OK for scripts, but for use in
897 libraries, it may be undesirable.
898  
899 use CLI::Helpers qw( :output preprocess_argv );
900  
901 =item B<delay_argv>
902  
903 This causes the C<@ARGV> processing to happen when the first call to a function
904 needing it run, usually an C<output()> call. This is the default.
905  
906 use CLI::Helpers qw( :output delay_argv );
907  
908 =back
909  
910 =head1 ARGS
911  
912 From CLI::Helpers:
913  
914 --data-file Path to a file to write lines tagged with 'data => 1'
915 --tags A comma separated list of tags to display
916 --color Boolean, enable/disable color, default use git settings
917 --verbose Incremental, increase verbosity (Alias is -v)
918 --debug Show developer output
919 --debug-class Show debug messages originating from a specific package, default: main
920 --quiet Show no output (for cron)
921 --syslog Generate messages to syslog as well
922 --syslog-facility Default "local0"
923 --syslog-tag The program name, default is the script name
924 --syslog-debug Enable debug messages to syslog if in use, default false
925 --nopaste Use App::Nopaste to paste output to configured paste service
926 --nopaste-public Defaults to false, specify to use public paste services
927 --nopaste-service Comma-separated App::Nopaste service, defaults to Shadowcat
928  
929 =head1 NOPASTE
930  
931 This is optional and will only work if you have L<App::Nopaste> installed. If
932 you just specify C<--nopaste>, any output that would be displayed to the screen
933 is submitted to the L<App::Nopaste::Service::Shadowcat> paste bin. This
934 paste service is pretty simple, but works reliably.
935  
936 During the C<END> block, the output is submitted and the URL of the paste is
937 returned to the user.
938  
939 =head1 OUTPUT OPTIONS
940  
941 Every output function takes an optional HASH reference containing options for
942 that output. The hash may contain the following options:
943  
944 =over 4
945  
946 =item B<tag>
947  
948 Add a keyword to tag output with. The user may then specify C<--tags
949 keyword1,keyword2> to only view output at the appropriate level. This option
950 will affect C<data-file> and C<syslog> output. The output filter requires both
951 the presence of the C<tag> in the output options B<and> the user to specify
952 C<--tags> on the command line.
953  
954 Consider a script, C<status.pl>:
955  
956 output("System Status: Normal")
957 output({tag=>'foo'}, "Component Foo: OK");
958 output({tag=>'bar'}, "Component Bar: OK");
959  
960 If an operator runs:
961  
962 $ status.pl
963 System Status: Normal
964 Component Foo: OK
965 Component Bar: OK
966  
967 $ status.pl --tags bar
968 System Status: Normal
969 Component Bar: OK
970  
971 $ status.pl --tags foo
972 System Status: Normal
973 Component Foo: OK
974  
975 This could be helpful for selecting one or more pertinent tags to display.
976  
977 =item B<sticky>
978  
979 Any lines tagged with 'sticky' will be replayed at the end program's end. This
980 is to allow a developer to ensure message are seen at the termination of the program.
981  
982 =item B<color>
983  
984 String. Using Term::ANSIColor for output, use the color designated, i.e.:
985  
986 red,blue,green,yellow,cyan,magenta,white,black, etc..
987  
988 =item B<level>
989  
990 Integer. For verbose output, this is basically the number of -v's necessary to see
991 this output.
992  
993 =item B<syslog_level>
994  
995 String. Can be any valid syslog_level as a string: debug, info, notice, warning, err, crit,
996 alert, emerg.
997  
998 =item B<no_syslog>
999  
1000 Bool. Even if the user specifies --syslog, these lines will not go to the syslog destination.
1001 alert, emerg.
1002  
1003 =item B<IMPORTANT>
1004  
1005 Bool. Even if --quiet is specified, output this message. Use sparingly, and yes,
1006 it is case sensitive. You need to yell at it for it to yell at your users.
1007  
1008 =item B<stderr>
1009  
1010 Bool. Use STDERR for this message instead of STDOUT. The advantage to using this is the
1011 "quiet" option will silence these messages as well.
1012  
1013 =item B<indent>
1014  
1015 Integer. This will indent by 2 times the specified integer the next string. Useful
1016 for creating nested output in a script.
1017  
1018 =item B<clear>
1019  
1020 Integer. The number of newlines before this output.
1021  
1022 =item B<kv>
1023  
1024 Bool. The array of messages is actually a key/value pair, this implements special coloring and
1025 expects the number of messages to be even.
1026  
1027 output(qw(a 1 b 2));
1028 # a
1029 # 1
1030 # b
1031 # 2
1032  
1033 Using kv, the output will look like this:
1034  
1035 output({kv=>1}, qw(a 1 b 2));
1036 # a: 1
1037 # b: 2
1038 #
1039  
1040 =item B<data>
1041  
1042 Bool. Lines tagged with "data => 1" will be output to the data-file if a user specifies it. This allows
1043 you to provide header/footers and inline context for the main CLI, but output just the data to a file for
1044 piping elsewhere.
1045  
1046 =back
1047  
1048 =head1 AUTHOR
1049  
1050 Brad Lhotsky <brad@divisionbyzero.net>
1051  
1052 =head1 COPYRIGHT AND LICENSE
1053  
1054 This software is Copyright (c) 2022 by Brad Lhotsky.
1055  
1056 This is free software, licensed under:
1057  
1058 The (three-clause) BSD License
1059  
1060 =head1 CONTRIBUTORS
1061  
1062 =for stopwords Kang-min Liu Kevin M. Goess Mohammad S Anwar
1063  
1064 =over 4
1065  
1066 =item *
1067  
1068 Kang-min Liu <gugod@gugod.org>
1069  
1070 =item *
1071  
1072 Kevin M. Goess <kgoess@craigslist.org>
1073  
1074 =item *
1075  
1076 Mohammad S Anwar <mohammad.anwar@yahoo.com>
1077  
1078 =back
1079  
1080 =for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
1081  
1082 =head1 SUPPORT
1083  
1084 =head2 Websites
1085  
1086 The following websites have more information about this module, and may be of help to you. As always,
1087 in addition to those websites please use your favorite search engine to discover more resources.
1088  
1089 =over 4
1090  
1091 =item *
1092  
1093 MetaCPAN
1094  
1095 A modern, open-source CPAN search engine, useful to view POD in HTML format.
1096  
1097 L<https://metacpan.org/release/CLI-Helpers>
1098  
1099 =item *
1100  
1101 RT: CPAN's Bug Tracker
1102  
1103 The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
1104  
1105 L<https://rt.cpan.org/Public/Dist/Display.html?Name=CLI-Helpers>
1106  
1107 =back
1108  
1109 =head2 Source Code
1110  
1111 This module's source code is available by visiting:
1112 L<https://github.com/reyjrar/CLI-Helpers>
1113  
1114 =cut
↑ Summary