blib/lib/Getopt/Complete.pm

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