File Coverage

blib/lib/Getopt/Auto.pm
Criterion Covered Total %
statement 392 433 90.5
branch 131 166 78.9
condition 34 48 70.8
subroutine 48 50 96.0
pod 0 2 0.0
total 605 699 86.5


line stmt bran cond sub pod time code
1             #! /usr/bin/perl
2              
3             #===============================================================================
4             #
5             # FILE: Auto.pm
6             #
7             # USAGE: use Getopt::Auto
8             #
9             # DESCRIPTION: Processes the command line when your Perl script is executed,
10             # looking for the options you define in your POD.
11             #
12             # OPTIONS: --- None
13             # REQUIREMENTS: --- See Build.PL
14             # BUGS: --- Hah!
15             # AUTHOR: Geoffrey Leach (), geoff@hughes.net
16             # VERSION: 2.0
17             # REVISION: ---
18             #===============================================================================
19              
20             # Copyright (C) 2003-2009, Simon Cozens
21             # Copyright (C) 2010-2011, Geoffrey Leach
22              
23             package Getopt::Auto;
24              
25 27     27   4194398 use 5.006;
  27         109  
  27         1248  
26 27     27   178 use strict;
  27         56  
  27         1290  
27 27     27   154 use warnings;
  27         87  
  27         1269  
28              
29 27     27   156 use Carp;
  27         54  
  27         2393  
30              
31 27     27   151 use File::Basename;
  27         60  
  27         3460  
32 27     27   154 use File::Spec;
  27         54  
  27         640  
33 27     27   25860 use Readonly;
  27         122576  
  27         38385  
34              
35             Readonly::Scalar my $SPACE => q{ };
36             Readonly::Scalar my $EMPTY => q{};
37             Readonly::Scalar my $DASH => q{-};
38             Readonly::Scalar my $DDASH => q{--};
39             Readonly::Scalar my $BARE => 0;
40             Readonly::Scalar my $SHORT => 1;
41             Readonly::Scalar my $LONG => 2;
42             Readonly::Array my @TYPES => qw( bare short long );
43             Readonly::Array my @PREFIXES => ( $EMPTY, $DASH, $DDASH );
44              
45             our $VERSION = '2.0';
46              
47             # Perlcritic complains about print to STDOUT. As this is merely for
48             # diagnostic purposes, it seems futile to fix them.
49              
50             ## no critic (RequireCheckedSyscalls)
51              
52             # Initialized by import(), used throughout
53             # Successive calls to import add to it, allowing code to work off
54             # of a particular script or module
55             # Each element is a list of
56             # 0: [package, file], as returned by caller() in import()
57             # 1: The package's options hash (our %options), or main::options
58             # 2: Hash of controls as given in call of Getopt::Auto
59             # nobare, noshort, nolong, trace, init, findsub
60             my @callers;
61              
62             # $caller is the current value of @callers when iterating and is
63             # used by subroutines that do not have a way to get it via a parameter
64             our $caller; ## no critic (ProhibitPackageVars)
65              
66             # User-requested global behaviors
67             # 'test' is intentionally undocumented
68             # It is used to avoid exiting on errors for test purposes
69             my %config = (
70             'trace' => undef,
71             'noshort' => undef,
72             'nolong' => undef,
73             'nobare' => undef,
74             'nohelp' => undef,
75             'nobundle' => undef,
76             'oknotreg' => undef,
77             'okerror' => undef,
78             'findsub' => undef,
79             'init' => undef,
80             'test' => undef,
81             );
82              
83             my $errors = 0;
84              
85             # CHECK is a specially-named block, that is executed by Perl at the _completion_ of compillation.
86             # This is critical, because _parse_pod() depends (indirectly, see Getopt::Auto::PodExtract)
87             # on the existence of subroutines to process the options. It's only executed _once_, however
88             # many times "use Getopt::Auto" has appeared. We've accumulated those packages; now we'll
89             # process them.
90              
91             CHECK {
92              
93             #$DB::single = 2; ## no critic (ProhibitPackageVars)
94 27 100   27   28859 if ($errors) {
95 1 50       6 if ( not defined $config{'test'} ) { exit 1; }
  0         0  
96             }
97 27         238 _parse_pod();
98             }
99              
100             # INIT is a specially-named block that is executed immediatly preceding the
101             # start of the program.
102              
103             INIT {
104              
105             #$DB::single = 2; ## no critic (ProhibitPackageVars)
106 27     27   149 _parse_args();
107 27 100       192 if ($errors) {
108 1 50 33     15 if ( ( not defined $config{'okerror'} )
109             && ( not defined $config{'test'} ) )
110             {
111 0         0 exit 1;
112             }
113             }
114             }
115              
116             # Executed when the Perl program is about to exit
117             # Retained for compabilility with V 1.0; I've no idea what it does
118              
119             END {
120 27 50   27   33634 if ( exists &main::default ) { main::default() }
  0         0  
121             }
122              
123             # Please note: subroutine names that begin with an underscore are internal.
124             # Calling sequence and/or existence is not guaranteed for future versions.
125              
126             # $their_version is managed by Getopt::Auto::PodExtract::preprocess_line()
127             # _set_their_version() assigns and _get_their_version() reports.
128             # their_version is the value of $VERSION in the source POD.
129              
130             my $their_version;
131              
132             sub _set_their_version {
133 27     27   58 $their_version = shift;
134 27         56 return;
135             }
136              
137             sub _get_their_version {
138 3025     3025   28457 return $their_version;
139             }
140              
141             # Carries the content of Getopt::Auto(...)
142             our @spec; ## no critic (ProhibitPackageVars)
143             Readonly::Scalar my $SPEC_NAME => 0;
144             Readonly::Scalar my $SPEC_SHORT => 1;
145             Readonly::Scalar my $SPEC_LONG => 2;
146             Readonly::Scalar my $SPEC_CODE => 3;
147             Readonly::Scalar my $SPEC_SIZE => 4;
148              
149             sub _get_spec_ref {
150 7     7   291 return \@spec;
151             }
152              
153             # Allows user to say what style to prefer
154             # Values are 'short', 'long', 'bare', default 'long' or 'undef' meaning use the POD;
155             my $help_p = $LONG;
156              
157             # %options contains the option registration data extracted from the POD
158             # (or from the use Getopt::Auto statement). It's loaded by _parse_pod()
159             # and used by _parse_args() when an option is discovered on the run-time command.
160              
161             our %options; ## no critic (ProhibitPackageVars)
162              
163             # This sub is intended for testing only. Absence of leading '_' is only to
164             # satisfy perlcritic.
165             sub test_option {
166 17     17 0 17702 my $query = shift;
167 17   100     138 return exists $options{$query} && !_is_restricted($query);
168             }
169              
170             sub _get_options_ref {
171 7     7   43 return \%options;
172             }
173              
174             sub _trace {
175 943 50   943   4003 if ( not defined $config{'trace'} ) {
176 943         3806 return;
177             }
178 0         0 my $arg = shift;
179 0         0 chomp $arg;
180 0         0 print "Getopt::Auto trace: $arg\n";
181 0         0 return;
182             }
183              
184             sub _trace_spec {
185 89 50   89   307 if ( not defined $config{'trace'} ) {
186 89         202 return;
187             }
188 0         0 my $spec = shift;
189 0         0 print "Getopt::Auto trace: Spec for $spec->[$SPEC_NAME]: ";
190 0 0       0 print length $spec->[$SPEC_SHORT]
191             ? "$spec->[$SPEC_SHORT], "
192             : "no short help, ";
193 0 0       0 print defined $spec->[$SPEC_LONG]
194             ? "$spec->[$SPEC_LONG], "
195             : "no long help, ";
196 0 0       0 print defined $spec->[$SPEC_CODE]
197             ? "$spec->[$SPEC_CODE]"
198             : "no code";
199 0         0 print "\n";
200 0         0 return;
201             }
202              
203             sub _trace_argv {
204 228 50   228   905 if ( not defined $config{'trace'} ) {
205 228         344 return;
206             }
207 0         0 _trace( 'Getopt::Auto trace: ARGV now: (' . join( ', ', @ARGV ) . ')' );
208 0         0 return;
209             }
210              
211             sub get_errors {
212 0     0 0 0 return $errors;
213             }
214              
215             sub _error {
216 22     22   36 my $msg = shift;
217 22         34 print {*STDERR} 'Getopt::Auto: ', $msg, "\n";
  22         1497  
218 22         52 $errors++;
219 22         43 return;
220             }
221              
222             # Modifies $name to make it an acceptable subrotine name.
223              
224             sub _clean_func {
225 91     91   135 my $func = shift;
226 91         293 $func =~ s{\A-+}{}smx;
227 91         156 $func =~ s{-}{_}smgx;
228 91         226 return $func;
229             }
230              
231             # Checks $pkg to see if there's a subroutine $name.
232             # $name will be an option, that is for --foo we look to
233             # see if there's a sub foo() Return it if so.
234              
235             sub _check_func {
236 91     91   150 my ( $name, $pkg ) = @_;
237 91 50       302 if ( not defined $caller ) {
238 0         0 return;
239             }
240 91 100       201 if ( not defined $pkg ) {
241 83         177 $pkg = qq{$caller->[0][0]::};
242             }
243              
244 91         181 my $func = _clean_func($name);
245 91 100       372 if ( exists &{"$pkg$func"} ) {
  91         336  
246 64         208 _trace("For $name code is $func()");
247 64         212 _trace("$pkg$func exists");
248 27     27   249 no strict 'refs'; ## no critic (ProhibitNoStrict)
  27         69  
  27         50364  
249 64         97 return *{"$pkg$func"}{'CODE'};
  64         223  
250             }
251             else {
252 27         87 _trace("There is no $pkg$func");
253 27         55 return;
254             }
255 0         0 return;
256             }
257              
258             # Look in all packages for a sub $name. If so, return it
259             # and store it in %options for future use. Note that
260             # at the point where this sub is called, we've determined
261             # that the option is not 'registered' and we wish to avoid
262             # registering the option by accident
263             # An nregistered option is something like --foo, where --foo
264             # did not appear in a =head line in the POD.
265              
266             sub _check_all_sub {
267 7     7   9 my $name = shift;
268 7         43 _trace("Checking for sub $name");
269              
270 7 50 33     26 if ( ( exists $options{$name} )
271             and ( exists $options{$name}{'code'} ) )
272             {
273 0         0 return $options{$name}{'code'};
274             }
275              
276             # Check in all packages
277 7         14 foreach my $caller_local (@callers) {
278 8         33 my $sub = _check_func( $name, qq{$caller_local->[0][0]::} );
279 8 100       28 if ( defined $sub ) {
280 5         17 $options{$name}{'code'} = $sub;
281 5         13 return $sub;
282             }
283             }
284 2         6 return;
285             }
286              
287             sub _is_restricted {
288 110     110   157 my $arg = shift;
289 110         231 my $arg_type = _option_type($arg);
290 110 100 100     1386 if (( ( $arg_type == $BARE ) && ( defined $config{'nobare'} ) )
      100        
      66        
      100        
      66        
291             || ( ( $arg_type == $SHORT )
292             && ( defined $config{'noshort'} ) )
293             || ( ( $arg_type == $LONG )
294             && ( defined $config{'nolong'} ) )
295             )
296             {
297 11         46 return 1;
298             }
299 99         615 return 0;
300             }
301              
302             # The specs parameter is assumed to be a ref to a 4-element array
303             # The elementts are options found either in the POD or the use Getopt::Auto
304              
305             sub _load_options {
306 29     29   62 my ( $specs, $caller_local ) = @_;
307 29         47 foreach my $spec ( @{$specs} ) {
  29         104  
308 89         144 my $name = $spec->[$SPEC_NAME];
309              
310 89         247 $options{$name}{'shorthelp'} = $spec->[$SPEC_SHORT];
311 89         177 $options{$name}{'longhelp'} = $spec->[$SPEC_LONG];
312 89         1052 $options{$name}{'package'} = $caller_local->[0][0];
313 89         206 $options{$name}{'options'} = $caller_local->[1];
314 89         154 $options{$name}{'registered'} = 1;
315              
316             # Avoid creating a code reference that's undefined
317 89 100       223 if ( defined $spec->[$SPEC_CODE] ) {
318 65         133 $options{$name}{'code'} = $spec->[$SPEC_CODE];
319             }
320 89         192 _trace_spec($spec);
321             }
322 29         65 return;
323             }
324              
325             # Check a spec that's been given us by the user.
326              
327             sub _check_spec {
328 5     5   9 my ( $spec_ref, $caller_local ) = @_;
329              
330 5         9 foreach my $spec ( @{$spec_ref} ) {
  5         9  
331              
332             # Each spec has the following members:
333             # The option name: we need to check it for consistency.
334             # The short help phrase, from the POD =item or =head
335             # The long help message, from the POD paragraph that follows
336             # The code (sub reference) to be called for the option
337              
338 8 100       27 if ( not( ref $spec eq 'ARRAY' ) ) {
339 1         5 _error(qq{Option specification $spec must be a reference});
340 1         5 return;
341             }
342              
343 7 100       8 if ( @{$spec} != $SPEC_SIZE ) {
  7         36  
344 1         3 _error(qq{Option list is incompletly specified});
345 1         5 return;
346             }
347              
348 6         13 push @spec, $spec;
349             }
350              
351 3         12 _load_options( \@spec, $caller_local );
352              
353 3         13 return 1;
354             }
355              
356             # Called by Perl at the time of processing 'use' but _not_ of processing 'require'
357              
358             sub import {
359 34     34   12430 my $class = shift; # Getopt::Auto
360             #$DB::single = 2; ## no critic (ProhibitPackageVars)
361              
362 34         2691 my @caller = caller;
363 34         74 pop @caller;
364              
365 34         105 my $opt = "$caller[0]::options";
366 34 50       347 if ( not defined $opt ) {
367              
368             # Which may not exist either, but that's OK.
369 0         0 $opt = q{main::options};
370             }
371              
372             # So it's easy to turn off the trace from the environment
373 34 50       173 if ( exists $ENV{'GETOPT_AUTO_TRACE'} ) {
374 0 0       0 $config{'trace'} = $ENV{'GETOPT_AUTO_TRACE'} == 1 ? 1 : undef;
375             }
376              
377 34         2736 my $ctls;
378 34         1702 while ( my $arg = shift ) {
379 30 100       1620 if ( ref $arg eq 'HASH' ) {
    100          
380 24         37 foreach my $opt ( keys %{$arg} ) {
  24         119  
381 30 100       1948 if ( exists $config{$opt} ) { $config{$opt} = 1; }
  29         1300  
382             else {
383 1         5 _error(qq{Option '$opt' is unknown});
384             }
385             }
386 24         107 $ctls = $arg;
387             }
388             elsif ( ref $arg eq 'ARRAY' ) {
389 5         9 $ctls = {};
390 5         24 _check_spec( $arg, [ \@caller, $opt, $ctls ] );
391             }
392             else {
393 1         4 _error(
394             qq{Must be use-d with: no args, an HASH ref or an ARRAY ref}
395             );
396 1         20 return;
397             }
398             }
399              
400             #$config{'trace'} = 1; # debugging
401 33         126 push @callers, [ \@caller, $opt, $ctls ];
402 33         132 _trace("Tracing ...");
403 33         1376 _trace("Package: $callers[-1][0][0], File: $callers[-1][0][1]");
404 33         6126 return;
405             }
406              
407             sub _option_type {
408 470     470   561 my $option = shift;
409 470 50       1298 return $BARE if not defined $option;
410 470 100       2769 $option =~ m{\A$DDASH}smx and return $LONG;
411 214 100       1012 $option =~ m{\A$DASH}smx and return $SHORT;
412 73 100       8551 $option =~ m{\A\w}smx and return $BARE;
413 2         6 return $BARE;
414             }
415              
416             # Process the files in the script looking for option registrations
417             # and build the global @spec array
418              
419             sub _parse_pod {
420              
421 27     27   83 foreach my $caller_local (@callers) {
422              
423             # We're doing magic!
424              
425             # Do the parsing. The -want_nonPODs causes Pod::Parser (the base) to
426             # call the preprocess_line() sub with all input, so we can scan for
427             # an assignment to $VERSION. Overhead is negligable.
428              
429             # The $caller global is used indirectly by PodExtract, via _check_func()
430 32         65 $caller = $caller_local;
431              
432 32         1543 my $pod = Getopt::Auto::PodExtract->new( -want_nonPODs => 1 );
433              
434 32         2187 my $filename
435             = File::Spec->rel2abs( $caller_local->[0][1] );
436 32         3163 my ( $name, $path, $suffix )
437             = fileparse( $filename, qw( .t .pm .pl ) );
438 32         96 my @filenames = $filename;
439              
440             # Add a possible POD extra file
441 32         101 push @filenames, "$path$name.pod";
442              
443 32         73 foreach my $file (@filenames) {
444 39         155 _trace("Processing POD in: $file");
445 39 100       1948 if ( not -r $file ) {
446 6         25 _trace("$file not readable");
447 6         20 next;
448             }
449              
450             # Pod::Parser method that does the work,
451             # calling the functions that fill 'funcs'
452 33         9437 $pod->parse_from_file( $file, '/dev/null' );
453 33 100       206 last if defined $pod->{'funcs'};
454 7         52 _trace("No POD in $file");
455             }
456              
457 32 100       125 if ( not defined $pod->{'funcs'} ) {
458              
459             # Strangely, this is OK. _parse_args checks for would-be option subs
460 6         32 _trace( "No POD in " . join $SPACE, @filenames );
461 6         15340 return;
462             }
463              
464             # Now move what the POD processing found into a useful format.
465             # $pod ($self in Getopt::Auto::PodExtract subs) has, if we've found
466             # any =item or =head[2|3|4] lines that parse out as being option
467             # registrations.
468            
469             # This code builds the @spec global array as a stack of spec definitions
470             # which will be used later on in option processing.
471             #
472             # Correction 1.9.0 => 1.9.2 courtesy of Bruce Gray
473 26         56 my @this_spec;
474 26         50 foreach my $n ( sort keys %{ $pod->{'funcs'} } ) {
  26         234  
475 83         151 my $spec = $pod->{'funcs'}{$n};
476              
477 83 100       223 if ( exists $spec->{'longhelp'} ) {
478 34         141 $spec->{'longhelp'} =~ s{\n+\z}{\n}smx;
479             }
480 83         436 push @this_spec,
481             [
482             $n, $spec->{'shorthelp'},
483             $spec->{'longhelp'}, $spec->{'code'}
484             ];
485             }
486              
487 26         112 _load_options( \@this_spec, $caller_local );
488              
489             # Global list '@spec' is assigned here
490 26         510 push @spec, @this_spec;
491             }
492              
493 21         24129 return;
494             }
495              
496             sub _set_option {
497 15     15   33 my ( $arg, $caller_local ) = @_;
498              
499 15         21 my ( $opt, $pkg );
500              
501             # This is sort of backwards.
502             # If the arg is known to be a registered option,
503             # then we don't need the caller.
504             # Otherwise, $caller_local is used to determine options and package.
505              
506 15 50       48 if ( defined $caller_local ) {
507 0         0 $opt = qq{$caller_local->[1]};
508             }
509             else {
510 15         40 $opt = $options{$arg}{'options'};
511             }
512             # At this point $opt is the hash defined by "our %options" (or main::options)
513             # in the _user's_ code. That's a different entity form %options in this code
514             # which saves the registration info we collected by parsing the POD
515              
516             # This is true for our --help and --version
517 15 50       67 if ( not defined $opt ) { return 0; }
  0         0  
518              
519             # Warning -- if opption_type is BARE, this should only be called if the
520             # op -- arg is registered.
521 15         62 _trace("Bumping $opt for $arg");
522 27     27   188 no strict 'refs'; ## no critic (ProhibitNoStrict)
  27         59  
  27         16130  
523             # And here we bump the use count for the option
524 15         16 ${$opt}{$arg}++;
  15         64  
525              
526 15         26 return 1;
527             }
528              
529             sub _split_arg {
530 8     8   17 my ( $arg, $args ) = @_;
531              
532 8 100       34 if ( defined $config{'nobundle'} ) {
533 1         3 $args->{$arg} = 1;
534 1         4 return $arg;
535             }
536              
537             # This applies only to SHORT options
538 7 50       54 if ( _option_type($arg) != $SHORT ) { return $arg; }
  0         0  
539 7 50       18 if ( length $arg == 2 ) { return $arg; }
  0         0  
540              
541             # Builtin help/version meets this criteria
542 7 50 33     33 if ( ( exists $options{$arg} )
543             and ( exists $options{$arg}{'registered'} ) )
544             {
545 0         0 return $arg;
546             }
547              
548 7         26 _trace("Splitting $arg into its components");
549              
550 7         13 my @args;
551 7         36 foreach my $char ( split m{}smx, substr $arg, 1 ) {
552 24         39 $char = "-$char";
553 24         34 push @args, $char;
554 24         51 $args->{$char}++;
555 24         48 $args->{$arg}++;
556             }
557 7         31 return @args;
558             }
559              
560             sub _is_registered {
561 118     118   175 my $arg = shift;
562              
563 118   66     839 return ( ( exists $options{$arg} )
564             and ( exists $options{$arg}{'registered'} ) );
565             }
566              
567             sub _notreg {
568 18     18   30 my $text = shift;
569 18 100       67 if ( defined $config{'oknotreg'} ) { return; }
  4         7  
570 14         62 _error(qq{$text is not a registered option});
571              
572 14 100       84 if ( defined $config{'nohelp'} ) { return; }
  9         22  
573            
574             # Make an attempt to add useful info
575             # If user has not provided help, this will be the builtin version
576 5 100       20 if ( exists $options{'--help'}{'code'} ) {
577 2         6 _do_option_action('--help');
578 2         4 return;
579             }
580              
581             # If user has not provided help, this will be the builtin version
582 3 50       7 if ( exists $options{'-h'}{'code'} ) {
583 0         0 _do_option_action('-h');
584 0         0 return;
585             }
586              
587             # Well get here iff the user has provided non-fatal help
588             # Or, 'test' is configured
589 3         4 return;
590             }
591              
592             sub _do_option_action {
593 76     76   203 my ( $arg, $arg_eq ) = @_;
594              
595 76 100       292 if ( defined $options{$arg} ) {
596              
597             # Registered option
598             # Check for sub to execute
599 74 100       239 if ( exists $options{$arg}{'code'} ) {
600 55         241 _trace("Running code $options{$arg}{'code'}");
601 27     27   482 no strict 'refs'; ## no critic (ProhibitNoStrict)
  27         55  
  27         14451  
602 55         222 $options{$arg}{'code'}->();
603 55         302 return 1;
604             }
605              
606             # No sub, registered option, so assign %options
607             # unless it's an assignment-type option, which must have a sub
608 19 100       60 if ( defined $arg_eq ) { return 0; }
  4         16  
609              
610 15         66 _set_option($arg);
611 15         30 return 1;
612             }
613             }
614              
615             sub _check_help {
616 53     53   133 my @perfs;
617 53         567 foreach my $op ( keys %options ) {
618 247 50       710 if ( exists $options{$op}{'restrict'} ) { next; }
  0         0  
619 247         519 $perfs[ _option_type($op) ]++;
620             }
621              
622 53         134 $help_p = $LONG;
623 53         92 my $max_p = 0;
624 53         173 foreach my $i ( $BARE .. $LONG ) {
625 159 100 66     741 if ( ( defined $perfs[$i] ) && ( $perfs[$i] > $max_p ) ) {
626 63         150 $help_p = $i;
627             }
628             }
629              
630 53         479 my $help = "$PREFIXES[$help_p]help";
631 53         705 my $vers = "$PREFIXES[$help_p]version";
632 53 100       442 if ( not exists $options{$help} ) {
633 27         156 $options{$help}{'code'} = \&_help;
634 27         85 $options{$help}{'registered'} = 1;
635 27         99 $options{$help}{'shorthelp'} = 'This text';
636             }
637 53 100       197 if ( not exists $options{$vers} ) {
638 28         128 $options{$vers}{'code'} = \&_version;
639 28         78 $options{$vers}{'registered'} = 1;
640 28         85 $options{$vers}{'shorthelp'} = 'Prints the version number';
641             }
642              
643 53         128 return;
644             }
645              
646             my @not_option;
647              
648             sub _not_option {
649 38     38   71 my ( $arg, $eq ) = @_;
650              
651             # The param $eq indicates that we're undoing an arg of the
652             # form -foo=22. The 22 is in @ARGV, but there was no sub
653             # to consume it, so we move it off.
654 38 100       152 if ( defined $eq ) { $arg .= qq{=$eq}; shift @ARGV; }
  7         14  
  7         16  
655 38         83 push @not_option, $arg;
656 38         112 return;
657             }
658              
659             sub _parse_args { ## no critic (ProhibitExcessComplexity)
660 53     53   110589 @not_option = ();
661              
662 53         238 _trace_argv();
663              
664             # Check that builtin help is defined according to the option type
665 53         285 _check_help();
666              
667             # Check each script/module for an init sub to execute
668             # If the user has defined one, its in the @callers array at [2].
669 53         125 foreach my $caller_local (@callers) {
670 66         178 my $init_sub = $caller_local->[2]{'init'};
671 66 100       258 if ( defined $init_sub ) {
672 3         25 _trace("Executing code for init_sub");
673 27     27   296 no strict 'refs'; ## no critic (ProhibitNoStrict)
  27         49  
  27         10953  
674 3         16 $init_sub->();
675             }
676             }
677              
678 53         245 while ( my $argv = shift @ARGV ) {
679              
680 106         249 my $op_type = _option_type($argv);
681              
682 106         529 _trace("Considering $argv, option type is $TYPES[$op_type]");
683 106         378 _trace_argv();
684              
685             # Check cease and desist
686 106 100       418 if ( $argv =~ m{\A-{1,2}\z}smx ) {
687 6         25 _trace("Option end $argv, scanning ends");
688              
689             # Marker is not replaced
690 6         20 last;
691             }
692              
693             # Check restricted option
694 100 100       268 if ( _is_restricted($argv) ) {
695 7         31 _trace("Option $argv is restricted, skipping");
696 7         21 _not_option($argv);
697 7         28 next;
698             }
699              
700             # Check --foo=bar syntax use
701 93         127 my $arg_eq;
702 93 100       281 if ( $argv =~ m{=}smx ) {
703              
704             # Assign-type option: --foo=bar
705 16         98 ( $argv, $arg_eq ) = split m{=}smx, $argv;
706 16         39 unshift @ARGV, $arg_eq;
707 16         68 _trace("Option $argv has assignment");
708 16         39 _trace_argv();
709             }
710              
711             # Process $argv as directed by %options, or push it back onto @ARGV
712              
713 93 100       273 if ( _is_registered($argv) ) {
714              
715             # Registered option, the simple case
716 61 100       173 if ( _do_option_action( $argv, $arg_eq ) ) { next; }
  57         213  
717              
718             # _do_option_action returns 0 iff $arg_eq and no sub
719 4         20 _error(qq{To use $argv with "=", a subroutine must be provided});
720 4         12 _not_option( $argv, $arg_eq );
721 4         15 next;
722             }
723              
724 32         138 _trace("$argv is not registered");
725              
726             # Well, what we have in $argv is not registered
727              
728 32 100       116 if ( defined $config{'findsub'} ) {
729 7         17 my $sub = _check_all_sub($argv);
730 7 100       60 if ( defined $sub ) {
731 5         20 _trace("Running code $sub");
732 27     27   156 no strict 'refs'; ## no critic (ProhibitNoStrict)
  27         49  
  27         34263  
733 5         20 $sub->();
734 5         114 next;
735             }
736 2 50       6 if ( _do_option_action( $argv, $arg_eq ) ) { next; }
  0         0  
737             }
738              
739             # $argv is not registered.
740             # Perhaps its a concatiation of single-letter SHORTs?
741 27 100 100     188 if ( ( $op_type == $SHORT ) && ( length $argv > 2 ) ) {
742 8         18 my %args;
743 8         28 my @args = _split_arg( $argv, \%args );
744              
745 8         19 foreach my $arg (@args) {
746 25 100       44 if ( _is_registered($arg) ) {
747 11         24 _do_option_action($arg);
748 11         21 $args{$arg}--;
749 11         23 $args{$argv}--;
750             }
751             else {
752 14         37 _trace("$arg is not registered");
753             }
754             }
755              
756             # Generate error messages for unregistered arg(s)
757             # $argv is not registered iff _none_ of its components are registered
758             # We know this because none of the components caused a decrement above
759 8 100       32 if ( $args{$argv} == @args ) {
760 4         12 _notreg($argv);
761 4         15 _trace("$argv is not an option");
762 4         13 _not_option( $argv, $arg_eq );
763 4         21 next;
764             }
765              
766             # Report all components of $argv that are not registered
767 4         9 foreach my $arg (@args) {
768 15 100       31 if ( $args{$arg} == 0 ) { next; }
  11         13  
769 4         14 _notreg(qq{$arg (from $argv)});
770 4         14 _trace("$arg is not an option");
771 4         17 _not_option($arg);
772             }
773 4         21 next;
774             }
775              
776             # Provide a warning for non-bare options
777 19 100       68 if ( $op_type != $BARE ) { _notreg($argv); }
  10         36  
778              
779             # Save an element of @ARGV that did not meet the criteria for an option
780 19         67 _trace("$argv is not an option");
781 19         74 _not_option( $argv, $arg_eq );
782             }
783              
784             # Give the user what's left
785 53         128 unshift @ARGV, @not_option;
786 53         155 _trace("Scanning ends");
787 53         134 _trace_argv();
788              
789 53         114 return;
790             }
791              
792             sub _sort_sub {
793 11     11   21 my ( $A, $B ) = ( $a, $b );
794 11         32 $A =~ s{\A-*}{}smx;
795 11         24 $B =~ s{\A-*}{}smx;
796 11         28 return $A cmp $B;
797             }
798              
799             sub _version {
800 5     5   171 print STDERR "This is $callers[0][0][1]";
801 5 50 33     40 if ( defined $their_version and length $their_version ) {
802 5         86 print STDERR " version $their_version";
803             }
804             else {
805 0         0 print STDERR " (no version is specified)";
806             }
807 5         62 print STDERR "\n\n";
808 5         11 return;
809             }
810              
811             sub _help {
812 4     4   12 _version();
813              
814             # Are we being asked for *specific* help?
815 4 100       21 if ( my @help = grep { exists $options{$_} } @ARGV ) {
  2         13  
816 2         5 my $what = shift @ARGV;
817 2 50       12 if ( exists $options{$what}{'shorthelp'} ) {
818 2         27 print STDERR
819             "$callers[0][0][1] $what - $options{$what}{'shorthelp'}\n\n";
820 2 50       11 if ( defined $options{$what}{'longhelp'} ) {
821 2         33 print STDERR $options{$what}{'longhelp'}, "\n";
822             }
823             }
824             else {
825 0         0 print STDERR "No help available for $what\n";
826             }
827             }
828             else {
829              
830 2         5 my $and_there_s_more = 0;
831 2         21 foreach ( sort _sort_sub keys %options ) {
832 8         93 print STDERR "$callers[0][0][1] $_";
833 8 100 66     65 if ( defined $options{$_}{'shorthelp'}
834             and ( $options{$_}{'shorthelp'} =~ m{\S}smx ) )
835             {
836 7         80 print STDERR " - $options{$_}{'shorthelp'}";
837             }
838 8 100 66     48 if ( defined $options{$_}{'longhelp'}
839             and ( $options{$_}{'longhelp'} =~ m{\S}smx ) )
840             {
841 2         4 $and_there_s_more++;
842 2         22 print STDERR q{ [*]};
843             }
844 8         82 print STDERR "\n";
845             }
846              
847 2 50       10 if ($and_there_s_more) {
848 2         15 print STDERR <<"EOF";
849              
850             More help is available on the topics marked with [*]
851             Try $callers[0][0][1] $PREFIXES[$help_p]help $PREFIXES[$help_p]foo
852             EOF
853             }
854             }
855 4         81 print STDERR qq{This is the built-in help, exiting\n};
856 4 50       25 if ( not defined $config{'test'} ) { exit 0; }
  0         0  
857 4         10 return;
858             }
859              
860             1;
861              
862             # This package exists to provide replacement for the default subs (of the same name)
863             # provided by Pod::Parser
864             # The way it works is that they are called at appropriate times to extract the
865             # information we need to support the options.
866             # The sub names are determined by Pod::Parser, so don't meddle.
867              
868             ## no critic (ProhibitMultiplePackages)
869             package Getopt::Auto::PodExtract;
870 27     27   331 use base 'Pod::Parser';
  27         68  
  27         57577  
871              
872             ## no critic (ProtectPrivateSubs)
873              
874             # Called when Pod::Parser finds '^=...'
875             sub command {
876 117     117   231 my ( $self, $command, $text, $line_num ) = @_;
877              
878             # Cancel text grabs; whatever we've got, we've got.
879 117         314 $self->{'copying'} = 0;
880              
881             # Process only "=item" and "=head2, =head3 and =head4"
882 117 100 100     684 if ( $command eq 'item' || $command =~ m{^head(?:2|3|4)}smx ) {
883              
884             # Sometimes more han one newline, which I don't understand
885 83         458 while ( chomp $text ) { }
886              
887 83         267 Getopt::Auto::_trace("Parsing =$command $text");
888              
889 83         94 my $shorthelp;
890 83         369 $text =~ s{\s+-+\s+(.*)}{}smx;
891 83 100       245 if ( defined $1 ) {
892 80         146 $shorthelp = $1;
893             }
894              
895             # No qualifying dash, or no space after dash
896             # The RE fails, leaving $t unchanged
897 83 100       177 if ( not defined $shorthelp ) {
898 3         6 Getopt::Auto::_trace('No shorthelp, not an option');
899 3         23 return;
900             }
901              
902 80         200 Getopt::Auto::_trace("Shorthelp is: $shorthelp");
903              
904             # This suports options of the form "-f, --foo"
905 80         95 my $sub;
906             my @nosub;
907 80         231 my @opts = split m{,\s*}smx, $text;
908 80         141 foreach my $name (@opts) {
909 83         373 $name =~ s{\A(\w<)?([\w_-]+)>?}{$2}smx;
910 83 50       243 if ( $name =~ m{\s}smx ) {
911 0         0 Getopt::Auto::_trace("$name dropped, has spaces");
912 0         0 next;
913             }
914              
915 83         254 Getopt::Auto::_trace("Option is $name");
916 83         324 $self->{'funcs'}{$name} = { 'shorthelp' => $shorthelp, };
917 83         140 $self->{'copying'} = 1;
918 83         141 $self->{'latest'} = $name;
919 83         178 my $sub_found = Getopt::Auto::_check_func($name);
920 83 100       187 if ( defined $sub_found ) {
921 59         138 $self->{'funcs'}{$name}{'code'} = $sub_found;
922 59         148 $sub = $sub_found;
923             }
924             else {
925 24         70 push @nosub, $name;
926             }
927             }
928              
929             # Options that had no defined sub get the last-defined sub
930 80         194 foreach my $name (@nosub) {
931 24         97 $self->{'funcs'}{$name}{'code'} = $sub;
932             }
933             }
934 114         1501 return;
935             }
936              
937             # Called when text that begins with spaces (or tabs) is discovered inside POD text.
938             # As implied by the name, verbatum text is taken 'as is'.
939             # We save it only if we're inside of =item or =head ($self->{copying})
940              
941             sub verbatim {
942 0     0   0 my ( $self, $paragraph, $line_num ) = @_;
943 0 0       0 if ( $self->{'copying'} ) {
944 0         0 $self->{'funcs'}{ $self->{'latest'} }{'longhelp'} .= $paragraph;
945 0         0 Getopt::Auto::_trace("verbatim - longhelp is: $paragraph");
946             }
947 0         0 return;
948             }
949              
950             # Called when text that does not begin with spaces (or tabs) is discovered inside POD text.
951             # The semantics of text blocks require that 'interior sequences' (e.g.: B) be expanded.
952             # That's what the Pod::Parser sub interpolate() does.
953             # We save it only if we're inside of =item or =head ($self->{copying})
954              
955             sub textblock {
956 38     38   67 my ( $self, $paragraph, $line_num ) = @_;
957 38 100       130 if ( $self->{'copying'} ) {
958 35         3167 $self->{'funcs'}{ $self->{'latest'} }{'longhelp'}
959             .= $self->interpolate( $paragraph, $line_num );
960 35         115 Getopt::Auto::_trace("textblock - longhelp is: $paragraph");
961             }
962 38         410 return;
963             }
964              
965             sub preprocess_line {
966 3025     3025   4392 my ( $self, $text, $line_num ) = @_;
967              
968 3025 100       4527 defined Getopt::Auto::_get_their_version() and return $text;
969              
970 715 100       1553 if ( $text =~ m{\$VERSION}smx ) {
971 27         165 my ($tv) = $text =~ m{([\d\.]+)}smx;
972 27         99 Getopt::Auto::_set_their_version($tv);
973 27         117 Getopt::Auto::_trace("Extracted version $tv from $text");
974             }
975 715         5303 return $text;
976             }
977              
978             1;
979              
980             __END__