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