2 package MooseX::Getopt;
5 use Moose::Util::TypeConstraints;
7 use MooseX::Getopt::OptionTypeMap;
9 use MooseX::Getopt::Session;
11 use MooseX::Getopt::Meta::Attribute;
12 use MooseX::Getopt::Meta::Attribute::NoGetopt;
15 our $VERSION = '0.15';
16 our $AUTHORITY = 'cpan:STEVAN';
19 use constant _default_getopt_session => 'MooseX::Getopt::Session';
24 isa => 'MooseX::Getopt::Session',
25 metaclass => 'NoGetopt',
26 handles => [ 'ARGV', 'extra_argv' ],
30 sub new_with_options {
33 return $class->new( $class->get_options_from_argv(@_) );
37 sub get_options_from_argv {
40 Moose->throw_error("Single parameters to get_options_from_argv() must be a HASH ref")
41 if ref $_[0] and ref $_ ne 'HASH';
43 my %params = ( $class->_get_options_from_configfile, @_ == 1 ? %{ $_[0] } : @_ );
45 my $getopt = defined $params{getopt}
47 : $class->_default_getopt_session->new(
48 classes_filter => sub { $_ eq $class },
53 %{ $getopt->params }, # params from session object
54 %params, # explicit params to ->new
55 %{ $getopt->options }, # params from CLI
63 sub _get_options_from_configfile {
68 if ($class->meta->does_role('MooseX::ConfigFromFile')) {
72 my $opt_parser = Getopt::Long::Parser->new( config => [ 'pass_through' ] );
73 $opt_parser->getoptions( "configfile=s" => \$configfile );
75 if (not defined $configfile) {
76 my $cfmeta = $class->meta->find_attribute_by_name('configfile');
77 $configfile = $cfmeta->default if $cfmeta->has_default;
80 if (defined $configfile) {
81 %params = %{ $class->get_config_from_file($configfile) };
89 sub _compute_getopt_attrs {
93 $_->does('MooseX::Getopt::Meta::Attribute::Trait')
97 !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
98 } $class->meta->compute_all_applicable_attributes;
110 MooseX::Getopt - A Moose role for processing command line options
118 with 'MooseX::Getopt';
120 has 'out' => (is => 'rw', isa => 'Str', required => 1);
121 has 'in' => (is => 'rw', isa => 'Str', required => 1);
123 # ... rest of the class here
130 my $app = My::App->new_with_options();
131 # ... rest of the script here
133 ## on the command line
134 % perl my_app_script.pl -in file.input -out file.dump
138 This is a role which provides an alternate constructor for creating
139 objects using parameters passed in from the command line.
141 This module attempts to DWIM as much as possible with the command line
142 params by introspecting your class's attributes. It will use the name
143 of your attribute as the command line option, and if there is a type
144 constraint defined, it will configure Getopt::Long to handle the option
147 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait> or the
148 attribute metaclass L<MooseX::Getopt::Meta::Attribute> to get non-default
149 commandline option names and aliases.
151 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait::NoGetopt>
152 or the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetopt>
153 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
155 By default, attributes which start with an underscore are not given
156 commandline argument support, unless the attribute's metaclass is set
157 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
158 to have the leading underscore in thier name, you can do this:
160 # for read/write attributes
161 has '_foo' => (accessor => 'foo', ...);
163 # or for read-only attributes
164 has '_bar' => (reader => 'bar', ...);
166 This will mean that Getopt will not handle a --foo param, but your
167 code can still call the C<foo> method.
169 If your class also uses a configfile-loading role based on
170 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
171 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
172 specified by the C<--configfile> option (or the default you've
173 given for the configfile attribute) for you.
175 Options specified in multiple places follow the following
176 precendence order: commandline overrides configfile, which
177 overrides explicit new_with_options parameters.
179 =head2 Supported Type Constraints
185 A I<Bool> type constraint is set up as a boolean option with
186 Getopt::Long. So that this attribute description:
188 has 'verbose' => (is => 'rw', isa => 'Bool');
190 would translate into C<verbose!> as a Getopt::Long option descriptor,
191 which would enable the following command line options:
193 % my_script.pl --verbose
194 % my_script.pl --noverbose
196 =item I<Int>, I<Float>, I<Str>
198 These type constraints are set up as properly typed options with
199 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
203 An I<ArrayRef> type constraint is set up as a multiple value option
204 in Getopt::Long. So that this attribute description:
209 default => sub { [] }
212 would translate into C<includes=s@> as a Getopt::Long option descriptor,
213 which would enable the following command line options:
215 % my_script.pl --include /usr/lib --include /usr/local/lib
219 A I<HashRef> type constraint is set up as a hash value option
220 in Getopt::Long. So that this attribute description:
225 default => sub { {} }
228 would translate into C<define=s%> as a Getopt::Long option descriptor,
229 which would enable the following command line options:
231 % my_script.pl --define os=linux --define vendor=debian
235 =head2 Custom Type Constraints
237 It is possible to create custom type constraint to option spec
238 mappings if you need them. The process is fairly simple (but a
239 little verbose maybe). First you create a custom subtype, like
242 subtype 'ArrayOfInts'
244 => where { scalar (grep { looks_like_number($_) } @$_) };
246 Then you register the mapping, like so:
248 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
249 'ArrayOfInts' => '=i@'
252 Now any attribute declarations using this type constraint will
253 get the custom option spec. So that, this:
257 isa => 'ArrayOfInts',
258 default => sub { [0] }
261 Will translate to the following on the command line:
263 % my_script.pl --nums 5 --nums 88 --nums 199
265 This example is fairly trivial, but more complex validations are
266 easily possible with a little creativity. The trick is balancing
267 the type constraint validations with the Getopt::Long validations.
269 Better examples are certainly welcome :)
271 =head2 Inferred Type Constraints
273 If you define a custom subtype which is a subtype of one of the
274 standard L</Supported Type Constraints> above, and do not explicitly
275 provide custom support as in L</Custom Type Constraints> above,
276 MooseX::Getopt will treat it like the parent type for Getopt
279 For example, if you had the same custom C<ArrayOfInts> subtype
280 from the examples above, but did not add a new custom option
281 type for it to the C<OptionTypeMap>, it would be treated just
282 like a normal C<ArrayRef> type for Getopt purposes (that is,
287 L<MooseX::Getopt> can handle more than one class which contain
288 attributes filled from CLI. In this case, you need to use explicite
289 L<MooseX::Getopt::Session> object and then the Getopt attributes will be
290 searched in any class which does L<MooseX::Getopt>.
294 with 'MooseX::Getopt';
295 has 'send' => (is => 'rw', predicate => 'has_send');
297 package My::App::Send;
299 with 'MooseX::Getopt';
300 has 'to' => (is => 'rw', isa => 'Str', default => 'localhost');
301 sub send { my $self = shift; warn "Sending mail to ", $self->to; }
303 # ... rest of the class here
308 my $getopt = MooseX::Getopt::Session->new;
310 my $app = My::App->new_with_options( getopt => $getopt );
311 if ($app->has_send) {
312 # Use the same command line
313 my $sender = My::App::Send->new_with_options( getopt => $getopt );
316 # ... rest of the script here
318 ## on the command line
319 % perl my_app_script.pl --send --to server.example.net
325 =item B<new_with_options (%params)>
327 This method will take a set of default C<%params> and then collect
328 params from the command line (possibly overriding those in C<%params>)
329 and then return a newly constructed object.
331 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
332 C<new_with_options> will throw an exception.
334 If you have L<Getopt::Long::Descriptive> a the C<usage> param is also passed to
337 =item B<get_options_from_argv (%params)>
339 This method returns the list of parameters collected from command line
340 without creating the new object.
344 This accessor contains a reference to a copy of the C<@ARGV> array as it
345 originally existed at the time of C<new_with_options>.
347 The C<ARGV> is delegated from L<MooseX::Getopt::Session> object.
351 This accessor contains an arrayref of leftover C<@ARGV> elements that
352 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
355 The C<extra_argv> is delegated from L<MooseX::Getopt::Session> object.
359 This accessor contains a L<MooseX::Getopt::Session> object. This object can
360 be shared between more than one class which does L<MooseX::Getopt>. The new
361 object is created by default.
365 This returns the role meta object.
373 =item L<MooseX::Getopt::Strict>
375 =item L<MooseX::Getopt::Session>
377 =item L<MooseX::Getopt::Parser>
383 All complex software has bugs lurking in it, and this module is no
384 exception. If you find a bug please either email me, or add the bug
389 Stevan Little E<lt>stevan@iinteractive.comE<gt>
391 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
393 Yuval Kogman, E<lt>nothingmuch@woobling.orgE<gt>
397 Ryan D Johnson, E<lt>ryan@innerfence.comE<gt>
399 Piotr Roszatycki, E<lt>dexter@cpan.orgE<gt>
401 =head1 COPYRIGHT AND LICENSE
403 Copyright 2007-2008 by Infinity Interactive, Inc.
405 L<http://www.iinteractive.com>
407 This library is free software; you can redistribute it and/or modify
408 it under the same terms as Perl itself.