blib/lib/IO/Prompt.pm

filter: Statementstmt 100% 20 / 20 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 100% 27 / 27 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Build ↑ Summary
1 package IO::Prompt;
2  
3 our $VERSION = '0.997003';
4  
5 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 2 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶no warnings 'utf8';
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 our @EXPORT = qw( prompt );
12 our @EXPORT_OK = qw( hand_print get_input );
13  
14 2 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use Term::ReadKey;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 ▶use POSIX qw( isprint );
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 my $clearfirst;
19 my %input;
20  
21 sub _clear {
22 return unless $_[0];
23 open my $OUT, ">/dev/tty" or croak "Cannot write to terminal: $!";
24 print {$OUT} "\n" x 60;
25 $clearfirst = 0;
26 }
27  
28 our %flags_arg = (
29 p => 'prompt',
30 s => 'speed',
31 e => 'echo',
32 r => 'require',
33 d => 'default',
34 u => 'until',
35 w => 'while',
36 nl => 'newline',
37 m => 'menu',
38 );
39  
40 our %flags_alias = (
41 '-okayif' => '-while', '-okay_if' => '-while',
42 '-failif' => '-until', '-fail_if' => '-until',
43 );
44  
45 our %flags_noarg = (
46 y => 'yes',
47 n => 'no',
48 i => 'integer',
49 num => 'number',
50 raw => 'raw_input',
51 1 => 'onechar',
52 c => 'clear',
53 f => 'clearfirst',
54 a => 'argv',
55 l => 'line',
56 t => 'tty',
57 x => 'escape',
58 );
59  
60 my $RECORD; # store filehandle for __PROMPT__ file supporting -record flag
61  
62 $flags_arg{$_} = $_ for values %flags_arg;
63 $flags_noarg{$_} = $_ for values %flags_noarg;
64  
65 my $flag_with_arg = join '|', reverse sort keys %flags_arg;
66 my $flag_no_arg = join '|', reverse sort keys %flags_noarg;
67  
68 my %yespat = (
69 'y' => qr/^\s*[yY]/,
70 'Y' => qr/^\s*Y/,
71 );
72  
73 my %nopat = (
74 'n' => qr/^\s*[nN]/,
75 'N' => qr/^\s*N/,
76 );
77  
78 my %num_pat = (
79 integer => qr{[+-]? \d+ (?:[Ee]+?\d+ )?}x,
80 number => qr{[+-]? (?:\d+[.]?\d* | [.]\d+) (?:[Ee][+-]?\d+)? }x,
81 );
82  
83 sub _get_prompt (\%@) {
84 my ($flags, @data) = @_;
85 my ($OUT);
86 @data = map { $flags_alias{$_} || defined($_) ? $_ : "" } @data;
87 for (my $i = 0 ; $i < @data ; $i++) {
88 local *_ = \$data[$i];
89 if (ref eq 'HASH') {
90 splice @data, $i + 1, 0, %$_;
91 }
92 elsif (ref eq 'GLOB' or UNIVERSAL::isa($_, 'IO::Handle')) {
93 croak "Can't write prompt to read-only $_" unless -w;
94 $OUT = $_;
95 }
96 elsif (/^-/) { # a flag
97 s/_//g;
98 if (s/^-(f|clearfirst)/-/) {
99 $clearfirst = 1 unless defined $clearfirst;
100 }
101 elsif (s/^-(yes|y)/-/i) {
102 $flags->{-yesno}{yes} = $yespat{ substr $1, 0, 1 };
103 $flags->{-yesno}{yesprompt} = substr $1, 0, 1;
104 }
105 elsif (s/^-(?:nl|newline)/-/i) {
106 $flags->{-nlstr} = $data[ $i + 1 ];
107 undef $data[ $i++ ];
108 }
109 elsif (s/^-escape|-x/-/i) {
110 $flags->{-escape} = 1;
111 }
112 elsif (s/^-raw_?(?:input)?/-/i) {
113 $flags->{-raw_input} = 1;
114 }
115 elsif (s/^-number|-num/-/i) {
116 $flags->{-number} = 'number';
117 }
118 elsif (s/^-integer|-i/-/i) {
119 $flags->{-number} = 'integer';
120 }
121 elsif (s/^-(no|n)/-/i) {
122 $flags->{-yesno}{no} = $nopat{ substr $1, 0, 1 };
123 $flags->{-yesno}{noprompt} = substr $1, 0, 1;
124 }
125 elsif (m/^-($flag_with_arg)/) {
126 croak "Missing argument for $_ option" if @data < $i+2
127 || !defined $data[$i+1];
128 s/^-($flag_with_arg)/-/;
129 $flags->{ -$flags_arg{$1} } = $data[$i+1];
130 undef $data[$i++];
131 }
132 elsif (s/^-($flag_no_arg)/-/) {
133 $flags->{ -$flags_noarg{$1} } = 1;
134 }
135 else { croak "Unknown flag ($_) in prompt" }
136  
137 redo if defined $_ && /^-./;
138 }
139 else { next }
140 undef $data[$i];
141 }
142 $_ =
143 !defined() ? undef
144 : ref eq 'Regexp' ? $_
145 : qr/^\Q$_\E$/
146 for @{$flags}{qw(-while -until -failif -okayif)};
147  
148 for (grep { defined } $flags->{ -require }) {
149 croak "Argument to -require must be hash reference"
150 unless ref eq 'HASH';
151 my %reqs = %$_;
152 $_ = sub {
153 my ($input) = @_;
154 for (keys %reqs) {
155 return $_ unless _smartmatch($input, $reqs{$_});
156 }
157 return;
158 };
159 }
160 my @prompt = grep { defined } @data;
161 if (@prompt && exists $flags->{-default}) {
162 my $prompt = join "", @prompt;
163 $prompt =~ s/(:?\s*)$/ [$flags->{-default}]$1/ if $prompt !~ /\[.*\]/;
164 @prompt = $prompt;
165 }
166 return $OUT, @prompt;
167 }
168  
169 my $prompt_req = "(The value entered is not acceptable) ";
170  
171 sub prompt {
172 my $caller = caller;
173  
174 local $\ = q{}; # Make sure no funny business on print statements
175  
176 my %flags;
177 my ($OUT, @prompt) = _get_prompt(%flags, @_);
178 open $OUT, ">/dev/tty" or croak "Cannot write to terminal: $!" if !$OUT;
179 $OUT->autoflush(1);
180 @prompt = $flags{ -prompt } if !@prompt and $flags{ -prompt };
181 my $IN;
182 if ($flags{-tty} || $flags{-argv}) {
183 open $IN, "</dev/tty" or croak "Cannot read from terminal: $!";
184 }
185 else {
186 use Scalar::Util;
187 no strict 'refs';
188 my $ARGV = $caller . "::ARGV";
189 unless (Scalar::Util::openhandle(*$ARGV)) {
190 $$ARGV = shift(@$ARGV) || '-';
191 open $ARGV or croak "Can't open $$ARGV: $!";
192 }
193 $IN = \*$ARGV;
194 @prompt = () unless -t $IN;
195 }
196 $flags{-speed} = 0.075 unless defined $flags{-speed};
197 use Want qw( want );
198 $flags{-set_underscore} ||= want('BOOL');
199  
200 $clearfirst = 1 if !defined($clearfirst) && $flags{-clearfirst};
201 _clear($flags{ -clear } || $clearfirst);
202 my $input;
203 if (-t $IN and defined $input{$caller}) {
204 $input = _fake_from_DATA($caller, $IN, $OUT, \%flags, @prompt);
205 }
206 elsif ($flags{-argv}) {
207 return if @ARGV;
208 @prompt = "Args for $0: " if -t $IN and !@prompt;
209 print {$OUT} @prompt;
210 @ARGV = map glob, split /\s+/, get_input($IN, $OUT, \%flags, @prompt);
211 return @ARGV;
212 }
213 elsif ($flags{-yesno}) {
214 return _yesno($IN, $OUT, \%flags, @prompt);
215 }
216 elsif ($flags{-number}) {
217 return _number($IN, $OUT, \%flags, @prompt);
218 }
219 elsif ($flags{-menu}) {
220 return _menu($IN, $OUT, \%flags, @prompt);
221 }
222 else {
223 print {$OUT} @prompt;
224 $input = get_input($IN, $OUT, \%flags, @prompt);
225 }
226 return _tidy($input, %flags);
227 }
228  
229 sub _tidy {
230 my ($input, %flags) = @_;
231 my $defined = defined $input;
232 chomp $input if $defined && !$flags{-line};
233 my $success = $defined
234 && (!$flags{ -while } || $input =~ $flags{ -while })
235 && (!$flags{ -until } || $input !~ $flags{ -until });
236 print {$RECORD} $input, "\n" if $success && $RECORD;
237 return "$input" if $flags{-raw_input};
238 return bless {
239 value => $input,
240 success => $success,
241 set_val => $flags{ -set_underscore },
242 },
243 'IO::Prompt::ReturnVal';
244 }
245  
246 sub _success {
247 my ($val, $no_set, $raw) = @_;
248 print {$RECORD} $val, "\n" if $val && $RECORD;
249 return "$val" if $raw;
250 return bless {
251 value => $val,
252 success => 1,
253 set_val => !$no_set,
254 },
255 'IO::Prompt::ReturnVal';
256 }
257  
258 sub _failure {
259 my ($val, $raw) = @_;
260 return "$val" if $raw;
261 return bless {
262 value => $val,
263 success => 0,
264 set_val => 0,
265 },
266 'IO::Prompt::ReturnVal';
267 }
268  
269 sub import {
270 my $class = shift;
271  
272 {
273 no strict 'refs';
274 *{ caller() . "::$_" } = \&{$_} for @EXPORT;
275  
276 foreach my $sym (@_) {
277 grep { $_ eq $sym } @EXPORT_OK or next;
278 *{ caller() . "::$sym" } = \&{$sym};
279 }
280 }
281  
282 @_ = grep /^-/, @_;
283 $input{ caller() } = undef;
284 if ("@_" eq "-clearfirst") {
285 $clearfirst = 1;
286 return;
287 }
288 for my $i (0 .. $#_) {
289 last if $RECORD;
290 if ($_[$i] eq '-record') {
291 splice @_, $i, 1;
292 open $RECORD, '>', '__PROMPT__'
293 or croak "Can't open __PROMPT__ recording file: $!";
294 print {$RECORD} "__DATA__\n__PROMPT__\n";
295 }
296 }
297 prompt @_ if @_;
298 }
299  
300 CHECK {
301 for my $pkg (keys %input) {
302 next if defined $input{$pkg};
303  
304 no strict 'refs';
305 if (my $datahandle = *{"${pkg}::DATA"}{IO}) {
306 local $/;
307 my $data = <$datahandle>;
308 if ($data =~ s/(\A|\n) __PROMPT__ \s*? \n (.*)/$1/xs) {
309 $input{$pkg} = "$2";
310 }
311 else {
312 delete $input{$pkg};
313 }
314 open "${pkg}::DATA", "<", \$data or die "Internal error: $!";
315 }
316 else {
317 delete $input{$pkg};
318 }
319 }
320 }
321  
322 my $baseline = ord 'A';
323  
324 sub _visualize {
325 local ($_) = @_;
326 return isprint($_) ? $_
327 : $_ eq "\n" ? $_
328 : ord($_) == 0 ? ''
329 : ord($_) < $baseline ? '^' . chr($baseline + ord($_) - 1)
330 : '?'
331 }
332  
333 sub hand_print {
334 my $OUT = \*STDOUT;
335 my $echo = undef;
336 my $speed = 0.05;
337 local $| = 1;
338 for (@_) {
339 if (ref eq 'HASH') {
340 $speed = $_->{-speed} if exists $_->{-speed};
341 $OUT = $_->{-to} if exists $_->{-to};
342 $echo = $_->{-echo} if exists $_->{-echo};
343 }
344 elsif (!$speed) {
345 print {$OUT} $_;
346 }
347 else {
348 print {$OUT} $_ and select undef, undef, undef, rand $speed
349 for map { defined $echo ? $echo : _visualize($_) } split "";
350 }
351 }
352 return scalar @_;
353 }
354  
355 sub _fake_from_DATA {
356 my ($caller, $IN, $OUT, $flags, @prompt) = @_;
357 local $SIG{INT} = sub { ReadMode 'restore', $IN; exit };
358 ReadMode 'noecho', $IN;
359 ReadMode 'raw', $IN;
360 print {$OUT} @prompt;
361 my $input = getc $IN;
362 if ($input =~ /\cD|\cZ/) { print {$OUT} _visualize($input),"\n"; return; }
363 if ($input eq "\e") {
364 ReadMode 'restore', $IN;
365 return get_input($IN, $OUT, $flags, @prompt);
366 }
367 $input{$caller} =~ m/\G (?!\cD|\cZ) (.*) (\n?)/xgc;
368 my ($line, $nlstr) = ($1, $2);
369 unless (defined $line) {
370 while ($input ne "\n") { $input = getc $IN }
371 print {$OUT} "\n";
372 return;
373 }
374 delete $input{$caller} if pos $input{$caller} == length $input{$caller};
375 if ($input eq "\n") {
376 hand_print { -to => $OUT, %$flags }, $line;
377 unless (defined <$IN>) { print {$OUT} "\n"; return; }
378 }
379 else {
380 my $i = 0;
381 while (1) {
382 my $done = $i >= length $line;
383 print {$OUT} substr($line, $i++, 1) unless $done;
384 if (getc $IN eq "\n") {
385 last if $done;
386 hand_print { -to => $OUT, %$flags }, substr($line, $i);
387 $i = length $line;
388 }
389 }
390 }
391 ReadMode 'restore', $IN;
392 print {$OUT} "\n";
393 return $line . $nlstr;
394 }
395  
396 sub get_input {
397 my ($IN, $OUT, $flags, @prompt) = @_;
398 my ($onechar, $nlstr, $echo, $require) =
399 @{$flags}{ -onechar, -nlstr, -echo, -'require' };
400 $nlstr = "\n" unless defined $nlstr;
401 if (!-t $IN) {
402 return scalar <$IN> unless $onechar;
403 return getc $IN;
404 }
405 $OUT->autoflush(1);
406 local $SIG{INT} = sub { ReadMode 'restore', $IN; exit };
407 my ($input, $newlines);
408 my %cntl = GetControlChars $IN;
409 my $cntl = join '|', values %cntl;
410 ReadMode 'raw', $IN;
411  
412 INPUT: while (1) {
413 my $next = getc $IN;
414 if ($next eq $cntl{INTERRUPT}) {
415 ReadMode 'restore', $IN;
416 exit;
417 }
418 elsif ($next eq $cntl{ERASE}) {
419 if (defined $input && length $input) {
420 substr($input, -1) = "";
421 print {$OUT} "\b \b";
422 }
423 next;
424 }
425 elsif ($next eq $cntl{EOF}) {
426 ReadMode 'restore', $IN;
427 close $IN;
428 return $input;
429 }
430 elsif ($flags->{-escape} && $next eq "\e") {
431 ReadMode 'restore', $IN;
432 print {$OUT} "<esc>";
433 return "\e";
434 }
435 elsif ($next !~ /$cntl/ && defined $next) {
436 $input .= $next;
437 if ($next eq "\n") {
438 if ($input eq "\n" && exists $flags->{-default}) {
439 print {$OUT} (
440 defined $echo
441 && $flags->{-menu} ? $echo
442 : defined $echo ? $echo x length($flags->{-default})
443 : '['.$flags->{-default}.']'
444 );
445 print {$OUT} $nlstr;
446 ReadMode 'restore', $IN;
447 return $onechar ? substr($_, 0, 1) : $_
448 for $flags->{-default};
449 }
450 $newlines .= $nlstr;
451 }
452 else {
453 print {$OUT}(defined $echo ? $echo : $next);
454 }
455 }
456 else {
457 $input .= $next;
458 }
459 if ($onechar or !defined $next or $input =~ m{\Q$/\E$}) {
460 chomp $input unless $flags->{-line};
461 if ($require and my $mesg = $require->($input)) {
462 print {$OUT} "\r", " " x 79, "\r", sprintf($mesg, @prompt);
463 undef $input;
464 undef $newlines;
465 }
466 else {
467 ReadMode 'restore', $IN;
468 print {$OUT} $newlines if defined $newlines;
469 return $onechar ? substr($input, 0, 1) : $input;
470 }
471 }
472 }
473 }
474  
475 sub _yesno {
476 my ($IN, $OUT, $flags, @prompt) = @_;
477 my ($yes, $no, $yesprompt, $noprompt) =
478 @{ $flags->{ -yesno } }{qw(yes no yesprompt noprompt)};
479 $yes = qr/^([^Nn])/ unless defined $yes;
480 $no = qr/^([^Yy])/ unless defined $no;
481 my $prompt2 =
482 $yesprompt && $noprompt ? "'$yesprompt' or '$noprompt'"
483 : $yesprompt ? "'$yesprompt' for yes"
484 : "'$noprompt' for no";
485 my $raw = $flags->{-raw_input};
486 print {$OUT} @prompt if -t $IN;
487 while (1) {
488 my $response =
489 get_input($IN, $OUT, { %$flags, -nlstr => "" }, @prompt);
490 chomp $response unless $flags->{-line};
491 print {$OUT} "\n" and return _success($response, 'no_set', $raw)
492 if defined $response and $response =~ /$yes/;
493 print {$OUT} "\n" and return _failure($response, $raw)
494 if !defined $response or $response =~ /$no/;
495 print {$OUT} "\r", " " x 79, "\r", @prompt,
496 "(Please answer $prompt2) "
497 if -t $IN;
498 }
499 }
500  
501 sub _number {
502 my ($IN, $OUT, $flags, @prompt) = @_;
503 my $numtype = $flags->{ -number };
504 my $prompt_num = "(Please enter a valid $numtype) ";
505 my $match = $num_pat{$numtype};
506 my $require = $flags->{ -require };
507 print {$OUT} @prompt if -t $IN;
508 while (1) {
509 my $response =
510 get_input($IN, $OUT, { %$flags, -nlstr => "", -require => undef },
511 @prompt);
512 chomp $response if defined $response && !$flags->{-line};
513 if (-t $IN and defined $response) {
514 if ($response !~ /\A \s* $match \s* \Z/x) {
515 print {$OUT} "\r", " " x 79, "\r", @prompt, $prompt_num;
516 next;
517 }
518 elsif ($require and my $mesg = $require->($response)) {
519 print {$OUT} "\r", " " x 79, "\r", sprintf($mesg, @prompt);
520 next;
521 }
522 }
523 print {$OUT} "\n" and return _tidy($response);
524 }
525 }
526  
527 sub _self { $_[0] }
528  
529 sub _menu {
530 my ($IN, $OUT, $flags, @prompt) = @_;
531 my $datatype = ref $flags->{ -menu };
532 my @data = $datatype eq 'ARRAY' ? @{ $flags->{ -menu } }
533 : $datatype eq 'HASH' ? sort keys %{ $flags->{ -menu } }
534 : croak "Argument to -menu must be hash or array reference";
535  
536 my $val_for = $datatype eq 'ARRAY'
537 ? \&_self
538 : sub { $flags->{ -menu }{$_[0]} };
539  
540 my $count = @data;
541  
542 croak "Too many -menu items" if $count > 26;
543 croak "Too few -menu items" if $count < 1;
544  
545 my $max_char = chr(ord('a') + $count - 1);
546 my $menu = q{};
547  
548 my $default_key;
549 my $next = 'a';
550 for (@data) {
551 my $item = $_;
552 if (defined $flags->{ -default } && !defined $default_key && $item eq $flags->{ -default }) {
553 $default_key = $next;
554 }
555 $item =~ s/\A/qq{ }.$next++.q{. }/xmse;
556 $item =~ s/\n?\z/\n/xms;
557 $item =~ s/(?!\Z)\n/\n /gxms;
558 $menu .= $item;
559 }
560  
561 push @prompt, "\n$menu\n> ";
562  
563 my $prompt_range = "(Please enter a-$max_char) > ";
564 my $require = $flags->{ -require };
565 print {$OUT} @prompt if -t $IN;
566 while (1) {
567 my $response =
568 get_input($IN, $OUT, { %$flags, -escape => 1, -nlstr => "", -require => undef },
569 @prompt);
570 chomp $response;
571 if (-t $IN and defined $response) {
572 if (length $response == 1 && $response eq "\e") {
573 return $response;
574 }
575 elsif (length $response > 1 || ($response lt 'a' || $response gt $max_char) ) {
576 if ($response ne $flags->{-default}) {
577 print {$OUT} "\r", " " x 79, "\r", $prompt_range;
578 next;
579 }
580 $response = $default_key;
581 }
582 elsif ($require and my $mesg = $require->($data[ord($response)-ord('a')])) {
583 print {$OUT} "\r", " " x 79, "\r", sprintf($mesg, @prompt);
584 next;
585 }
586 }
587 print {$OUT} "\n";
588 my $selection = $data[ord($response)-ord('a')];
589 $response = defined $response ? $val_for->($selection) : $response;
590 if (defined $response && ref($response) =~ m/\A(?:HASH|ARRAY)\z/xms ) {
591 $response = _menu($IN, $OUT, {%{$flags}, -menu=>$response}, "$selection: ");
592 if (defined $response && $response eq "\e") {
593 print {$OUT} "\n", @prompt if -t $IN;
594 next;
595 }
596 }
597 return _tidy($response);
598 }
599 }
600  
601 sub _smartmatch {
602 my ($str, $matcher) = @_;
603 my $type = ref $matcher;
604 my $res = $type eq 'CODE'
605 ? do { local $_ = $str; $matcher->() }
606 : $type eq 'Regexp' ? ($str =~ $matcher)
607 : $type eq 'ARRAY' ? scalar grep({ _smartmatch($str, $_) } @$matcher)
608 : $type eq 'HASH' ? $matcher->{$str}
609 : $str eq $matcher;
610 return $res;
611 }
612  
613 package IO::Prompt::ReturnVal;
614  
615 use overload
616 q{bool} => sub {
617 $_ = $_[0]{value} if $_[0]{set_val};
618 $_[0]{handled} = 1;
619 $_[0]{success};
620 },
621 q{""} => sub { $_[0]{handled} = 1; "$_[0]{value}"; },
622 q{0+} => sub { $_[0]{handled} = 1; 0 + $_[0]{value}; },
623 fallback => 1,
624 ;
625  
626 sub DESTROY {
627 $_ = $_[0]{value} unless $_[0]{handled};
628 }
629  
630 1; # Magic true value required at end of module
631 __END__
« Build ↑ Summary