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