File Coverage

blib/lib/App/Cmdline.pm
Criterion Covered Total %
statement 37 52 71.1
branch 6 18 33.3
condition 1 2 50.0
subroutine 10 12 83.3
pod 5 5 100.0
total 59 89 66.2


line stmt bran cond sub pod time code
1             #-----------------------------------------------------------------
2             # App::Cmdline
3             # Author: Martin Senger
4             # For copyright and disclaimer see the POD.
5             #
6             # ABSTRACT: helper for writing command-line applications
7             # PODNAME: App::Cmdline
8             #-----------------------------------------------------------------
9 2     2   37949 use warnings;
  2         4  
  2         62  
10 2     2   9 use strict;
  2         4  
  2         73  
11              
12             package App::Cmdline;
13 2     2   9 use parent 'App::Cmd::Simple';
  2         2  
  2         12  
14              
15             our $VERSION = '0.1.2'; # VERSION
16              
17 2     2   441 BEGIN {
18             # we need to say no_auto_version early
19 2     2   159005 use Getopt::Long qw(:config no_auto_version);
  2         25660  
  2         14  
20             }
21 2     2   21 use Sub::Install;
  2         4  
  2         21  
22              
23             # ----------------------------------------------------------------
24             # Return the command-line script usage (the 1st line of the
25             # Usage). The content of the usage slightly differs depending on the
26             # configuration options used.
27             # ----------------------------------------------------------------
28             sub usage_desc {
29 1     1 1 20799 my $self = shift;
30 1         3 my $config = { map { $_ => 1 } @{ $self->getopt_conf() } };
  3         11  
  1         12  
31 1 50       8 if (exists $config->{'no_bundling'}) {
32 1         11 return "%c [short or long options, not bundled]";
33             } else {
34 0         0 return "%c %o";
35             }
36             }
37              
38             # ----------------------------------------------------------------
39             # Create (and return) option definitions from wanted option sets
40             # (given as class names). Also install the validate_args() subroutine
41             # that will call validate_opts() on all wanted option sets.
42             # ----------------------------------------------------------------
43             sub composed_of {
44 2     2 1 3197 my $self = shift;
45 2         7 my @option_classes = @_; # list of class names with wanted options sets
46              
47             # create option definitions
48 2         3 my @opt_spec = ();
49 2         5 foreach my $set (@option_classes) {
50 2 100 50     13 push (@opt_spec, $set) and next if ref ($set);
51             ## no critic
52 1         64 eval "require $set";
53 1 50       16 if ($set->can ('get_opt_spec')) {
54 1         6 push (@opt_spec, $set->get_opt_spec());
55             } else {
56 0         0 warn "Cannot find the set of options $set. The set is, therefore, ignored.\n";
57             }
58             }
59              
60             # install a dispatcher of all validating methods
61             Sub::Install::reinstall_sub ({
62             code => sub {
63 1     1   3520 foreach my $set (@option_classes) {
64 1 50       8 next if ref ($set);
65 1 50       9 if ($set->can ('validate_opts')) {
66 1         6 $set->validate_opts ($self, @_);
67             }
68             }
69             },
70 2         24 as => 'validate_args',
71             });
72             # add the configuration options
73 2         160 return (@opt_spec, { getopt_conf => $self->getopt_conf() } );
74             }
75              
76             # ----------------------------------------------------------------
77             # Check if the given set of options has duplications. Warn if yes.
78             # ----------------------------------------------------------------
79             sub check_for_duplicates {
80 0     0 1 0 my ($self, @opt_spec) = @_;
81 0         0 my $already_defined = {};
82 0         0 foreach my $opt (@opt_spec) {
83             # e.g. $opt: [ 'check|c' => "only check the configuration" ]
84             # or: []
85 0 0       0 next unless ref ($opt) eq 'ARRAY';
86 0 0       0 next if @$opt == 0;
87 0         0 my ($opt_name) = split (m{\|}, $opt->[0]);
88 0 0       0 next unless defined $opt_name;
89 0 0       0 if (exists $already_defined->{$opt_name}) {
90 0         0 warn
91             "Found duplicated definition of the option '$opt_name': [" .
92             join (' => ', @$opt) . "].\n";
93             } else {
94 0         0 $already_defined->{$opt_name} = 1;
95             }
96             }
97 0         0 return @opt_spec;
98             }
99              
100             # ----------------------------------------------------------------
101             # Return a refarray of the Getopt configuration options.
102             # ----------------------------------------------------------------
103             sub getopt_conf {
104             return [
105 3     3 1 21 'no_bundling',
106             'no_ignore_case',
107             'auto_abbrev',
108             ];
109             }
110              
111             # ----------------------------------------------------------------
112             # Die with a given $error message and with the full Usage.
113             # ----------------------------------------------------------------
114             sub usage_error {
115 0     0 1   my ( $self, $error ) = @_;
116 0           die "Error: $error\nUsage: " . $self->usage->text;
117             }
118              
119             1;
120              
121              
122             =pod
123              
124             =head1 NAME
125              
126             App::Cmdline - helper for writing command-line applications
127              
128             =head1 VERSION
129              
130             version 0.1.2
131              
132             =head1 SYNOPSIS
133              
134             In your command-line script, e.g. in F:
135              
136             use App::myapp;
137             App::myapp->run;
138              
139             Such command-line script will be executed, for example, by:
140              
141             senger@ShereKhan$ myapp --version
142             senger@ShereKhan$ myapp --check
143             senger@ShereKhan$ myapp -c
144              
145             In your module that does the full job you are implementing, e.g. in
146             F:
147              
148             package App::myapp;
149             use parent 'App::Cmdline';
150              
151             # Define your own options, and/or add some predefined sets.
152             sub opt_spec {
153             my $self = shift;
154             return $self->check_for_duplicates (
155             [ 'check|c' => "only check the configuration" ],
156             $self->composed_of (
157             'App::Cmdline::Options::Basic',
158             'App::Cmdline::Options::DB',
159             )
160             );
161             }
162              
163             # The main job is implemented here
164             use Data::Dumper;
165             sub execute {
166             my ($self, $opt, $args) = @_;
167              
168             print STDERR "Started...\n" unless $opt->quiet;
169             print STDOUT 'Options ($opt): ' . Dumper ($opt);
170             print STDOUT 'Arguments ($args): ' . Dumper ($args);
171             ...
172             }
173              
174             =head1 DESCRIPTION
175              
176             This module helps to write command-line applications, especially if
177             they need to be fed by some command-line options and arguments. It
178             extends the L module by adding the ability to use
179             several predefined sets of options that many real command-line
180             applications use and need anyway. For example, in most applications
181             you need a way how to print its version or how to provide a decent
182             help text. Once (or if) you agree with the way how it is done here,
183             you can spend much less time with the almost-always-repeating options.
184              
185             Your module (representing the application you are writing) should
186             inherit from this module and implement, at least, the method
187             L (optionally) and the method L (mandatory).
188              
189             =for :stopwords d'E<234>tre
190              
191             =head1 METHODS
192              
193             In order to use the ability of composing list of options from the
194             existing sets of predefined options (which is, after all, the main
195             Itre> of this module) use the method
196             L. And to find out that various predefined
197             sets of options do not step on each other toes, use the method
198             L.
199              
200             When writing a subclass of App::Cmdline, there are only a few methods
201             that you might want to overwrite (except for L that you
202             B overwrite). Below are those that may be of your interest, or
203             those that are implemented here slightly differently from the
204             L.
205              
206             =head3 Summary of methods
207              
208             =over
209              
210             =item Methods that you must overwrite
211              
212             execute()
213              
214             =item Methods that you should overwrite
215              
216             opt_spec()
217              
218             =item Methods that you may overwrite
219              
220             usage_desc()
221             validate_args()
222             usage_error()
223             getopt_conf()
224             ...
225              
226             =item Methods that you just call
227              
228             composed_of()
229             check_for_duplicates()
230             usage_error()
231              
232             =back
233              
234             =head2 B
235              
236             This method returns a list with option definitions, each element being
237             an arrayref. This returned list is passed (starting as its second
238             argument) to C from
239             L. You need to check the documentation on
240             how to specify options, but mainly each element is a pair of I
241             specification> and the I. For example:
242              
243             sub opt_spec {
244             my $self = shift;
245             return
246             [ 'latitude|y=s' => "geographical latitude" ],
247             [ 'longitude|x=s' => "geographical longitude" ],
248             ;
249             }
250              
251             The I
252             option can appear on the command-line, in its short or long version, if
253             it takes a value, how/if can be repeated, etc.
254              
255             The option elements can be richer. Another useful piece of the option
256             definition is its default value - see an example of it in
257             L.
258              
259             The example above, however, does not add anything new to the
260             L. Specifying the options this way, you could (and
261             probably should) inherit directly from the L without
262             using C. Therefore, let's have another example:
263              
264             sub opt_spec {
265             my $self = shift;
266             return
267             [ 'latitude|y=s' => "geographical latitude" ],
268             [ 'longitude|x=s' => "geographical longitude" ],
269             $self->composed_of (
270             'App::Cmdline::Options::Basic',
271             'App::Cmdline::Options::DB',
272             );
273             }
274              
275             In this example, your command-line application will recognize the same
276             options (latitude and longitude) as before and, additionally, all
277             options that were predefined in the I classes
278             L and L. See
279             more about these classes in L<"PREDEFINED SETS OF OPTIONS">;
280              
281             If not overridden, it returns an empty list.
282              
283             =head2 B
284              
285             The core method of this module. You call it with a list of names of
286             the classes that are able to give back a list of predefined options
287             that you may instantly use. The classes are not only specifying their
288             options but, for some options, they also B something. For example,
289             the C<-h> option (defined in L) prints
290             the usage and exits.
291              
292             This distribution contains few such classes (see the L<"PREDEFINED
293             SETS OF OPTIONS">). Later, they may be published other similar classes
294             providing different sets of options.
295              
296             The method returns a list of options definitions that is suitable
297             for including in the returned values of the L
298             method (as it was shown in the example above). The returned value
299             should always be used only at the end, after your application
300             specifies its own options (those that are not coming from any
301             predefined set). This is because the last element of the returned
302             list is a hashref containing configuration for the L -
303             as described in the L. Therefore, if you
304             need to call this method more than once or not at the end, perhaps
305             because you wish to see the options in the help usage in a different
306             order, you need to remove its last element before you add anything
307             after that:
308              
309             sub opt_spec {
310             my $self = shift;
311             my @db_options = $self->composed_of ('App::Cmdline::Options::DB');
312             pop @db_options;
313             return
314             @db_options,
315             [ 'latitude|y=s' => "geographical latitude" ],
316             [ 'longitude|x=s' => "geographical longitude" ],
317             $self->composed_of (
318             'App::Cmdline::Options::Basic',
319             );
320             }
321              
322             The last example looks a bit inconvenient. And you do not need to do
323             it that way - because the C method accepts also any
324             arrayrefs, ignoring them and just passing them to its return
325             value. That's why you really can call this method only once and not to
326             be bothered with the hashref at the end. Here is an example how you
327             can combine class names (predefined sets) with your own option
328             specification and/or usage separators (the empty arrayrefs):
329              
330             return
331             [ 'check|c' => "only check the configuration" ],
332             [],
333             $self->composed_of (
334             'App::Cmdline::Options::DB',
335             [ 'show|s' => "show database access properties" ],
336             [],
337             'App::Cmdline::Options::Basic',
338             );
339              
340             which - when called with the -h option - shows this nicely formatted
341             usage:
342              
343             Usage: myapp [short or long options, not bundled]
344             -c --check only check the configuration
345              
346             --dbname database name
347             --dbhost hostname hosting database
348             --dbport database port number
349             --dbuser user name to access database
350             --dbpasswd password to access database
351             --dbsocket UNIX socket accessing the database
352             -s --show show database access properties
353              
354             -h display a short usage message
355             -v --version display a version
356              
357             =head2 B
358              
359             When you are composing options from more sets, it is worth to check
360             whether, unintentionally, some options are not duplicated. It can be
361             done by this method that gets the list of options definitions, checks
362             it (warning if any duplicate was found, and returning the same list
363             unchanged. It can, therefore, be used like this:
364              
365             sub opt_spec {
366             my $self = shift;
367             return $self->check_for_duplicates (
368             [ 'latitude|y=s' => "geographical latitude" ],
369             [ 'longitude|x=s' => "geographical longitude" ],
370             $self->composed_of (
371             'App::Cmdline::Options::Basic',
372             'App::Cmdline::Options::DB',
373             )
374             );
375             }
376              
377             =head2 B
378              
379             The machinery behind the scene is done by the L
380             module. This module can be configured by a list of strings in order to
381             achieve a different interpretation of the command-line options. Such
382             as to treat them case-insensitively, or to allow them to be bundled
383             together. For the recognized strings you need to read the
384             L. Here is shown how and
385             when to use them.
386              
387             The C provides a default set of strings:
388              
389             sub getopt_conf {
390             return [
391             'no_bundling',
392             'no_ignore_case',
393             'auto_abbrev',
394             ];
395             }
396              
397             If you need it differently, override the getopt_conf method, returning
398             an arrayref with configuration strings you want. Here are the examples
399             showing the difference. Using the default configuration and having the
400             following options:
401              
402             sub opt_spec {
403             my $self = shift;
404             return
405             [ 'xpoint|x' => 'make an X point'],
406             [ 'ypoint|y' => 'make a Y point'],
407             [],
408             $self->composed_of (
409             'App::Cmdline::Options::Basic',
410             );
411             }
412              
413             I can run (and get dumped the recognized options and arguments in the
414             C method:
415              
416             senger@ShereKhan2:myapp -x -y
417             Executing...
418             Options ($opt): $VAR1 = bless( {
419             'xpoint' => 1,
420             'ypoint' => 1
421             }, 'Getopt::Long::Descriptive::Opts::__OPT__::2' );
422             Arguments ($args): $VAR1 = [];
423              
424             You can see that both options, C<-x> and C<-y>, were recognized. But
425             if I bundle them (and by default, the bundling is disabled), I get no
426             recognized options; instead they will be shown as arguments (arguments
427             being everything what remained not recognized on the command-line):
428              
429             senger@ShereKhan2:myapp -x -y
430             Executing...
431             Options ($opt): $VAR1 = bless( {}, 'Getopt::Long::Descriptive::Opts::__OPT__::2' );
432             Arguments ($args): $VAR1 = [ '-xy' ];
433              
434             But if I change the configuration by implementing:
435              
436             sub getopt_conf {
437             return [ 'bundling' ];
438             }
439              
440             the bundled options are now recognized as options (and no argument
441             reminded):
442              
443             senger@ShereKhan2:myapp -xy
444             Executing...
445             Options ($opt): $VAR1 = bless( {
446             'xpoint' => 1,
447             'ypoint' => 1
448             }, 'Getopt::Long::Descriptive::Opts::__OPT__::2' );
449             Arguments ($args): $VAR1 = [];
450              
451             =head2 B
452              
453             The returned value from this method will be used as the first line of
454             the usage message. The full usage is returned by another method,
455             C, that you usually do not overwrite because its default
456             behaviour is to create a reasonable summary from the help texts you
457             provided in the L method and, possibly, by this
458             C method.
459              
460             Behind the scene, the returned string is interpreted by the
461             L which accepts also few special
462             constructs:
463              
464             =over
465              
466             =item
467              
468             %c will be replaced with what C thinks is
469             the program name (it is computed from $0).
470              
471             =item
472              
473             %o will be replaced with a list of the short options, as well as the
474             text "[long options...]" if any have been defined.
475              
476             =item
477              
478             Literal % characters will need to be written as %%, just like with
479             sprintf.
480              
481             =back
482              
483             By default, the C returns slightly different usage
484             description depending on the bundling configuration option (see
485             L): if the bundling is disabled, the bundle
486             of all short options is not shown. Often, you want to use whatever
487             C returns plus what you wish to add on the first line of
488             the usage. For example:
489              
490             sub usage_desc {
491             return shift->SUPER::usage_desc() . ' ...and anything else';
492             }
493              
494             =head2 B
495              
496             Originally, this method was meant to check (validate) the command-line
497             arguments (remember that arguments are whatever remains on the
498             command-line after options defined in the L
499             method have been processed). The options themselves could be already
500             validated by various subroutines and attributes given in the option
501             specifications (as described, sometimes only vaguely, in the
502             L). But sometimes, it is useful to have all
503             validation, of options and of arguments, in one place - so we have
504             this method.
505              
506             The method gets two parameters, C<$opt> and C<$args>. The first one is
507             an instance of L giving you access to
508             all existing options, using their names (as were defined in
509             L) as the access methods. The second parameter is
510             an arrayref containing all remaining arguments on the command-line.
511              
512             I Some predefined sets of options (see the L<"PREDEFINED
513             SETS OF OPTIONS">) do also some checking (or other actions, like
514             printing the version and exiting) and this checking is invoked from
515             the C's validate_args method. Therefore, it is strongly
516             recommended that if you overwrite this method, you also call the SUPER:
517              
518             sub validate_args {
519             my ($self, $opt, $args) = @_;
520             $self->SUPER::validate_args ($opt, $args);
521             if ($opt->number and scalar @$args != $opt->number) {
522             $self->usage_error ("Option --number does not correspond with the number of arguments");
523             }
524             }
525              
526             senger@ShereKhan2:myapp -n 2 a b c
527             Error: Option --number does not correspond with the number of arguments
528             Usage: myapp [short or long options, not bundled]
529             -n --number expected number of args
530             -h display a short usage message
531             -v --version display a version
532              
533             The example also shows calling the method C. Unless you
534             overwrite also this method, it prints the given error message together
535             with the usage and dies.
536              
537             =head2 B
538              
539             Last but definitely not least. You B to implement this method
540             and put here whatever your command-line application is supposed to do.
541              
542             The method gets two parameters, C<$opt> and C<$args>. The first one is
543             an instance of L giving you access to
544             all existing options, using their names (as were defined in
545             L) as the access methods. The second parameter is
546             an arrayref containing all remaining arguments on the command-line.
547              
548             sub execute {
549             my ($self, $opt, $args) = @_;
550             if ($opt->crystal eq 'ball') {
551             print ask_ball ($args->[0]);
552             } else {
553             die "All is vanity...\n"
554             unless $opt->godess;
555             }
556             }
557              
558             =head1 PREDEFINED SETS OF OPTIONS
559              
560             The predefined sets of options are represented by classes that are
561             considered rather C. You do not extend them (inherit from them)
562             but you just use them (by naming them in the method
563             L).
564              
565             This distribution bundles several of such classes. See their own
566             documentation to find out what options they provide. Here is just a
567             quick summary:
568              
569             =over
570              
571             =item L
572              
573             Provides basic options (help and version).
574              
575             =item L
576              
577             Provides the same options as in L and
578             adds options for richer documentation.
579              
580             =item L
581              
582             Provides options for accessing a database (user authentication, host and
583             port name, etc.).
584              
585             =item L
586              
587             Provides the same options as in L and adds
588             an option for showing what values were given by the database-related
589             options.
590              
591             =back
592              
593             =head3 How to create a new predefined set
594              
595             You may wish to create a new set of options if you want to re-use
596             them. For application-specific options, used only once, you do not
597             need to have a predefined set, you just specify them directly in the
598             L method.
599              
600             The classes that can be used as the predefined sets of options do not
601             inherit from any common class (so far, there was no need for it) -
602             unless one extends another one (as is the case of
603             L). It is, however, recommended, to
604             use the namespace I - just to find them
605             easier on CPAN.
606              
607             Each of these classes should implement up to two methods:
608              
609             =over
610              
611             =item B
612              
613             Strictly speaking, it is not mandatory, but without this method the
614             class can hardly predefine any new options. The method should return
615             a list of arrayrefs, suitable to be consumed by the
616             L method. For example (taken from the
617             L):
618              
619             sub get_opt_spec {
620             return
621             [ 'h' => "display a short usage message" ],
622             [ 'version|v' => "display a version" ];
623             }
624              
625             =item B
626              
627             This method, if exists, will be called from the
628             L method. Its purpose is to do
629             something with the options belonging to (predefined by) this class.
630              
631             It gets four parameters, C<$app> (the class name of your application),
632             C<$caller> (who is calling), C<$opts> (an object allowing to access
633             all options) and C<$args> (an arrayref with the remaining arguments
634             from the command-line).
635              
636             If it finds an error, it usually dies by calling
637             $caller->C.
638              
639             =back
640              
641             =head1 AUTHOR
642              
643             Martin Senger
644              
645             =head1 COPYRIGHT AND LICENSE
646              
647             This software is copyright (c) 2013 by Martin Senger, CBRC - KAUST (Computational Biology Research Center - King Abdullah University of Science and Technology) All Rights Reserved.
648              
649             This is free software; you can redistribute it and/or modify it under
650             the same terms as the Perl 5 programming language system itself.
651              
652             =cut
653              
654              
655             __END__