blib/lib/Module/TestConfig.pm

filter: Statementstmt 82.3% 173 / 210 Branchbran 63.3% 71 / 112 Conditioncond 37.1% 13 / 35 MC/DCmcdc 19.0% 4 / 21 Subroutinesub 93.9% 31 / 33 Podpod 90.9% 20 / 22 totaltotal 72.0% 312 / 433 CC 73 SCAR 24.8
CC
73
Cov
72%
prompt
44.5
report_pretty
30.0
ask
14.2
CRAP 12.0
↑ Summary blib/lib/Module/TestConfig/Question.pm »
1 # -*- perl -*-
2 #
3 # Module::TestConfig - asks questions and autowrite a module
4 #
5 # $Id: TestConfig.pm,v 1.33 2003/08/29 18:40:16 jkeroes Exp $
6  
7 package Module::TestConfig;
8  
9 7 require 5.008;
10 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶use Fcntl;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 7 ▶use File::Basename qw/dirname/;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 7 ▶use Params::Validate;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 7 ▶use Config::Auto;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 7 ▶use Module::TestConfig::Question;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 # Dynamically loaded modules
19 # Data::Dumper;
20 # Text::FormatTable;
21 # Term::ReadKey;
22 # File::Path
23  
24 7 our $VERSION = '0.05';
25  
26 #------------------------------------------------------------
27 # Methods
28 #------------------------------------------------------------
29  
30 8 ▶sub new {
Subroutine new: called CC=2 SCAR=7.4
Pod documented
31 8 my $proto = shift;
32 8 ▶ my $class = ref $proto || $proto;
Condition33%1/3
ref $proto || $proto
l!l&&r!l&&!r
080
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table33%1/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
33 8 my $self = bless {}, $class;
34 8 return $self->init(
35 verbose => 1,
36 defaults => 'defaults.config',
37 file => 'MyConfig.pm',
38 package => 'MyConfig',
39 order => [ qw/defaults/ ],
40 questions => [ ],
41 _defaults => { },
42 qi => 0,
43 @_,
44 );
45 }
46  
47 8 ▶sub init {
Subroutine init: called CC=3 SCAR=11.0
Pod undocumented
48 8 my ( $self, %args ) = @_;
49  
50 8 ▶ while ( my ( $method, $args ) = each %args ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %args) 62 7 69
51 62 ▶ if ( $self->can( $method ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can($method)) { } 61 1 62
52 61 $self->$method( $args );
53 } else {
54 1 croak "Can't handle arg: '$method'. Aborting";
55 }
56 }
57  
58 7 $self->load_defaults;
59  
60 Params::Validate::validation_options(
61 22 ▶ on_fail => sub { $_[0] =~ s/to.*did //; die "Your answer didn't validate.\n$_[0]" },
Subroutine __ANON__: called CC=1 SCAR=0.0
62 7 );
63  
64 7 return $self;
65 }
66  
67 7 ▶sub load_defaults {
Subroutine load_defaults: called CC=2 SCAR=6.9
Pod documented
68 7 my $self = shift;
69 $self->{_defaults} = Config::Auto::parse( $self->{defaults} )
70 7 ▶ if -r $self->{defaults};
Branch: 1 branch
BranchTrueFalseTotal
if -r $self->{"defaults"} 3 4 7
71 }
72  
73 9 ▶sub verbose {
Subroutine verbose: called CC=2 SCAR=6.9
Pod documented
74 9 my $self = shift;
75 9 ▶ $self->{verbose} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 8 1 9
76 9 $self->{verbose};
77 }
78  
79 0 ▶sub debug {
Subroutine debug: not called CC=2 SCAR=17.9
Pod undocumented
80 0 my $self = shift;
81 0 ▶ $self->{debug} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
82 0 $self->{debug};
83 }
84  
85 11 ▶sub file {
Subroutine file: called CC=2 SCAR=6.9
Pod documented
86 11 my $self = shift;
87 11 ▶ $self->{file} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 9 2 11
88 11 $self->{file};
89 }
90  
91 7 ▶sub package {
Subroutine package: called CC=2 SCAR=7.1
Pod documented
92 7 my $self = shift;
93 7 ▶ $self->{package} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 7 0 7
94 7 $self->{package};
95 }
96  
97 # The filename of the defaults file.
98 9 ▶sub defaults {
Subroutine defaults: called CC=2 SCAR=6.9
Pod documented
99 9 my $self = shift;
100 9 ▶ $self->{defaults} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 8 1 9
101 9 $self->{defaults};
102 }
103  
104 # The defaults hash
105 8 ▶sub _defaults {
Subroutine _defaults: called CC=2 SCAR=7.1
106 8 my $self = shift;
107 8 ▶ $self->{_defaults} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 8 0 8
108 8 $self->{_defaults};
109 }
110  
111 54 ▶sub order {
Subroutine order: called CC=6 SCAR=17.9
Pod documented
112 54 my $self = shift;
113  
114 54 ▶ if ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 10 44 54
115 10 ▶ my @order = ref $_[0] eq "ARRAY" ? @{ $_[0] } : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'ARRAY' ? : 9 1 10
116 10 for my $order ( @order ) {
117 13 ▶ croak "Bad arg given to order(): '$order'"
Branch: 1 branch
BranchTrueFalseTotal
unless grep /^$order$/, ("defaults", "env") 0 13 13
118 unless grep /^$order$/, qw/defaults env/;
119 }
120 10 $self->{order} = [ @order ];
121 }
122  
123 54 ▶ return wantarray ? @{ $self->{order} } : $self->{order};
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 46 8 54
124 }
125  
126 15 ▶sub questions {
Subroutine questions: called CC=6 SCAR=19.2
Pod documented
127 15 my $self = shift;
128  
129 15 ▶ if ( @_ > 1 ) {
Branch: 3 branches
BranchTrueFalseTotal
if (@_ > 1) { } 0 15 15
elsif (@_ == 1 and ref $_[0] eq 'ARRAY') { } 7 8 15
elsif (@_) { } 0 8 8
130 $self->{questions}
131 0 = [ map { Module::TestConfig::Question->new( $_ ) } @_ ];
132 ▶ } elsif ( @_ == 1 && ref $_[0] eq "ARRAY" ) {
Condition66%2/3
@_ == 1 and ref $_[0] eq "ARRAY"
!ll&&!rl&&r
807
MC/DC50%1/2
@_ == 1 and ref $_[0] eq "ARRAY"
@_ == 1 ref $_[0] eq "ARRAY"
Truth table66%2/3
A and B
A= @_ == 1B= ref $_[0] eq "ARRAY"
ABresult
0X0
100
111
133 $self->{questions}
134 7 = [ map { Module::TestConfig::Question->new( $_ ) } @{ $_[0] } ];
135 } elsif ( @_ ) {
136 0 croak "questions() got bad args. Needs a list or arrayref.";
137 }
138  
139 15 ▶ return wantarray ? @{ $self->{questions} } : $self->{questions};
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 13 15
140 }
141  
142 2 ▶sub answers {
Subroutine answers: called CC=3 SCAR=11.0
Pod documented
143 2 my $self = shift;
144 2 ▶ $self->{answers} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 1 2
145 2 ▶ return wantarray ? %{ $self->{answers} } : $self->{answers};
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 1 2
146 }
147  
148 54 ▶sub answer {
Subroutine answer: called CC=1 SCAR=0.0
Pod documented
149 54 my $self = shift;
150 54 return $self->{answers}{+shift};
151 }
152  
153 6 ▶sub ask {
Subroutine ask: called CC=11 SCAR=26.5
Pod documented
154 6 my $self = shift;
155  
156 do {
157  
158 23 my $i = $self->{qi};
159 23 my $q = $self->{questions}[$i];
160 23 my $name = $q->name;
161  
162 # Skip the question?
163 23 ▶ if ( $q->skip ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($q->skip) 0 23 23
164 0 ▶ if ( ref $q->skip eq "CODE" ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $q->skip eq 'CODE') { } 0 0 0
elsif (not ref $q->skip) { } 0 0 0
165 0 ▶ next if $q->skip->( $self );
Branch: 1 branch
BranchTrueFalseTotal
if $q->skip->($self) 0 0 0
166 } elsif ( not ref $q->skip ) {
167 0 ▶ next if $q->skip;
Branch: 1 branch
BranchTrueFalseTotal
if $q->skip 0 0 0
168 } else {
169 0 croak "Don't know how to handle question #$i\'s skip block";
170 }
171 }
172  
173 23 my $attempts = 0;
174  
175 ASK: {
176 23 my @args = ( $name => $self->prompt( $q ) );
177  
178 # Valid answer?
179 43 ▶ if ( $q->validate ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($q->validate) 25 18 43
180 25 ▶ croak "validate must be a hashref. Aborting"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $q->validate eq "HASH" 0 25 25
181 unless ref $q->validate eq "HASH";
182  
183 25 eval { validate( @args, { $name => $q->validate } ) };
184  
185 25 ▶ if ( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 22 3 25
186 22 warn $@;
187  
188 22 ▶ if ( ++$attempts > 10 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$attempts > 10) { } 2 20 22
189 2 warn "Let's just skip that question, shall we?\n\n";
190 2 last ASK;
191 } else {
192 20 warn "Please try again. [Attempt $attempts]\n\n";
193 20 redo ASK;
194 }
195 }
196 }
197  
198 21 $self->{answers}{$name} = $args[-1];
199 }
200  
201 6 ▶ } while ( $self->{qi}++ < scalar @{$self->{questions}} - 1 );
Branch: 1 branch
BranchTrueFalseTotal
$self->{"qi"}++ < scalar @{$self->{"questions"};} - 1 and do { do { my $i = $self->{"qi"}; my $q = $self->{"questions"}[$i]; my $name = $q->name; if ($q->skip) { if (ref $q->skip eq "CODE") { next if $q->skip->($self); } elsif (not ref $q->skip) { next if $q->skip; } else { croak("Don't know how to handle question #${i}'s skip block"); } ; } ; my $attempts = 0; ASK: { my(@args) = ($name, $self->prompt($q)); if ($q->validate) { croak("validate must be a hashref. Aborting") unless ref $q->validate eq "HASH"; eval { do { &validate(\@args, {$name, $q->validate}) } }; if ($@) { warn $@; if (++$attempts > 10) { warn "Let's just skip that question, shall we?\n\n"; last ASK; } else { warn "Please try again. [Attempt $attempts]\n\n"; redo ASK; } ; } ; } ; $self->{"answers"}{$name} = $args[-1]; } } } 17 6 23
202  
203 6 return $self;
204 }
205  
206 43 ▶sub get_default {
Subroutine get_default: called CC=10 SCAR=23.1
Pod documented
207 43 my ($self, $i) = @_;
208  
209 43 ▶ $i ||= $self->{qi};
Condition66%2/3
$i ||= $self->{"qi"}
l!l&&r!l&&!r
02716
MC/DC50%1/2
$i ||= $self->{"qi"}
$i $self->{"qi"}
Truth table66%2/3
A ||= B
A= $iB= $self->{"qi"}
ABresult
1X1
011
000
210 43 my $q = $self->{questions}[$i];
211 43 my $default = $q->default;
212 43 ▶ my $name = $q->name
Branch: 1 branch
BranchTrueFalseTotal
my $name = $q->name or croak("No name defined for question #$i.") 43 0 43
213 or croak "No name defined for question \#$i.";
214  
215 43 for ( $self->order ) {
216 55 ▶ if ( /^env/o ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^env/o) 19 36 55
217 19 ▶ return $ENV{"\U$name"} if defined $ENV{"\U$name"};
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{uc $name} 5 14 19
218 14 ▶ return $ENV{"\L$name"} if defined $ENV{"\L$name"};
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{lc $name} 2 12 14
219 }
220  
221 return $self->{_defaults}{$name}
222 48 ▶ if /^defaults/ && $self->{_defaults}{$name};
Branch: 1 branch
BranchTrueFalseTotal
if /^defaults/ and $self->{"_defaults"}{$name} 9 39 48
Condition100%3/3
/^defaults/ and $self->{"_defaults"}{$name}
!ll&&!rl&&r
12279
MC/DC100%2/2
/^defaults/ and $self->{"_defaults"}{$name}
/^defaults/ $self->{"_defaults"}{$name}
Truth table100%3/3
A and B
A= /^defaults/B= $self->{"_defaults"}{$name}
ABresult
0X0
100
111
223 }
224  
225 # This will be undef unless set via answers()
226 # or new( answers => {...} ).
227 27 ▶ return $self->{answers}{$name} || $default;
Condition66%2/3
$self->{'answers'}{$name} || $default
l!l&&r!l&&!r
2250
MC/DC0%0/2
$self->{'answers'}{$name} || $default
$self->{'answers'}{$name} $default
Truth table66%2/3
A || B
A= $self->{'answers'}{$name}B= $default
ABresult
1X1
011
000
228 }
229  
230 1 ▶sub save {
Subroutine save: called CC=7 SCAR=23.4
Pod documented
231 1 my ($self) = @_;
232  
233 1 ▶ my $text = $self->package_text
Branch: 1 branch
BranchTrueFalseTotal
my $text = $self->package_text or croak("No text to save. Aborting.") 1 0 1
234 or croak "No text to save. Aborting.";
235  
236 1 my $dir = dirname( $self->{file} );
237 1 ▶ unless ( -d $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir) 0 1 1
238 0 require File::Path;
239 File::Path::mkpath( [ $dir ], $self->{verbose})
240 0 ▶ or croak "Can't make path $dir: $!";
Branch: 1 branch
BranchTrueFalseTotal
File::Path::mkpath([$dir], $self->{"verbose"}) or croak("Can't make path ${dir}: $!") 0 0 0
241 }
242  
243 1 ▶ sysopen F, $self->{file}, O_CREAT | O_WRONLY | O_TRUNC, 0600
Branch: 1 branch
BranchTrueFalseTotal
sysopen F, $self->{"file"}, 577, 384 or croak(qq[Can't open '$self->{"file"}' for write: $!]) 1 0 1
244 or croak "Can't open '$self->{file}' for write: $!";
245 1 print F $text;
246 1 ▶ close F or carp ("Can't close '$self->{file}'. $!"), return;
Branch: 1 branch
BranchTrueFalseTotal
close F or carp(qq[Can't close '$self->{"file"}'. $!]), return 1 0 1
247  
248 print "Module::TestConfig saved $self->{file} with these settings:\n"
249 1 ▶ . $self->report if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 1 0 1
250 }
251  
252 # Error in v.04:
253 #
254 # Failed test 'save_defaults()'
255 # at t/40_defaults.t line 40.
256 # found warning: Filehandle STDIN reopened as F only for output at /home/sand/.cpan/build/Module-TestConfig-0.04-pvLCvJ/blib/lib/Module/TestConfig.pm line 263.
257 # found carped warning: Skipping bad key with a separator in it: 'bro:ken' at t/40_defaults.t line 39
258 # expected to find carped warning: /^Skipping bad key/
259 # Looks like you failed 1 test of 28.
260 #
261 # We're going to ignore that STDIN warning here - ignoring it in t/40_defaults.t does nothing.
262  
263 2 ▶sub save_defaults {
Subroutine save_defaults: called CC=6 SCAR=17.9
Pod documented
264 2 my $self = shift;
265 my %args = ( file => $self->{defaults},
266 2 sep => ':',
267 @_,
268 );
269  
270 # doesn't matter if this fails:
271 2 ▶ rename $args{file}, "$args{file}.bak" if -e $args{file};
Branch: 1 branch
BranchTrueFalseTotal
if -e $args{"file"} 1 1 2
272  
273 7 ▶ no warnings "io";
Subroutine BEGIN: called CC=1 SCAR=0.0
274  
275 2 ▶ open F, "> $args{file}"
Branch: 1 branch
BranchTrueFalseTotal
open F, qq[> $args{"file"}] or carp(qq[Unable to write to $args{"file"}: $!]), return 2 0 2
276 or carp ("Unable to write to $args{file}: $!"), return;
277  
278 7 ▶ use warnings "io";
Subroutine BEGIN: called CC=1 SCAR=0.0
279  
280 2 print F "# This defaults file was autogenerated by Module::TestConfig for $self->{package}\n\n";
281  
282 2 ▶ while ( my ($k, $v) = each %{ $self->{answers} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$$self{"answers"};}) 12 2 14
283 12 ▶ carp ("Skipping bad key with a separator in it: '$k'"), next
Branch: 1 branch
BranchTrueFalseTotal
if $k =~ /$args{"sep"}/ 2 10 12
284 if $k =~ /$args{sep}/;
285 10 print F "$k$args{sep}$v\n";
286 }
287  
288 2 ▶ close F or return;
Branch: 1 branch
BranchTrueFalseTotal
close F or return 2 0 2
289  
290 2 return 1;
291 }
292  
293 # Try to report using the best metho
294 6 ▶sub report {
Subroutine report: called CC=2 SCAR=7.0
Pod documented
295 6 my $self = shift;
296  
297 6 eval { require Text::FormatTable };
298  
299 6 ▶ return $@
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 6 0 6
300 ? $self->report_plain
301 : $self->report_pretty
302  
303 }
304  
305 # Report using Test::FormatTable
306 0 ▶sub report_pretty {
Subroutine report_pretty: not called CC=5 SCAR=34.0
Pod documented
307 0 my $self = shift;
308  
309 0 ▶ croak "Can't use report_pretty() unless Text::AutoFormat is loaded."
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::can("Text::FormatTable", "new") 0 0 0
310 unless UNIVERSAL::can('Text::FormatTable', 'new');
311  
312 0 ▶ my $screen_width = eval { require Term::ReadKey; (Term::ReadKey::GetTerminalSize())[0] } || 79;
Condition0%0/2
eval { do { require Term::ReadKey; (Term::ReadKey::GetTerminalSize())[0] } } || 79
l!l
00
MC/DC0%0/1
eval { do { require Term::ReadKey; (Term::ReadKey::GetTerminalSize())[0] } } || 79
eval { do { require Term::ReadKey; (Term::ReadKey::GetTerminalSize())[0] } }
Truth table0%0/2
A
A= eval { do { require Term::ReadKey; (Term::ReadKey::GetTerminalSize())[0] } }
Aresult
11
00
313 0 my $table = Text::FormatTable->new( '| r | l |' );
314  
315 0 $table->rule('=');
316 0 $table->head('Name', 'Value');
317 0 $table->rule('=');
318  
319 0 for my $q ( @{ $self->{questions} } ) {
320 0 ▶ if ( $q->noecho ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($q->noecho) { } 0 0 0
321 0 $table->row( $q->name, '*****' );
322 } else {
323 0 $table->row( $q->name, $self->answer( $q->name ) );
324 }
325 }
326  
327 0 $table->rule('-');
328  
329 0 my $report = $table->render($screen_width);
330 0 $report =~ s/^/\t/mg; # indent
331  
332 0 return $report;
333 }
334  
335 # Report with plain text.
336 6 ▶sub report_plain {
Subroutine report_plain: called CC=3 SCAR=11.2
Pod documented
337 6 my $self = shift;
338  
339 6 my $report = '';
340  
341 6 for my $q ( @{ $self->{questions} } ) {
342 30 ▶ if ( $q->noecho ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($q->noecho) { } 0 30 30
343 0 $report .= $q->name . ": *****\n";
344 } else {
345 30 $report .= $q->name . ": "
346 . $self->answer( $q->name ) . "\n";
347 }
348 }
349  
350 6 $report =~ s/^/\t/mg; # indent
351  
352 6 return $report;
353 }
354  
355 1 ▶sub package_text {
Subroutine package_text: called CC=1 SCAR=0.0
Pod documented
356 1 my $self = shift;
357  
358 1 local $/ = undef;
359 1 local $_ = <DATA>;
360  
361 1 my $pkg = $self->{package};
362  
363 1 require Data::Dumper;
364 1 $Data::Dumper::Terse = 2;
365 1 my $answers = Data::Dumper->Dump( [$self->{answers}] );
366  
367 1 s/%%PACKAGE%%/$pkg/mg;
368 1 s/%%ANSWERS%%/$answers/m;
369  
370 1 return $_;
371 }
372  
373  
374 # Based on ExtUtils::MakeMaker::prompt().
375 43 ▶sub prompt {
Subroutine prompt: called CC=13 SCAR=38.0
Pod documented
376 43 my $self = shift;
377 43 ▶ my $q = shift || $self->{questions}[$self->{qi}];
Condition33%1/3
shift() || $self->{'questions'}[$self->{'qi'}]
l!l&&r!l&&!r
4300
MC/DC0%0/2
shift() || $self->{'questions'}[$self->{'qi'}]
shift() $self->{'questions'}[$self->{'qi'}]
Truth table33%1/3
A || B
A= shift()B= $self->{'questions'}[$self->{'qi'}]
ABresult
1X1
011
000
378  
379 43 local $| = 1;
380  
381 43 ▶ croak "prompt() called incorrectly"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $q->msg and defined $q->name 0 43 43
Condition33%1/3
defined $q->msg and defined $q->name
!ll&&!rl&&r
0043
MC/DC0%0/2
defined $q->msg and defined $q->name
defined $q->msg defined $q->name
Truth table33%1/3
A and B
A= defined $q->msgB= defined $q->name
ABresult
0X0
100
111
382 unless defined $q->msg && defined $q->name;
383  
384 43 my $def = $self->get_default;
385 43 ▶ my $dispdef = defined $def ? " [$def] " : " ";
Branch: 1 branch
BranchTrueFalseTotal
defined $def ? : 43 0 43
386 43 ▶ $def = defined $def ? $def : "";
Branch: 1 branch
BranchTrueFalseTotal
defined $def ? : 43 0 43
387  
388 43 print $q->msg . $dispdef;
389  
390 43 my $ans = '';
391 43 ▶ my $ISA_TTY = -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT)); # Pipe?
Condition11%1/9
-t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT))
!ll&&!rl&&r
4300
-t STDOUT or not -f STDOUT || -c STDOUT
l!l&&r!l&&!r
000
-f STDOUT || -c STDOUT
l!l&&r!l&&!r
000
MC/DC0%0/4
-t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT))
-t STDIN -t STDOUT -f STDOUT -c STDOUT
Truth table20%1/5
A && B or not(C || D)
A= -t STDINB= -t STDOUTC= -f STDOUTD= -c STDOUT
ABCDresult
0XXX0
101X0
10010
11XX1
10001
392  
393 43 ▶ if ( $ISA_TTY ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ISA_TTY) { } 0 43 43
394 0 ▶ if ( $Term::ReadKey::VERSION && $q->noecho ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Term::ReadKey::VERSION and $q->noecho) { } 0 0 0
Condition0%0/3
$Term::ReadKey::VERSION and $q->noecho
!ll&&!rl&&r
000
MC/DC0%0/2
$Term::ReadKey::VERSION and $q->noecho
$Term::ReadKey::VERSION $q->noecho
Truth table0%0/3
A and B
A= $Term::ReadKey::VERSIONB= $q->noecho
ABresult
0X0
100
111
395 0 ReadMode( 'noecho' );
396 0 chomp( $ans = ReadLine(0) );
397 0 ReadMode( 'normal' );
398 0 print "\n";
399 } else {
400 0 chomp( $ans = <STDIN> );
401 }
402 } else {
403 43 print "$def\n";
404 }
405  
406 43 ▶ return $ans ne '' ? $ans : $def;
Branch: 1 branch
BranchTrueFalseTotal
$ans ne '' ? : 0 43 43
407 }
408  
409 # Question index
410 8 ▶sub qi {
Subroutine qi: called CC=2 SCAR=7.1
Pod documented
411 8 my $self = shift;
412 8 ▶ $self->{qi} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 8 0 8
413 8 $self->{qi};
414 }
415  
416 #------------------------------------------------------------
417 # Docs
418 #------------------------------------------------------------
419  
420 =head1 NAME
421  
422 Module::TestConfig - Interactively prompt user to generate a config module
423  
424 =head1 SYNOPSIS
425  
426 use Module::TestConfig;
427  
428 Module::TestConfig->new(
429 verbose => 1,
430 defaults => 'defaults.config',
431 file => 'MyConfig.pm',
432 package => 'MyConfig',
433 order => [ qw/defaults env/ ],
434 questions => [
435 [ 'Would you like tea?' => 'tea', 'y' ],
436 [ 'Crumpets?' => 'crumpets', 'y' ],
437 ]
438 )->ask->save;
439  
440 # and in another module or test file:
441  
442 use MyConfig;
443  
444 my $config = MyConfig->new;
445 print $config->tea eq 'y'
446 ? "We're having tea today; splendid!"
447 : "No tea, I'm afraid. P'raps tomorrow.";
448  
449 print $config->crumpets eq 'y'
450 ? "Crumpets; lovely!"
451 : "Alas, we have no crumpets today";
452  
453  
454 =head1 DESCRIPTION
455  
456 This module prompts a user for info and writes a module for later use.
457 You can use it during the module build process (e.g. perl Makefile.PL)
458 to share info among your test files. You can also use it to install
459 that module into your site_perl.
460  
461 Module::TestConfig writes an object-oriented file. You specify
462 the file's location as well as the package name. When you use()
463 the file, each of the questions' names will become an object method.
464  
465 For example, if you asked the questions:
466  
467 Module::TestConfig->new(
468 file => 't/MyConfig.pm',
469 package => 'MyConfig',
470 questions => [
471 [ 'Can you feel that bump?', 'feel', 'n' ],
472 [ 'Would you like another?', 'another', 'y' ],
473 { msg => 'How many fingers am I holding up?',
474 name => 'fingers',
475 default => 11,
476 },
477 ],
478 )->ask->save;
479  
480 You'd see something like this:
481  
482 Can you feel that bump? [n] y
483 Would you like another? [y] n
484 How many fingers am I holding up? [11]
485 Module::TestConfig saved t/MyConfig.pm with these settings:
486 ===================
487 | Name | Value |
488 ===================
489 | feel | y |
490 | another | n |
491 | fingers | 11 |
492 +---------+-------+
493  
494 ...and the file t/MyConfig.pm was written. To use it, add this to
495 another file:
496  
497 use MyConfig;
498  
499 my $config = MyConfig->new;
500 print $config->fingers; # prints 11
501 print $config->feel; # prints 'y'
502 print $config->another; # prints 'n'
503  
504 =head1 PUBLIC METHODS
505  
506 =over 2
507  
508 =item new()
509  
510 Args and defaults:
511  
512 verbose => 1,
513 defaults => 'defaults.config',
514 file => 'MyConfig.pm',
515 package => 'MyConfig',
516 order => [ 'defaults' ],
517 questions => [ ... ],
518  
519 Returns: a new Module::TestConfig object.
520  
521 =item questions()
522  
523 Set up the questions that we'll ask of the user. This is a list (or
524 array) of questions. Each question can be in one of two forms, the
525 array form or the hash form. See L<Module::TestConfig::Question> for
526 more about the question's arguments.
527  
528 Args:
529 an array of question hashes (or question arrays)
530 a list of question hashes (or question arrays)
531  
532 e.g. (to keep it simple, I'll only give an example of a hash-style
533 question):
534  
535 [
536 { question => "Question to ask:",
537 name => "foo",
538 default => 42,
539 noecho => 0,
540 skip => sub { shift->answer('bar') }, # skip if bar is true
541 validate => { regex => /^\d+$/ }, # answer must be all numbers
542 },
543 ...
544 ]
545  
546 Returns:
547 a list of questions in list context
548 an arrayref of questions in scalar context.
549  
550 Here's an overview of the hash-style arguments to set up a question.
551 See L<Module::TestConfig::Question> for more details.
552  
553 Args:
554  
555 =over 4
556  
557 =item question or msg:
558  
559 A string like "Have you seen my eggplant?" or "Kittens:". They look
560 best when they end with a ':' or a '?'.
561  
562 =item name:
563  
564 A simple mnemonic used for looking up values later. Since it will turn
565 into a method name in the future, it ought to match /\w+/.
566  
567 =item default or def:
568  
569 optional. a default answer.
570  
571 =item noecho:
572  
573 optional. 1 or 0. Do we print the user's answer while they are typing?
574 This is useful when asking for for passwords.
575  
576 =item skip:
577  
578 optional. Accepts either a coderef or a scalar. The Module::TestConfig
579 object will be passed to the coderef as its first and only
580 argument. Use it to look up answer()s. If the coderef returns true or
581 the scalar is true, the current question will be skipped.
582  
583 =item validate:
584  
585 optional. A hashref suitable for Params::Validate::validate_pos().
586 See L<Params::Validate>. The question will loop over and over until
587 the user types in a correct answer - or at least one that validates.
588 After the user tries and fails 10 times, Module::TestConfig will give
589 up and skip the question.
590  
591 e.g.
592  
593 Module::TestConfig->new(
594 questions => [ { question => 'Choose any integer: ',
595 name => 'num',
596 default => 0,
597 validate => { regex => qr/^\d+$/ },
598 },
599 { question => 'Pick an int between 1 and 10: ',
600 name => 'guess',
601 default => 5,
602 validate => {
603 callbacks => {
604 '1 <= guess <= 10',
605 sub { my $n = shift;
606 return unless $n =~ /^\d+$/;
607 return if $n < 1 || $n > 10;
608 return 1;
609 },
610 }
611 }
612 },
613 ]
614 )->ask->save;
615  
616 would behave like this when run:
617  
618 Pick a number, any integer: [0] peach
619 Your answer didn't validate.
620 The 'num' parameter did not pass regex check
621 Please try again. [Attempt 1]
622  
623 Pick a number, any integer: [0] plum
624 Your answer didn't validate.
625 The 'num' parameter did not pass regex check
626 Please try again. [Attempt 2]
627  
628 Pick a number, any integer: [0] 5
629 Pick an integer between 1 and 10: [5] 12
630 Your answer didn't validate.
631 The 'guess' parameter did not pass the '1 <= guess <= 10' callback
632 Please try again. [Attempt 1]
633  
634 Pick an integer between 1 and 10: [5] -1
635 Your answer didn't validate.
636 The 'guess' parameter did not pass the '1 <= guess <= 10' callback
637 Please try again. [Attempt 2]
638  
639 Pick an integer between 1 and 10: [5] 3
640 Module::TestConfig saved MyConfig.pm with these settings:
641 =================
642 | Name | Value |
643 =================
644 | num | 5 |
645 | guess | 3 |
646 +-------+-------+
647  
648 =back
649  
650 =item ask()
651  
652 Asks the user the questions.
653  
654 Returns: a Module::TestConfig object.
655  
656 =item save()
657  
658 Writes our answers to the file. The file created will always be
659 0600 for security reasons. This may change in the future. See
660 L<"SECURITY"> for more info.
661  
662 =item defaults()
663  
664 A file parsed by Config::Auto which may be used as default answers to
665 the questions. See L<"order()">
666  
667 Default: "defaults.config"
668  
669 Args: A filename or path.
670  
671 Returns: A filename or path.
672  
673 =item save_defaults()
674  
675 Writes a new defaults file. The key-value separator should be either
676 ':' or '=' to keep it compatible with L<Config::Auto>. See
677 L<"order()"> for more about defaults.
678  
679 Args and defaults:
680  
681 file => $object->defaults, # 'defaults.config'
682 sep => ':',
683  
684 Returns: 1 on success, undef on failure. Any error message can be
685 found in $!.
686  
687 =item file()
688  
689 The filename that gets written during save().
690  
691 Default: "MyConfig.pm"
692  
693 Args: a filepath that should probably end in ".pm". e.g. "t/MyConfig.pm"
694  
695 Returns: the filename or path.
696  
697 =item package()
698  
699 The file's package name written during save().
700  
701 Default: "MyConfig"
702  
703 Args: a package namespace. e.g. "Foo::Bar::Baz"
704  
705 Returns: the set package.
706  
707 =item order()
708  
709 Default: [ 'defaults' ]
710  
711 Args: [ qw/defaults env/ ]
712 [ qw/env defaults/ ]
713 [ qw/defaults/ ]
714 [ qw/env/ ]
715 [ ] # Don't preload defaults from file or env
716  
717 Where do we look up defaults for the questions? They can come from
718 either a file, the environment or perhaps come combination of both.
719  
720 =over 4
721  
722 =item defaults:
723  
724 a file read by Config::Auto that must parse to a hash of question
725 names and values.
726  
727 =item env:
728  
729 environment variables in either upper or lowercase.
730  
731 =back
732  
733 The following will also be checked, in order:
734  
735 =over 4
736  
737 =item answers:
738  
739 Any answers already hard-set via answers().
740  
741 =item a question's default:
742  
743 A default supplied with the question.
744  
745 =back
746  
747 There's a security risk accepting defaults from the environment or
748 from a file. See L<"SECURITY">.
749  
750 =item answer()
751  
752 Get the current value of a question. Useful when paired with a skip
753 or validate.
754  
755 Args: a question's name.
756  
757 Returns: The current value or undef.
758  
759 =item verbose()
760  
761 Should the module be chatty while running? Should it print a report at
762 the end?
763  
764 Default: 1
765  
766 Args: 1 or 0
767  
768 Returns: current value
769  
770 =back
771  
772 =head1 PROTECTED METHODS
773  
774 These are documented primarily for subclassing.
775  
776 =over 2
777  
778 =item answers()
779  
780 A user's questions get stored here. If you preset any answers before
781 calling ask(), they may be used as defaults. See L<"order()"> for
782 those rules.
783  
784 Args: a hash of question names and answers
785  
786 Returns: A hash in list context, a hashref in scalar context.
787  
788 =item prompt()
789  
790 Ask the user a question. It's your job to store the answer in
791 the answers().
792  
793 Args: $question, $default_answer, \%options
794  
795 Returns: the user's answer, a suitable default or ''.
796  
797 =item get_default()
798  
799 Get a question's default answer from env, file, answer() or the
800 question. It's printed with a prompt()ed question.
801  
802 =item load_defaults()
803  
804 Uses Config::Auto to parse the file specified by defaults(). Defaults
805 are stored in $obj-E<gt>{_defaults}.
806  
807 =item package_text()
808  
809 Returns the new file's text. This should take package() and
810 answers() into account.
811  
812 =item qi()
813  
814 The current question index.
815  
816 Args: A number
817  
818 Returns: The current number
819  
820 =item report()
821  
822 Returns a report of question names and values. Will be printed if the
823 object is in verbose mode. This calls report_pretty() or
824 report_plain() depending on whether Text::AutoFormat is
825 available. Won't print any passwords (questions called with C<noecho
826 =E<gt> 1> ) in plaintext.
827  
828 =item report_pretty()
829  
830 Prints the report like this:
831  
832 ==================
833 | Name | Value |
834 ==================
835 | one | 1 |
836 | two | 2 |
837 | three | 3 |
838 | fruit | kiwi |
839 | meat | pork |
840 | passwd | ***** |
841 +--------+-------+
842  
843 =item report_plain()
844  
845 Prints the report like this:
846  
847 one: 1
848 two: 2
849 three: 3
850 fruit: kiwi
851 meat: pork
852 passwd: *****
853  
854 =back
855  
856 =head1 SECURITY
857  
858 The resultant file (MyConfig.pm by default) will be chmod'd to 0600
859 but it will remain on the system.
860  
861 The default action is to load a file named 'defaults.config' and use
862 that for, well, defaults. If someone managed to put their own
863 defaults.config into your working directory, they might be able to
864 sneak a bad default past an unwitting user.
865  
866 Using the environment as input may be a security risk - or a potential
867 bug - especially if your names mimic existing environment variables.
868  
869 =head1 AUTHOR
870  
871 Joshua Keroes E<lt>jkeroes@eli.netE<gt>
872  
873 =head1 COPYRIGHT AND LICENSE
874  
875 Copyright 2003 by Joshua Keroes E<lt>jkeroes@eli.netE<gt>
876  
877 This library is free software; you can redistribute it and/or modify
878 it under the same terms as Perl itself.
879  
880 =head1 SEE ALSO
881  
882 L<Module::TestConfig::Question>
883 L<ExtUtils::MakeMaker>
884 L<Module::Build>
885  
886 =cut
887  
888 # Template for module generation follows:
889  
890 __DATA__
↑ Summary blib/lib/Module/TestConfig/Question.pm »