File Coverage

blib/lib/Getopt/Complete.pm
Criterion Covered Total %
statement 22 50 44.0
branch 2 14 14.2
condition 0 3 0.0
subroutine 7 8 87.5
pod 0 1 0.0
total 31 76 40.7


line stmt bran cond sub pod time code
1             package Getopt::Complete;
2              
3 2     2   25212 use strict;
  2         168  
  2         91  
4 2     2   13 use warnings;
  2         3  
  2         118  
5              
6             our $VERSION = '0.26';
7              
8 2     2   2841 use Getopt::Complete::Options;
  2         16  
  2         211  
9 2     2   4913 use Getopt::Complete::Args;
  2         7  
  2         66  
10 2     2   2357 use Getopt::Complete::Compgen;
  2         6  
  2         734  
11              
12             our $ARGS;
13             our %ARGS;
14              
15             our $EXIT_ON_ERRORS = 1;
16             our $LONE_DASH_SUPPORT = 0;
17              
18             sub import {
19 1     1   13 my $class = shift;
20 1 50       25 unless (@_) {
21             # re-using this module after options processing, with no arguments,
22             # will just re-export (alias, actually) %ARGS and $ARGS.
23 1 50       5 if ($ARGS) {
24 0         0 $class->export_aliases();
25             }
26 1         13 return;
27             }
28              
29 0 0         if ($ARGS) {
30             # Turn on fatal warnings, and this will safely be a die().
31 0           warn "Overriding default command-line %ARGS with a second call to Getopt::Complete!";
32             }
33              
34             # The safe way to use this module is to specify args at compile time.
35             # This allows 'perl -c' to handle shell-completion requests.
36             # Direct creation of objects is mostly for testing, and wrapper modules.
37            
38             # Make a single default Getopt::Complete::Options object,
39            
40 0           my $options = Getopt::Complete::Options->new(@_);
41            
42             # See if we are really just being run to respond to a shell completion request.
43             # (in this case, the app will exit inside this call)
44              
45 0           $options->handle_shell_completion();
46              
47             # and then a single default Getopt::Complete::Args object.
48            
49 0           my $args = Getopt::Complete::Args->new(
50             options => $options,
51             argv => [@ARGV]
52             );
53            
54             # Then make it and its underlying hash available globally in this namespace
55 0           $args->__install_as_default__();
56              
57             # Alias the above into the caller's namespace
58 0           my $caller = caller();
59 0           $class->export_aliases($caller);
60            
61             # This is overridable externally.
62 0 0         if ($EXIT_ON_ERRORS) {
63 0 0         if (my @errors = $ARGS->errors) {
64 0           for my $error ($ARGS->errors) {
65 0           chomp $error;
66 0           warn __PACKAGE__ . ' ERROR: ' . $error . "\n";
67             }
68 0           exit 1;
69             }
70             }
71             }
72              
73             sub export_aliases {
74 0     0 0   my ($class,$pkg) = @_;
75 2     2   14 no strict 'refs';
  2         3  
  2         609  
76 0   0       $pkg ||= caller();
77 0           my $v;
78 0           $v = ${ $pkg . "::ARGS" };
  0            
79 0 0         unless (defined $v) {
80 0           *{ $pkg . "::ARGS" } = \$ARGS;
  0            
81             }
82 0           $v = \%{ $pkg . "::ARGS" };
  0            
83 0 0         unless (keys %$v) {
84 0           *{ $pkg . "::ARGS" } = \%ARGS;
  0            
85             }
86             }
87              
88             1;
89              
90             =pod
91              
92             =head1 NAME
93              
94             Getopt::Complete - programmable shell completion for Perl apps
95              
96             =head1 VERSION
97              
98             This document describes Getopt::Complete 0.26.
99              
100             =head1 SYNOPSIS
101              
102             In the Perl program "myprogram":
103              
104             use Getopt::Complete (
105             'frog' => ['ribbit','urp','ugh'],
106             'fraggle' => sub { return ['rock','roll'] },
107             'quiet!' => undef,
108             'name' => undef,
109             'age=n' => undef,
110             'outfile=s@' => 'files',
111             'outdir' => 'directories'
112             'runthis' => 'commands',
113             'username' => 'users',
114             '<>' => 'directories',
115             );
116              
117             print "the frog says " . $ARGS{frog} . "\n";
118              
119             In ~/.bashrc or ~/.bash_profile, or directly in bash:
120              
121             function _getopt_complete () {
122             COMPREPLY=($( COMP_CWORD=$COMP_CWORD perl `which ${COMP_WORDS[0]}` ${COMP_WORDS[@]:0} ));
123             }
124             complete -F _getopt_complete myprogram
125              
126             Thereafter in the terminal (after next login, or sourcing the updated .bashrc):
127              
128             $ myprogram --f
129             $ myprogram --fr
130              
131             $ myprogram --fr
132             frog fraggle
133              
134             $ myprogram --fro
135             $ myprogram --frog
136              
137             $ myprogram --frog
138             ribbit urp ugh
139              
140             $ myprogram --frog r
141             $ myprogram --frog ribbit
142              
143             =head1 DESCRIPTION
144              
145             This module makes it easy to add custom command-line completion to Perl
146             applications. It also does additional validation of arguments, when the
147             program is actually executed, based on completion lists.
148              
149             Support is also present for apps which are an entry point for a hierarchy of
150             sub-commands (in the style of cvs and git).
151              
152             Getopt::Complete also wraps the standard options processing and exports
153             it as a %ARGS hash at compile time, making using the arguments hassle-free.
154              
155             The completion features currently work with the bash shell, which is
156             the default on most Linux and Mac systems. Patches for other shells
157             are welcome.
158              
159             =head1 OPTIONS PROCESSING
160              
161             Getopt::Complete processes the command-line options at compile time.
162              
163             The results are avaialble in the %ARGS hash, which is intended as a companion
164             to the @ARGV array generated natively by Perl.
165              
166             use Getopt::Complete (
167             'mydir' => 'd',
168             'myfile' => 'f',
169             '<>' = ['monkey', 'taco', 'banana']
170             );
171              
172             for $opt (keys %ARGS) {
173             $val = $ARGS{$opt};
174             print "$opt has value $val\n";
175             }
176              
177             Errors in shell argumentes result in messages to STDERR via warn(), and cause the
178             program to exit during "use" call. Getopt::Complete verifies that the option values
179             specified match their own completion list, and will otherwise add additional errors
180             explaining the problem.
181              
182             The %ARGS hash is an alias for %Getopt::Complete::ARGS. The alias is not created
183             in the caller's namespaces if a hash named %ARGS already exists with data, but
184             the results are always available from %Getopt::Complete::ARGS.
185              
186             They keys of the hash are the option names, minus any specifiers like "=s" or "!".
187             The key is only present if the option was specified on the command-line.
188              
189             The values of the hash are the values from the command-line. For multi-value
190             options the hash value is an arrayref.
191              
192             =head1 OBJECT API
193              
194             An object $ARGS is also created in the caller's namespace (class L)
195             with a more detailed API for argument interrogation. See the documentation for that
196             module, and also for the underlying L module.
197              
198             It is possible to override any part of the default process, including doing custom
199             parsing, doing processing at run-time, and and preventing exit when there are errors.
200              
201             See OVERRIDING COMPILE-TIME OPTION PARSING for more information.
202              
203             =head1 PROGRAMMABLE COMPLETION BACKGROUND
204              
205             The bash shell supports smart completion of words when the key is pressed.
206             By default, after the program name is specified, bash will presume the word the user
207             is typing a is a file name, and will attempt to complete the word accordingly. Where
208             completion is ambiguous, the shell will go as far as it can and beep. Subsequent
209             completion attempts at that position result in a list being shown of possible completions.
210              
211             Bash can be configured to run a specific program to handle the completion task, allowing
212             custom completions to be done for different appliations. The "complete" built-in bash
213             command instructs the shell as-to how to handle tab-completion for a given command.
214              
215             This module allows a program to be its own word-completer. It detects that the
216             COMP_LINE and COMP_POINT environment variables are set, indicating that it is being
217             used as a completion program, and responds by returning completion values suitable
218             for the shell _instead_ of really running the application.
219              
220             See the manual page for "bash", the heading "Programmable Completion" for full
221             details on the general topic.
222              
223             =head1 HOW TO CONFIGURE PROGRAMMABLE COMPLETION
224              
225             =over 4
226              
227             =item 1
228              
229             Put a "use Getopt::Complete" statement into your app as shown in the synopsis.
230             The key-value pairs describe the command-line options available,
231             and their completions.
232              
233             This should be at the TOP of the app, before any real processing is done.
234             The only modules used before it should be those needed for custom callbacks,
235             if there are any. No code should print to standard output during compile
236             time, or it will confuse bash.
237              
238             Subsequent code can use %ARGS or the $ARGS object to check on command-line
239             option values.
240              
241             Existing apps using Getopt::Long should use their option spec in the use declaration
242             instead. If they bind variables directly the code should to be updated to get
243             values from the %ARGS hash instead.
244              
245             =item 2
246              
247             Put the following in your .bashrc or .bash_profile:
248              
249             function _getopt_complete () {
250             COMPREPLY=($( COMP_CWORD=$COMP_CWORD perl `which ${COMP_WORDS[0]}` ${COMP_WORDS[@]:0} ));
251             }
252             complete -F _getopt_complete myprogram
253              
254             =item 3
255              
256             New logins will automatically run the above and become aware that your
257             program has programmable completion. For shells you already
258             have open, run this to alert bash to your that your program has
259             custom tab-completion.
260              
261             source ~/.bashrc
262              
263             =back
264              
265             Type the name of your app ("myprogram" in the example), and experiment
266             with using the key to get various completions to test it. Every time
267             you hit , bash sets certain environment variables, and then runs your
268             program. The Getopt::Complete module detects these variables, responds to the
269             completion request, and then forces the program to exit before really running
270             your regular application code.
271              
272             IMPORTANT: Do not do steps #2 and #3 w/o doing step #1, or your application
273             will actually run "normally" every time you press with it on the command-line!
274             The module will not be present to detect that this is not a "real" execution
275             of the program, and you may find your program is running when it should not.
276              
277              
278             =head1 KEYS IN THE OPTIONS SPECIFICATION
279              
280             Each key in the list decribes an option which can be completed. Any
281             key usable in a Getopt:::Long GetOptions specification works here,
282             (except as noted in BUGS below):
283              
284             =over 4
285              
286             =item an option name
287              
288             A normal word is interpreted as an option name. The '=s' specifier is
289             presumed if no specifier is present.
290              
291             'p1' => [...]
292              
293             =item a complete option specifier
294              
295             Any specification usable by L is valid as the key.
296             For example:
297              
298             'p1=s' => [...] # the same as just 'p1'
299             'p2=s@' => [...] # expect multiple values
300              
301             =item the '<>' symbol for "bare arguments"
302              
303             This special key specifies how to complete non-option (bare) arguments.
304             It presumes multiple values are possible (like '=s@'):
305              
306             Have an explicit list:
307             '<>' = ['value1','value2','value3']
308              
309             Do normal file completion:
310             '<>' = 'files'
311              
312             Take arbitrary values with no expectations:
313             '<>' = undef
314              
315             If there is no '<>' key specified, bare arguments will be treated as an error.
316              
317             =item a sub-command specifier, starting with '>'
318              
319             When a key in the options specification starts with '>', it indicates
320             a that word maps to a distinct sub-command with its own options. The
321             array to the right is itself a full options specification, following
322             the same format as the one above it, including possible further
323             sub-commands.
324              
325             See SUB-COMMAND TREES for more details.
326              
327             =back
328              
329             =head1 VALUES IN THE OPTIONS SPECIFICATION
330              
331             Each value describes how the option in question should be completed.
332              
333             =over 4
334              
335             =item array reference
336              
337             An array reference expliciitly lists the valid values for the option.
338              
339             In the app:
340              
341             use Getopt::Complete (
342             'color' => ['red','green','blue'],
343             );
344              
345             In the shell:
346              
347             $ myprogram --color
348             red green blue
349              
350             $ myprogram --color blue
351             (runs with no errors)
352              
353             The list of value is also used to validate the user's choice after options
354             are processed:
355              
356             myprogram --color purple
357             ERROR: color has invalid value purple: select from red green blue
358              
359             See below for details on how to permit values which aren't shown in completions to
360             be used and not generate errors.
361              
362             =item undef
363              
364             An undefined value indicates that the option is not completable. No completions
365             will be offered by the application, though any value provided by the user will be
366             considered valid.
367              
368             Note that this is distinct from returning an empty arrayref from a callback, which
369             implies that there ARE known completions but the user has failed to match any of them.
370              
371             Also note: this is the only valid completion for boolean parameters, since there is no
372             value to specify on the command-line.
373              
374             use Getopt::Complete (
375             'name' => undef, # take --name "anyting"
376             'perky!' => undef, # take --perky or --no-perky
377             );
378              
379             =item subroutine callback
380              
381             When the list of valid values must be determined dynamically, a subroutine reference or
382             name can be specified. If a name is specified, it should be fully qualified. (If
383             it is not, it will be presumed to refer to one of the bash builtin completions types.
384             See BUILTIN COMPLETION TYPES below.)
385              
386             The subroutine will be called, and is expected to return an arrayref of possiible matches.
387             The arrayref will be treated as though it were specified directly in the specification.
388              
389             As with explicit values, an empty arrayref indicated that there are no valid matches
390             for this option, given the other params on the command-line, and the text already typed.
391             An undef value indicates that any value is valid for this parameter.
392              
393             Parameters to the callback are described below.
394              
395             =back
396              
397             =head1 WRITING SUBROUTINE CALLBACKS
398              
399             A subroutine callback is useful when the list of options to match must be dynamically generated.
400              
401             It is also useful when knowing what the user has already typed helps narrow the search for
402             valid completions, or when iterative completion needs to occur (see PARTIAL COMPLETIONS below).
403              
404             The callback is expected to return an arrayref of valid completions. If it is empty, no
405             completions are considered valid. If an undefined value is returned, no completions are
406             specified, but ANY arbitrary value entered is considered valid as far as error checking is
407             concerned.
408              
409             The callback registerd in the completion specification will receive the following parameters:
410              
411             =over 4
412              
413             =item command name
414              
415             Contains the name of the command for which options are being parsed. This is $0 in most
416             cases, though hierarchical commands may have a name "svn commit" or "foo bar baz" etc.
417              
418             =item current word
419              
420             This is the word the user is trying to complete. It may be an empty string, if the user hits
421             without typing anything first.
422              
423             =item option name
424              
425             This is the name of the option for which we are resolving a value. It is typically ignored unless
426             you use the same subroutine to service multiple options.
427              
428             A value of '<>' indicates an unnamed argument (a.k.a "bare argument" or "non-option" argument).
429              
430             =item other opts
431              
432             It is the hashref resulting from Getopt::Long processing of all of the OTHER arguments.
433             This is useful when one option limits the valid values for another option.
434              
435             In some cases, the options which should be available change depending on what other
436             options are present, or the values available change depending on other options or their
437             values.
438              
439             =back
440              
441             The environment variables COMP_LINE and COMP_POINT have the exact text
442             of the command-line and also the exact character position, if more detail is
443             needed in raw form than the parameters provide.
444              
445             The return value is a list of possible matches. The callback is free to narrow its results
446             by examining the current word, but is not required to do so. The module will always return
447             only the appropriate matches.
448              
449             =head2 EXAMPLE
450              
451             This app takes 2 parameters, one of which is dependent on the other:
452              
453             use Getopt::Complete (
454             type => ['names','places','things'],
455             instance => sub {
456             my ($command, $value, $option, $other_opts) = @_;
457             if ($other_opts{type} eq 'names') {
458             return [qw/larry moe curly/],
459             }
460             elsif ($other_opts{type} eq 'places') {
461             return [qw/here there everywhere/],
462             }
463             elsif ($other_opts{type} eq 'things') {
464             return [ query_database_matching("${value}%") ]
465             }
466             elsif ($otper_opts{type} eq 'surprsing') {
467             # no defined list: take anything typed
468             return undef;
469             }
470             else {
471             # invalid type: no matches
472             return []
473             }
474             }
475             );
476              
477             $ myprogram --type people --instance
478             larry moe curly
479              
480             $ myprogram --type places --instance
481             here there everywhere
482              
483             $ myprogram --type surprising --instance
484             (no completions appear)
485              
486              
487             =head1 BUILTIN COMPLETIONS
488              
489             Bash has a list of built-in value types which it knows how to complete. Any of the
490             default shell completions supported by bash's "compgen" are supported by this module.
491              
492             The list of builtin types supported as-of this writing are:
493              
494             files
495             directories
496             commands
497             users
498             groups
499             environment
500             services
501             aliases
502             builtins
503              
504             To indicate that an argument's valid values are one of the above, use the exact string
505             after Getopt::Complete:: as the completion callback. For example:
506              
507             use Getopt::Complete (
508             infile => 'Getopt::Complete::files',
509             outdir => 'Getopt::Complete::directories',
510             myuser => 'Getopt::Complete::users',
511             );
512              
513             The full name is alissed as the single-character compgen parameter name for convenience.
514             Further, because Getopt::Complete is the default namespace during processing, it can
515             be ommitted from callback function names.
516              
517             The following are all equivalent. They effectively produce the same list as 'compgen -f':
518              
519             file1 => \&Getopt::Complete::files
520             file1 => \&Getopt::Complete::f
521             file1 => 'Getopt::Complete::files'
522             file1 => 'Getopt::Complete::f'
523             file1 => 'files'
524             file1 => 'f'
525              
526             See L for specifics on using builtin completions.
527              
528             See "man bash", in the Programmable Complete secion, and the "compgen" builtin command for more details.
529              
530             =head1 UNLISTED VALID VALUES
531              
532             If there are options which should not be part of completion lists, but still count
533             as valid if passed-into the app, they can be in a final sub-array at the end. This
534             list doesn't affect the completion system at all, just prevents errors in the
535             ERRORS array described above.
536              
537             use Getopt::Complete (
538             'color' => ['red','green','blue', ['yellow','orange']],
539             );
540              
541             myprogram --color
542             red green blue
543              
544             myprogram --color orange
545             # no errors
546              
547             myprogram --color purple
548             # error
549            
550             =head1 PARTIAL COMPLETIONS
551              
552             =head2 BASICS
553              
554             Any returned value ending in a character ("\t") will be considered
555             a "partial" completion. This means that the shell will be instructed
556             to leave the cursor at the end of that word even if there is no ambiguity
557             in the rest of the returned list.
558              
559             Partial completions are only usable from callbacks. From a hard-coded
560             array of values, it would be impossible to ever fuly complete the partial
561             completion.
562              
563             =head2 BACKGROUND
564              
565             Sometimes, the entire list of completions is too big to reasonable resolve and
566             return. The most obvious example is filename completion at the root of a
567             large filesystem. In these cases, the completion of is handled in pieces, allowing
568             the user to gradually "drill down" to the complete value directory by directory.
569             It is even possible to hit to get one completion, then hit it again and get
570             more completion, in the case of single-sub-directory directories.
571              
572             The Getopt::Complete module supports iterative drill-down completions from any
573             parameter configured with a callback. It is completely valid to complete
574             "a" with "aa" "ab" and "ac", but then to complete "ab" with yet more text.
575              
576             Unless the shell knows, however that your "aa", "ab", and "ac" completions are
577             in fact only partial completions, an inconvenient space will be added
578             after the word on the terminal line, as the shell happily moves on to helping
579             the user enter the next argument.
580              
581             =head2 DETAILS
582              
583             Because partial completions are indicated in Getopt::Complete by adding a "\t"
584             tab character to the end of the returned string, an application can
585             return a mix of partial and full completions, and it will respect each
586             correctly.
587              
588             Note: The "\t" is actually stripped-off before going to the shell
589             and internal hackery is used to force the shell to not put a space
590             where it isn't needed. This is not part of the bash programmable completion
591             specification, but is used to simulate features typically only available
592             with bash for builtin completions like files/directories.
593              
594             =head1 SUB-COMMAND TREES
595              
596             It is common for a given appliction to actually be an entry point for several different tools.
597             Popular exmples are the big version control suites (cvs,svn,svk,git), which use
598             the form:
599              
600             cvs SUBCOMMAND [ARGS]
601              
602             Each sub-command has its own options specification. Those may in turn have further sub-commands.
603              
604             Sub-commands are identified by an initial '>' in the options specification key. The value
605             is interpreted as a complete, isolated options spec, using the same general syntax. This
606             applies recursively.
607              
608             =head2 EXAMPLE COMMAND TREE SPEC
609              
610             use Getopt::Complete (
611             '>animal' => [
612             '>dog' => [
613             '>bark' => [
614             'ferocity' => ['yip','wail','ruf','grrrr'],
615             'count' => ['1','2','one too many'],
616             ],
617             '>drool' => [
618             'buckets=n' => undef,
619             'lick' => 'users',
620             ],
621             'list!' => undef,
622             ],
623             '>cat' => [
624             '>purr' => [],
625             '>meow' => [
626             'volume=n' => undef,
627             'bass' => ['low','medium','high'],
628             ]
629             ],
630             ],
631             '>plant' => [
632             '>taters' => [
633             '>fry' => [
634             'greasiness' => ['crispy','drippy'],
635             'width' => ['fat','thin','frite'],
636             ],
637             '>bake' => [
638             'hard!' => undef,
639             'temp=n' => undef,
640             ],
641             ],
642             '>dasies' => [
643             '>pick' => [
644             '<>' => ['mine','yours','theirs'],
645             ],
646             '>plant' => [
647             'season' => ['winter','spring','summer','fall'],
648             'seeds=n' => undef,
649             'deep!' => undef,
650             ]
651             ]
652             ]
653             );
654              
655             my ($word1,$word2,$word3) = $ARGS->parent_sub_commands;
656             # (the above is also in $ARGS{'>'} for non-OO access)
657              
658             # your program probably has something smarter to decide where to go
659             # for a given command
660             if ($word1 eq 'animal') {
661             if ($word2 eq 'dog') {
662             if ($word3 eq 'bark') {
663             # work with %ARGS for barking dogs...
664             # ....
665             }
666             }
667             }
668             elsif ($path[0] eq 'plant') {
669             ...
670             }
671              
672             The above example specifies two sub-commands "animal" and "plant, each of which has its own two
673             sub-commands, dog/cat and taters/dasies. Each of those, in turn, have two sub-commands,
674             for a total of 8 complete commands possible, each with different arguments. Each of the
675             8 has thier own options specification.
676              
677             When the program executes, the %ARGS hash contains option/value pairs for the specific command
678             chosen. The the series of sub-command choices in $ARGS{'>'}, separate from the regular bare
679             arguments in '<>'. (The method name on an $ARGS object for this is "parent_sub_commands", a
680             companion to the "bare_args" method.
681              
682             The method to determine the next available sub-commands is just "sub_commands".)
683              
684             Note that, since the user can hit at any time, it is possible that the parent_sub_commands
685             will be a partial drill-down. It isn't uncommon to have something like this in place:
686              
687             if (my @next = $ARGS->sub_commands) {
688             print STDERR "Please select a sub-command:\n";
689             print STDERR join("\n", @sub_commands),"\n";
690             exit 1;
691             }
692              
693             The above checking is not done automatically, since a sub-command may have further sub-commands, but
694             still also be used directly, possibly with other option and bare arguments.
695              
696             =head1 THE LONE DASH
697              
698             A lone dash is often used to represent using STDIN instead of a file for applications which otherwise take filenames.
699              
700             This is supported by all options which complete with the "files" builtin, though it does not appear in completion hint displays.
701              
702             To disable this, set $Getopt::Complete::LONE_DASH = 0.
703              
704             =head1 OVERRIDING COMPILE-TIME OPTION PARSING
705              
706             Getopt::Complete makes a lot of assumptions in order to be easy to use in the
707             default case. Here is how to override that behavior if it's not what you want.
708              
709             =head2 OPTION 1: DOING CUSTOM ERROR HANDLING
710              
711             To prevent Getopt::Complete from exiting at compile time if there are errors,
712             the EXIT_ON_ERRORS flag should be set to 0 first, at compile time, before using
713             the Getopt::Complete module as follows:
714              
715             BEGIN { $Getopt:Complete::EXIT_ON_ERRORS = 0; }
716              
717             This should not affect completions in any way (it will still exit if it realizes
718             it is talking to bash, to prevent accidentally running your program).
719              
720             Errors are retained in:
721            
722             $Getopt::Complete::ARGS->errors;
723              
724             It is then up to the application to not run with invalid parameters.
725              
726             =head2 OPTION 2: RE-PROCESS @ARGV
727              
728             This module restores @ARGV to its original state after processing, so
729             independent option processing can be done if necessary. The full
730             spec imported by Getopt::Complete is stored as:
731              
732             $Getopt::Complete::ARGS->option_specs;
733              
734             This is an easy option when upgrading old applications.
735              
736             Combined with disabling the EXIT_ON_ERROS flag above, set, you can completely ignore,
737             or partially ignore, the options processing which happens automatically.
738              
739             =head2 OPTION 3: CHANGING COMPILE-TIME PROCESSING
740              
741             You can also adjust how option processing happens inside of Getopt::Complete.
742             Getopt::Complete wraps Getopt::Long to do the underlying option parsing. It uses
743             GetOptions(\%h, @specification) to produce the %ARGS hash. Customization of
744             Getopt::Long should occur in a BEGIN block before using Getopt::Complete.
745              
746             =head2 OPTION 4: USE THE OBJECTS AND WRITE YOUR OWN LOGIC
747              
748             The logic in import() is very short, and is simple to modify. It is best
749             to do it in a BEGIN {} block so that bash can use 'perl -c myprogram'
750             to get completions at compile time.
751              
752             BEGIN {
753              
754             my $options = Getopt::Complete::Options->new(
755             'myfile' => 'f',
756             'mychoice' => ['small','medium','huge']
757             );
758              
759             $options->handle_shell_completion();
760              
761             my $args = Getopt::Complete::Args->new(
762             options => $options,
763             argv => [@ARGV]
764             );
765            
766             if (my @errors = $ARGS->errors) {
767             for my $error ($ARGS->errors) {
768             chomp $error;
769             warn __PACKAGE__ . ' ERROR:' . $error . "\n";
770             }
771             exit 1;
772             }
773            
774             # make the %ARGS available to all of the app
775             $args->__install_as_default__;
776              
777             # if you also want %ARGS and $ARGS here when you're finished...
778             Getopt:Complete->export_aliases(__PACKAGE__);
779             };
780              
781             =head1 EXTENSIVE USAGE EXAMPLE
782              
783             Cut-and-paste this into a script called "myprogram" in your path, make it executable,
784             and then run this in the shell:
785              
786             function _getopt_complete () {
787             COMPREPLY=($( COMP_CWORD=$COMP_CWORD perl `which ${COMP_WORDS[0]}` ${COMP_WORDS[@]:0} ));
788             }
789             complete -F _getopt_complete myprogram
790              
791             Then try it out.
792             It does one of everything, besides command trees.
793              
794             #!/usr/bin/env perl
795             use strict;
796             use warnings;
797              
798             use Getopt::Complete (
799             # list the explicit values which are valid for this option
800             'frog' => ['ribbit','urp','ugh'],
801              
802             # you can add any valid Getopt::Long specification to the key on the left
803             # ...if you put nothing: "=s" is assumed
804             'names=s@' => ['eenie','meanie','miney'],
805              
806             # support for Bash "compgen" builtins is present with some pre-made callbacks
807             'myfile' => 'Getopt::Complete::Compgen::files',
808             'mydir' => 'Getopt::Complete::Compgen::directories',
809            
810             # the plain name or first letter of the compgen builtins also work
811             'myfile2' => 'files',
812             'myfile3' => 'f',
813              
814             # handle unnamed arguments from the command-line ("non-option" arguments) with a special key:
815             '<>' => ['some','raw','words'],
816              
817             # CODE callbacks allow a the completion list to be dynamically resolved
818             'fraggle' => sub { return ['rock','roll','fried fish','fried taters','fries and squid'] },
819              
820             # callbacks get extra info to help them, including the part of the
821             # word already typed, and the remainder of the options already processed for context
822             'type' => ['people','places'],
823             'instance'=> sub {
824             my ($command, $partial_word, $option_name, $other_opts_hashref) = @_;
825             # be lazy and ignore the partial word: bash will compensate
826             if (my $type = $other_opts_hashref->{type}) {
827             if ($type eq 'people') {
828             return [qw/larry moe curly/]
829             }
830             elsif ($type eq 'places') {
831             return [qw/here there everywhere/],
832             }
833             }
834             return [];
835             },
836            
837             # undef means we don't know how to complete the value: any value specified will do
838             # this will result in no shell ompletions, but will still expect a value to be entered
839             'name=s' => undef,
840              
841             # boolean values never have a completion list, and will yell if you are that foolish
842             # this will give you --no-fast for free as well
843             'fast!' => undef,
844              
845             );
846              
847             use Data::Dumper;
848             print "The arguments are: " . Dumper(\%ARGS);
849              
850             =head1 DEVELOPMENT
851              
852             Patches are welcome.
853            
854             http://github.com/sakoht/Getopt--Complete-for-Perl/
855              
856             git clone git://github.com/sakoht/Getopt--Complete-for-Perl.git
857              
858             As are complaints. Help us find bugs by sending an email to the address below, or using CPAN's bug tracking system:
859            
860             https://rt.cpan.org/
861              
862             The latest version of this module is always availabe on CPAN:
863              
864             http://search.cpan.org/search?query=Getopt%3A%3AComplete&mode=all
865              
866             And is readily installable with the CPAN shell on Mac, Linux, and other Unix-like systems:
867              
868             sudo cpan Getopt::Complete
869              
870             =head1 BUGS
871              
872             Completions with whitespace work, but they do so by escaping whitespace characters instead of quoting.
873             Support should be present for completing quoted text. It should also be the default, since it is
874             more attractive.
875              
876             The logic to "shorten" the completion options shown in some cases is still in development.
877             This means that filename completion shows full paths as options instead of just the last word in the file path.
878              
879             Some uses of Getopt::Long will not work currently: multi-name options (though standard shortening works), +, :, %.
880              
881             Currently this module only supports bash, though other shells could be added easily.
882              
883             There is logic in development to have the tool possibly auto-update the user's .bashrc / .bash_profile, but this
884             is incomplete.
885              
886             =head1 SEE ALSO
887              
888             =over 4
889              
890             =item L
891              
892             the object API for the option/value argument set
893              
894             =item L
895              
896             the object API for the options specification
897              
898             =item L
899              
900             supplies builtin completions like file lists
901              
902             =item L
903              
904             the definitive options parser, wrapped by this module
905              
906             =item L
907              
908             the manual page for bash has lots of info on how tab-completion works
909              
910             =back
911              
912             =head1 COPYRIGHT
913              
914             Copyright 2010, 2011 Washington University School of Medicine
915              
916             =head1 AUTHORS
917              
918             Scott Smith (sakoht at cpan .org)
919             Nathan Nutter
920             Andrei Benea
921              
922             =head1 LICENSE
923              
924             This program is free software; you can redistribute it and/or modify it under
925             the same terms as Perl itself.
926              
927             The full text of the license can be found in the LICENSE file included with this
928             module.
929              
930             =cut
931