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