27c17c8496eefd2e71629aa0d9969a12d20619af
[gitmo/MooseX-Getopt.git] / lib / MooseX / Getopt.pm
1
2 package MooseX::Getopt;
3 use Moose::Role;
4
5 use Moose::Util::TypeConstraints;
6
7 use MooseX::Getopt::OptionTypeMap;
8
9 use MooseX::Getopt::Session;
10
11 use MooseX::Getopt::Meta::Attribute;
12 use MooseX::Getopt::Meta::Attribute::NoGetopt;
13
14
15 our $VERSION   = '0.15';
16 our $AUTHORITY = 'cpan:STEVAN';
17
18
19 use constant _default_getopt_session => 'MooseX::Getopt::Session';
20
21
22 has getopt => (
23     is => 'rw',
24     isa => 'MooseX::Getopt::Session',
25     metaclass => 'NoGetopt',
26     handles => [ 'ARGV', 'extra_argv' ],
27 );
28
29
30 sub new_with_options {
31     my $class = shift;
32
33     return $class->new( $class->get_options_from_argv(@_) );
34 };
35
36
37 sub get_options_from_argv {
38     my $class = shift;
39
40     Moose->throw_error("Single parameters to get_options_from_argv() must be a HASH ref")
41         if ref $_[0] and ref $_ ne 'HASH';
42
43     my %params = ( $class->_get_options_from_configfile, @_ == 1 ? %{ $_[0] } : @_ );
44
45     my $getopt = defined $params{getopt}
46                  ? $params{getopt}
47                  : $class->_default_getopt_session->new(
48                        classes_filter => sub { $_ eq $class },
49                        params => \%params,
50                    );
51
52     my %new_params = (
53         %{ $getopt->params },                   # params from session object
54         %params,                                # explicit params to ->new
55         %{ $getopt->options },                  # params from CLI
56         getopt => $getopt,
57     );
58
59     return %new_params;
60 };
61
62
63 sub _get_options_from_configfile {
64     my $class = shift;
65
66     my %params = ();
67
68     if ($class->meta->does_role('MooseX::ConfigFromFile')) {
69         local @ARGV = @ARGV;
70
71         my $configfile;
72         my $opt_parser = Getopt::Long::Parser->new( config => [ 'pass_through' ] );
73         $opt_parser->getoptions( "configfile=s" => \$configfile );
74
75         if (not defined $configfile) {
76             my $cfmeta = $class->meta->find_attribute_by_name('configfile');
77             $configfile = $cfmeta->default if $cfmeta->has_default;
78         };
79
80         if (defined $configfile) {
81             %params = %{ $class->get_config_from_file($configfile) };
82         };
83     };
84
85     return %params;
86 };
87
88
89 sub _compute_getopt_attrs {
90     my $class = shift;
91
92     return grep {
93         $_->does('MooseX::Getopt::Meta::Attribute::Trait')
94             or
95         $_->name !~ /^_/
96     } grep {
97         !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
98     } $class->meta->compute_all_applicable_attributes;
99 };
100
101
102 no Moose::Role; 1;
103
104 __END__
105
106 =pod
107
108 =head1 NAME
109
110 MooseX::Getopt - A Moose role for processing command line options
111
112 =head1 SYNOPSIS
113
114   ## In your class
115   package My::App;
116   use Moose;
117
118   with 'MooseX::Getopt';
119
120   has 'out' => (is => 'rw', isa => 'Str', required => 1);
121   has 'in'  => (is => 'rw', isa => 'Str', required => 1);
122
123   # ... rest of the class here
124
125   ## in your script
126   #!/usr/bin/perl
127
128   use My::App;
129
130   my $app = My::App->new_with_options();
131   # ... rest of the script here
132
133   ## on the command line
134   % perl my_app_script.pl -in file.input -out file.dump
135
136 =head1 DESCRIPTION
137
138 This is a role which provides an alternate constructor for creating
139 objects using parameters passed in from the command line.
140
141 This module attempts to DWIM as much as possible with the command line
142 params by introspecting your class's attributes. It will use the name
143 of your attribute as the command line option, and if there is a type
144 constraint defined, it will configure Getopt::Long to handle the option
145 accordingly.
146
147 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait> or the
148 attribute metaclass L<MooseX::Getopt::Meta::Attribute> to get non-default
149 commandline option names and aliases.
150
151 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait::NoGetopt>
152 or the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetopt>
153 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
154
155 By default, attributes which start with an underscore are not given
156 commandline argument support, unless the attribute's metaclass is set
157 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
158 to have the leading underscore in thier name, you can do this:
159
160   # for read/write attributes
161   has '_foo' => (accessor => 'foo', ...);
162
163   # or for read-only attributes
164   has '_bar' => (reader => 'bar', ...);
165
166 This will mean that Getopt will not handle a --foo param, but your
167 code can still call the C<foo> method.
168
169 If your class also uses a configfile-loading role based on
170 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
171 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
172 specified by the C<--configfile> option (or the default you've
173 given for the configfile attribute) for you.
174
175 Options specified in multiple places follow the following
176 precendence order: commandline overrides configfile, which
177 overrides explicit new_with_options parameters.
178
179 =head2 Supported Type Constraints
180
181 =over 4
182
183 =item I<Bool>
184
185 A I<Bool> type constraint is set up as a boolean option with
186 Getopt::Long. So that this attribute description:
187
188   has 'verbose' => (is => 'rw', isa => 'Bool');
189
190 would translate into C<verbose!> as a Getopt::Long option descriptor,
191 which would enable the following command line options:
192
193   % my_script.pl --verbose
194   % my_script.pl --noverbose
195
196 =item I<Int>, I<Float>, I<Str>
197
198 These type constraints are set up as properly typed options with
199 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
200
201 =item I<ArrayRef>
202
203 An I<ArrayRef> type constraint is set up as a multiple value option
204 in Getopt::Long. So that this attribute description:
205
206   has 'include' => (
207       is      => 'rw',
208       isa     => 'ArrayRef',
209       default => sub { [] }
210   );
211
212 would translate into C<includes=s@> as a Getopt::Long option descriptor,
213 which would enable the following command line options:
214
215   % my_script.pl --include /usr/lib --include /usr/local/lib
216
217 =item I<HashRef>
218
219 A I<HashRef> type constraint is set up as a hash value option
220 in Getopt::Long. So that this attribute description:
221
222   has 'define' => (
223       is      => 'rw',
224       isa     => 'HashRef',
225       default => sub { {} }
226   );
227
228 would translate into C<define=s%> as a Getopt::Long option descriptor,
229 which would enable the following command line options:
230
231   % my_script.pl --define os=linux --define vendor=debian
232
233 =back
234
235 =head2 Custom Type Constraints
236
237 It is possible to create custom type constraint to option spec
238 mappings if you need them. The process is fairly simple (but a
239 little verbose maybe). First you create a custom subtype, like
240 so:
241
242   subtype 'ArrayOfInts'
243       => as 'ArrayRef'
244       => where { scalar (grep { looks_like_number($_) } @$_)  };
245
246 Then you register the mapping, like so:
247
248   MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
249       'ArrayOfInts' => '=i@'
250   );
251
252 Now any attribute declarations using this type constraint will
253 get the custom option spec. So that, this:
254
255   has 'nums' => (
256       is      => 'ro',
257       isa     => 'ArrayOfInts',
258       default => sub { [0] }
259   );
260
261 Will translate to the following on the command line:
262
263   % my_script.pl --nums 5 --nums 88 --nums 199
264
265 This example is fairly trivial, but more complex validations are
266 easily possible with a little creativity. The trick is balancing
267 the type constraint validations with the Getopt::Long validations.
268
269 Better examples are certainly welcome :)
270
271 =head2 Inferred Type Constraints
272
273 If you define a custom subtype which is a subtype of one of the
274 standard L</Supported Type Constraints> above, and do not explicitly
275 provide custom support as in L</Custom Type Constraints> above,
276 MooseX::Getopt will treat it like the parent type for Getopt
277 purposes.
278
279 For example, if you had the same custom C<ArrayOfInts> subtype
280 from the examples above, but did not add a new custom option
281 type for it to the C<OptionTypeMap>, it would be treated just
282 like a normal C<ArrayRef> type for Getopt purposes (that is,
283 C<=s@>).
284
285 =head2 Session
286
287 L<MooseX::Getopt> can handle more than one class which contain
288 attributes filled from CLI.  In this case, you need to use explicite
289 L<MooseX::Getopt::Session> object and then the Getopt attributes will be
290 searched in any class which does L<MooseX::Getopt>.
291
292   package My::App;
293   use Moose;
294   with 'MooseX::Getopt';
295   has 'send' => (is => 'rw', predicate => 'has_send');
296
297   package My::App::Send;
298   use Moose;
299   with 'MooseX::Getopt';
300   has 'to' => (is => 'rw', isa => 'Str', default => 'localhost');
301   sub send { my $self = shift; warn "Sending mail to ", $self->to; }
302
303   # ... rest of the class here
304
305   ## in your script
306   #!/usr/bin/perl
307
308   my $getopt = MooseX::Getopt::Session->new;
309
310   my $app = My::App->new_with_options( getopt => $getopt );
311   if ($app->has_send) {
312       # Use the same command line
313       my $sender = My::App::Send->new_with_options( getopt => $getopt );
314       $sender->send;
315   }
316   # ... rest of the script here
317
318   ## on the command line
319   % perl my_app_script.pl --send --to server.example.net
320
321 =head1 METHODS
322
323 =over 4
324
325 =item B<new_with_options (%params)>
326
327 This method will take a set of default C<%params> and then collect
328 params from the command line (possibly overriding those in C<%params>)
329 and then return a newly constructed object.
330
331 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
332 C<new_with_options> will throw an exception.
333
334 If you have L<Getopt::Long::Descriptive> a the C<usage> param is also passed to
335 C<new>.
336
337 =item B<get_options_from_argv (%params)>
338
339 This method returns the list of parameters collected from command line
340 without creating the new object.
341
342 =item B<ARGV>
343
344 This accessor contains a reference to a copy of the C<@ARGV> array as it
345 originally existed at the time of C<new_with_options>.
346
347 The C<ARGV> is delegated from L<MooseX::Getopt::Session> object.
348
349 =item B<extra_argv>
350
351 This accessor contains an arrayref of leftover C<@ARGV> elements that
352 L<Getopt::Long> did not parse.  Note that the real C<@ARGV> is left
353 un-mangled.
354
355 The C<extra_argv> is delegated from L<MooseX::Getopt::Session> object.
356
357 =item B<getopt>
358
359 This accessor contains a L<MooseX::Getopt::Session> object.  This object can
360 be shared between more than one class which does L<MooseX::Getopt>.  The new
361 object is created by default.
362
363 =item B<meta>
364
365 This returns the role meta object.
366
367 =back
368
369 =head1 SEE ALSO
370
371 =over 4
372
373 =item L<MooseX::Getopt::Strict>
374
375 =item L<MooseX::Getopt::Session>
376
377 =item L<MooseX::Getopt::Parser>
378
379 =back
380
381 =head1 BUGS
382
383 All complex software has bugs lurking in it, and this module is no
384 exception. If you find a bug please either email me, or add the bug
385 to cpan-RT.
386
387 =head1 AUTHOR
388
389 Stevan Little E<lt>stevan@iinteractive.comE<gt>
390
391 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
392
393 Yuval Kogman, E<lt>nothingmuch@woobling.orgE<gt>
394
395 =head1 CONTRIBUTORS
396
397 Ryan D Johnson, E<lt>ryan@innerfence.comE<gt>
398
399 Piotr Roszatycki, E<lt>dexter@cpan.orgE<gt>
400
401 =head1 COPYRIGHT AND LICENSE
402
403 Copyright 2007-2008 by Infinity Interactive, Inc.
404
405 L<http://www.iinteractive.com>
406
407 This library is free software; you can redistribute it and/or modify
408 it under the same terms as Perl itself.
409
410 =cut