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