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