File Coverage

lib/Getopt/ArgParse.pm
Criterion Covered Total %
statement 14 14 100.0
branch n/a
condition n/a
subroutine 5 5 100.0
pod 0 1 0.0
total 19 20 95.0


line stmt bran cond sub pod time code
1             require 5.008001;
2              
3             package Getopt::ArgParse;
4             {
5             $Getopt::ArgParse::VERSION = '1.0.6';
6             };
7              
8             # ABSTRACT: Getopt::ArgParse - Parsing args with a richer and more user-friendly API
9              
10 9     9   159804 use strict;
  9         14  
  9         267  
11 9     9   36 use warnings;
  9         11  
  9         293  
12 9     9   38 use Carp;
  9         13  
  9         623  
13              
14 9     9   3320 use Getopt::ArgParse::Parser;
  9         14  
  9         1605  
15              
16             sub new_parser {
17 14     14 0 988 shift;
18 14         176 return Getopt::ArgParse::Parser->new(@_);
19             }
20              
21             1;
22              
23             # perldoc
24              
25             =pod
26              
27             =head1 NAME
28              
29             Getopt::ArgParse - Parsing command line arguments with a richer and
30             more user-friendly API interface, similar to python's argpare but with
31             perlish extras.
32              
33             In particular, the modules provides the following features:
34              
35             - generating usage messages
36             - storing parsed arg values in an object, which can be also used to
37             load configuration values from files and therefore the ability for
38             applications to combine configurations in a single interface
39             - A more user-friendly interface to specify arguments, such as
40             argument types, argument values split, etc.
41             - Subcommand parsing, such svn
42             - Supporting both flag based named arguments and positional arguments
43              
44             =head1 VERSION
45              
46             version 1.0.6
47              
48             =head1 SYNOPSIS
49              
50             use Getopt::ArgParse;
51              
52             $ap = Getopt::ArgParse->new_parser(
53             prog => 'MyProgramName',
54             description => 'This is a program',
55             epilog => 'This appears at the bottom of usage',
56             );
57              
58             # Parse an option: '--foo value' or '-f value'
59             $ap->add_arg('--foo', '-f', required => 1);
60              
61             # Parse a boolean: '--bool' or '-b' using a different name from
62             # the option
63             $ap->add_arg('--bool', '-b', type => 'Bool', dest => 'boo');
64              
65             # Parse a positonal option.
66             # But in this case, better using subcommand. See below
67             $ap->add_arg('command', required => 1);
68              
69             # $ns is also accessible via $ap->namespace
70             $ns = $ap->parse_args(split(' ', 'test -f 1 -b'));
71              
72             say $ns->command; # 'test'
73             say $ns->foo; # false
74             say $ns->boo; # false
75             say $ns->no_boo; # true - 'no_' is added for boolean options
76              
77             # You can continue to add arguments and parse them again
78             # $ap->namespace is accumulatively populated
79              
80             # Parse an Array type option and split the value into an array of values
81             $ap->add_arg('--emails', type => 'Array', split => ',');
82             $ns = $ap->parse_args(split(' ', '--emails a@perl.org,b@perl.org,c@perl.org'));
83             # Because this is an array option, this also allows you to specify the
84             # option multiple times and splitting
85             $ns = $ap->parse_args(split(' ', '--emails a@perl.org,b@perl.org --emails c@perl.org'));
86              
87             # Below will print: a@perl.org|b@perl.org|c@perl.org|a@perl.org|b@perl.org|c@perl.org
88             # Because Array types are appended
89             say join('|', $ns->emails);
90              
91             # Parse an option as key,value pairs
92             $ap->add_arg('--param', type => 'Pair', split => ',');
93             $ns = $ap->parse_args(split(' ', '--param a=1,b=2,c=3'));
94              
95             say $ns->param->{a}; # 1
96             say $ns->param->{b}; # 2
97             say $ns->param->{c}; # 3
98              
99             # You can use choice to restrict values
100             $ap->add_arg('--env', choices => [ 'dev', 'prod' ],);
101              
102             # or use case-insensitive choices
103             # Override the previous option with reset
104             $ap->add_arg('--env', choices_i => [ 'dev', 'prod' ], reset => 1);
105              
106             # or use a coderef
107             # Override the previous option
108             $ap->add_args(
109             '--env',
110             choices => sub {
111             die "--env invalid values" if $_[0] !~ /^(dev|prod)$/i;
112             },
113             reset => 1,
114             );
115              
116             # subcommands
117             $ap->add_subparsers(title => 'subcommands'); # Must be called to initialize subcommand parsing
118             $list_parser = $ap->add_parser(
119             'list',
120             help => 'List directory entries',
121             description => 'A multiple paragraphs long description.',
122             );
123              
124             $list_parser->add_args(
125             [
126             '--verbose', '-v',
127             type => 'Count',
128             help => 'Verbosity',
129             ],
130             [
131             '--depth',
132             help => 'depth',
133             ],
134             );
135              
136             $ns = $ap->parse_args(split(' ', 'list -v'));
137              
138             say $ns->current_command(); # current_command stores list,
139             # Don't use this name for your own option
140              
141             $ns =$ap->parse_args(split(' ', 'help list')); # This will print the usage for the list command
142             # help subcommand is automatically added for you
143             say $ns->help_command(); # list
144              
145             # Copy parsing
146             $common_args = Getopt::ArgParse->new_parser();
147             $common_args->add_args(
148             [
149             '--dry-run',
150             type => 'Bool',
151             help => 'Dry run',
152             ],
153             );
154              
155             $sp = $ap->add_parser(
156             'remove',
157             aliases => [qw(rm)], # prog remove or prog rm
158             parents => [ $command_args ], # prog rm --dry-run
159             );
160              
161             # Or copy explicitly
162             $sp = $ap->add_parser(
163             'copy',
164             aliases => [qw(cp)], # prog remove or prog rm
165             );
166              
167             $sp->copy_args($command_parser); # You can also copy_parsers() but in this case
168             # $common_parser doesn't have subparsers
169              
170             =head1 DESCRIPTIOIN
171              
172             Getopt::ArgParse, Getopt::ArgParse::Parser and related classes
173             together aim to provide user-friendly interfaces for writing
174             command-line interfaces. A user should be able to use it without
175             looking up the document most of the time. It allows applications to
176             define argument specifications and it will parse them out of @AGRV by
177             default or a command line if provided. It implements both named
178             arguments, using Getopt::Long for parsing, and positional
179             arguments. The class also generates help and usage messages.
180              
181             The parser has a namespace property, which is an object of
182             ArgParser::Namespace. The parsed argument values are stored in this
183             namespace property. Moreover, the values are stored accumulatively
184             when parse_args() is called multiple times.
185              
186             Though inspired by Python's argparse and names and ideas are borrowed
187             from it, there is a lot of difference from the Python one.
188              
189             =head2 Getopt::ArgParser::Parser
190              
191             This is the underlying parser that does the heavylifting.
192              
193             Getopt::ArgParse::Parser is a Moo class.
194              
195             =head3 Constructor
196              
197             my $parser = Getopt::ArgParse->new_parser(
198             help => 'short description',
199             description => 'long description',
200             );
201              
202             The former calls Getopt::ArgParser::Parser->new to create a parser
203             object. The parser constructor accepts the following parameters.
204              
205             All parsers are created with a predefined Bool option --help|-h. The
206             program can choose to reset it, though.
207              
208             =over 8
209              
210             =item * prog
211              
212             The program's name. Default $0.
213              
214             =item * help
215              
216             A short description of the program.
217              
218             =item * description
219              
220             A long description of the program.
221              
222             =item * namespace
223              
224             An object of Getopt::ArgParse::Namespace. An empty namespace is created if
225             not provided. The parsed values are stored in it, and they can be
226             refered to by their argument names as the namespace's properties,
227             e.g. $parser->namespace->boo. See also Getopt::ArgParse::Namespace
228              
229             =item * parser_configs
230              
231             The Getopt::Long configurations. See also Getopt::Long
232              
233             =item * parents
234              
235             Parent parsents, whose argument and subparser specifications the new
236             parser will copy. See copy() below
237              
238             =item * error_prefix
239              
240             Customize the message prefixed to error messages thrown by
241             Getop::ArgParse, default to 'Getopt::ArgParse: '
242              
243             =item * print_usage_if_help
244              
245             Set this to false to not display usage messages even if --help is on
246             or the subcommand help is called. The default behavior is to display
247             usage messages if help is set.
248              
249             =back
250              
251             =head3 add_arg, add_argument, add_args, and add_arguments
252              
253             $parser->add_args(
254             [ '--foo', required => 1, type => 'Array', split => ',' ],
255             [ 'boo', required => 1, nargs => '+' ],
256             );
257              
258             The object method, arg_arg or the longer version add_argument, defines
259             the specfication of an argument. It accepts the following parameters.
260              
261             add_args or add_arguments() is to add multiple multiple arguments.
262              
263             =over 8
264              
265             =item * name or flags
266              
267             Either a name or a list of option strings, e.g. foo or -f, --foo.
268              
269             If dest is not specified, the name or the first option without leading
270             dashes will be used as the name for retrieving values. If a name is
271             given, this argument is a positional argument. Otherwise, it's an
272             option argument.
273              
274             Hyphens can be used in names and flags, but they will be replaced with
275             underscores '_' when used as option names. For example:
276              
277             $parser->add_argument( [ '--dry-run', type => 'Bool' ]);
278             # command line: prog --dry-run
279             $parser->namespace->dry_run; # The option's name is dry_run
280              
281             A name or option strings are following by named paramters.
282              
283             =item * dest
284              
285             The name of the attribute to be added to the namespace populated by
286             parse_args().
287              
288             =item * type => $type
289              
290             Specify the type of the argument. It can be one of the following values:
291              
292             =over 8
293              
294             =item * Scalar
295              
296             The option takes a scalar value.
297              
298             =item * Array
299              
300             The option takes a list of values. The option can appear multiple
301             times in the command line. Each value is appended to the list. It's
302             stored in an arrayref in the namespace.
303              
304             =item * Pair
305              
306             The option takes a list of key-value pairs separated by the equal sign
307             '='. It's stored in a hashref in the namespace.
308              
309             =item * Bool
310              
311             The option does not take an argument. It's set to true if the option
312             is present or false otherwise. A 'no_bool' option is also available,
313             which is the negation of bool().
314              
315             For example:
316              
317             $parser->add_argument('--dry-run', type => 'Bool');
318              
319             $ns = $parser->parse_args(split(' ', '--dry-run'));
320              
321             print $ns->dry_run; # true
322             print $ns->no_dry_run; # false
323              
324             =item * Count
325              
326             The option does not take an argument and its value will be incremented
327             by 1 every time it appears on the command line.
328              
329             =back
330              
331             =item * split
332              
333             split should work with types 'Array' and 'Pair' only.
334              
335             split specifies a string by which to split the argument string e.g. if
336             split => ',', a,b,c will be split into [ 'a', 'b', 'c' ].When split
337             works with type 'Pair', the parser will split the argument string and
338             then parse each of them as pairs.
339              
340             =item * choices or choices_i
341              
342             choices specifies a list of the allowable values for the argument or a
343             subroutine that validates input values.
344              
345             choices_i specifies a list of the allowable values for the argument,
346             but case insenstive, and it doesn't allow to use a subroutine for
347             validation.
348              
349             Either choices or chioces_i can be present or completely omitted, but
350             not both at the same time.
351              
352             =item * default
353              
354             The value produced if the argument is absent from the command line.
355              
356             Only one value is allowed for scalar argument types: Scalar, Count, and Bool.
357              
358             =item * required
359              
360             Whether or not the command-line option may be omitted (optionals
361             only). This has no effect on types 'Bool' and 'Count'. An named
362             option is marked by the question mark ? in the generated usage, e.g.
363             --help, -h ? show this help message and exit
364              
365             This parameter is ignored for Bool and Count types for they will
366             already have default values.
367              
368             =item * help
369              
370             A brief description of what the argument does.
371              
372             =item * metavar
373              
374             A name for the argument in usage messages.
375              
376             =item * reset
377              
378             Set reset to override the existing definition of an option. This will
379             clear the value in the namspace as well.
380              
381             =cut
382              
383             =item * nargs - Positional option only
384              
385             This only instructs how many arguments the parser consumes. The
386             program still needs to specify the right type to achieve the desired
387             result.
388              
389             =over 8
390              
391             =item * n
392              
393             1 if not specified
394              
395             =item * ?
396              
397             1 or 0
398              
399             =item * +
400              
401             1 or more
402              
403             =item * *
404              
405             0 or many. This will consume the rest of arguments.
406              
407             =back
408              
409             =back
410              
411             =head3 parse_args
412              
413             $namespace = $parser->parse_args(@command_line);
414              
415             This object method accepts a list of arguments or @ARGV if
416             unspecified, parses them for values, and stores the values in the
417             namespace object.
418              
419             A few things may be worth noting about parse_args().
420              
421             First, parsing for Named Arguments is done by Getopt::Long
422              
423             Second, parsing for positional arguments takes place after that for
424             named arguments. It will consume what's still left in the command
425             line.
426              
427             Finally, the Namespace object is accumulatively poplulated. If
428             parse_args() is called multiple times to parse a number of command
429             lines, the same namespace object is accumulatively populated. For
430             Scalar and Bool options, this means the previous value will be
431             overwrittend. For Pair and Array options, values will be appended. And
432             for a Count option, it will add on top of the previous value.
433              
434             In face, the program can choose to pass a already populated namespace
435             when creating a parser object. This is to allow the program to pre-load
436             values to a namespace from conf files before parsing the command line.
437              
438             And finally, it does NOT display usage messages if the argument list
439             is empty. This may be contrary to many other implementations of
440             argument parsing.
441              
442             =head3 argv
443              
444             @argv = $parser->argv; # called after parse_args
445              
446             Call this after parse_args() is invoked to get the unconsumed
447             arguments. It's up to the application to decide what to do if there is
448             a surplus of arguments.
449              
450             =head3 The Namespace Object
451              
452             The parsed values are stored in a namespace object. Any class with the
453             following three methods:
454              
455             * A constructor new()
456             * set_attr(name => value)
457             * get_attr(name)
458              
459             can be used as the Namespace class.
460              
461             The default one is Getopt::ArgParse::Namespace. It uses autoload to
462             provide a readonly accessor method using dest names to access parsed
463             values. However, this is not required for user-defined namespace. So
464             within the implementation, $namespace->get_attr($dest) should always
465             be used.
466              
467             =head2 Subcommand Support
468              
469             Note only one level of subcommand parsing is supported. Subcommands
470             cannot have subcommands.
471              
472             Call add_subparsers() first to initialize the current parser for
473             subcommand support. A help subcommand is created as part of the
474             initialization. The help subcommand has the following options:
475              
476             =over 4
477              
478             required positional arguments:
479             COMMAND ? Show the usage for this command
480             optional named arguments:
481             --help, -h ? show this help message and exit
482             --all, -a ? Show the full usage
483              
484             =back
485              
486             Call add_parser() to add a subparser for each subcommand. Use the
487             parser object returned by add_parser() to add the options to the
488             subcommand.
489              
490             Once subcommand support is on, if the first argument is not a flag,
491             i.e. starting with a dash '-', the parser's parse_args() will treat it
492             as a subcommand. Otherwise, the parser parses for the defined
493             arguments.
494              
495             The namespace's current_command() will contain the subcommand after
496             parsing successfully.
497              
498             Unlike arguments, subparsers cannot be reset.
499              
500             =head3 add_subparsers
501              
502             $parser->add_subparsers(
503             title => 'Subcommands',
504             description => 'description about providing subcommands',
505             );
506              
507             add_subparsers must be called to initialize subcommand support.
508              
509             =over 8
510              
511             =item * title
512              
513             A title message to mark the beginning of subcommand usage in the usage
514             message
515              
516             =item * description
517              
518             A general description appearing about the title
519              
520             =back
521              
522             =head3 add_parser
523              
524             $subparser = $parser->add_parser(
525             'list',
526             aliases => [qw(ls)],
527             help => 'short description',
528             description => 'a long one',
529             parents => [ $common_args ], # inherit common args from
530             # $common_args
531             );
532              
533             =over 8
534              
535             =item * $command
536              
537             The first argument is the name of the new command.
538              
539             =item * help
540              
541             A short description of the subcommand.
542              
543             =item * description
544              
545             A long description of the subcommand.
546              
547             =item * aliases
548              
549             An array reference containing a list of command aliases.
550              
551             =item * parents
552              
553             An array reference containing a list of parsers whose specification
554             will be copied by the new parser.
555              
556             =back
557              
558             =head2 get_parser
559              
560             $subparser = $parser->get_parser('ls');
561              
562             Return the parser for parsing the $alias command if exsist.
563              
564             =head2 Copying Parsers
565              
566             A parser can copy argument specification or subcommand specifciation
567             for existing parsers. A use case for this is that the program wants all
568             subcommands to have a command set of arguments.
569              
570             =head3 copy_args
571              
572             $parser->copy_args($common_args_parser);
573              
574             Copy argument specification from the $parent parser
575              
576             =head3 copy_parsers
577              
578             $parser->copy_parsers($common_args_parser);
579              
580             Copy parser specification for subcommands from the $parent parser
581              
582             =head3 copy
583              
584             $parser->copy($common_args_parser);
585              
586             Copy both arguments and subparsers.
587              
588             =head2 Usage Messages and Related Methods
589              
590             =head3 format_usage
591              
592             $usage = $parser->format_usage;
593              
594             Return the formated usage message for the whole program in an array
595             reference.
596              
597             =head3 print_usage
598              
599             $parser->print_usage;
600              
601             Print the usage mesage returned by format_usage().
602              
603             =head3 format_command_usage
604              
605             $usage = $parser->format_command_usage($subcommand);
606              
607             Return the formated usage message for the command in an array
608             reference.
609              
610             =head3 print_command_usage
611              
612             $parser->print_command_usage($subcommand);
613              
614             Print the usage message returned by format_command_usage(). If
615             $command is not given, it will first try to use
616             $self->namespace->help_command, which will be present for the help
617             subcommand, and then $self->namespace->current_command.
618              
619             =head3
620              
621             =head1 SEE ALSO
622              
623             Getopt::Long
624             Python's argparse
625              
626             =head1 AUTHOR
627              
628             Mytram (original author)
629              
630             =head1 CONTRIBUTORS
631              
632             Robbin Bonthond (rbonthond@github)
633             Adam Pfeiffer (apinco@github)
634              
635             =head1 COPYRIGHT AND LICENSE
636              
637             This software is Copyright (c) 2015 by Mytram.
638              
639             This is free software, licensed under:
640              
641             The Artistic License 2.0 (GPL Compatible)
642              
643             =cut
644              
645             __END__