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 $options = { %{ $class->get_options_from_configfile }, @_ == 1 ? %{ $_[0] } : @_ };
45 my $getopt = defined $options->{getopt}
47 : $class->_default_getopt_session->new(
48 classes_filter => sub { $_ eq $class },
53 %{ $options }, # explicit options to ->new
54 %{ $getopt->options }, # options from CLI
62 sub get_options_from_configfile {
67 if ($class->meta->does_role('MooseX::ConfigFromFile')) {
71 my $opt_parser = Getopt::Long::Parser->new( config => [ 'pass_through' ] );
72 $opt_parser->getoptions( "configfile=s" => \$configfile );
74 if (not defined $configfile) {
75 my $cfmeta = $class->meta->find_attribute_by_name('configfile');
76 $configfile = $cfmeta->default if $cfmeta->has_default;
79 if (defined $configfile) {
80 $options = $class->get_config_from_file($configfile);
88 sub _compute_getopt_attrs {
92 $_->does('MooseX::Getopt::Meta::Attribute::Trait')
96 !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
97 } $class->meta->compute_all_applicable_attributes;
109 MooseX::Getopt - A Moose role for processing command line options
117 with 'MooseX::Getopt';
119 has 'out' => (is => 'rw', isa => 'Str', required => 1);
120 has 'in' => (is => 'rw', isa => 'Str', required => 1);
122 # ... rest of the class here
129 my $app = My::App->new_with_options();
130 # ... rest of the script here
132 ## on the command line
133 % perl my_app_script.pl -in file.input -out file.dump
137 This is a role which provides an alternate constructor for creating
138 objects using parameters passed in from the command line.
140 This module attempts to DWIM as much as possible with the command line
141 params by introspecting your class's attributes. It will use the name
142 of your attribute as the command line option, and if there is a type
143 constraint defined, it will configure Getopt::Long to handle the option
146 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait> or the
147 attribute metaclass L<MooseX::Getopt::Meta::Attribute> to get non-default
148 commandline option names and aliases.
150 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait::NoGetopt>
151 or the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetopt>
152 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
154 By default, attributes which start with an underscore are not given
155 commandline argument support, unless the attribute's metaclass is set
156 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
157 to have the leading underscore in thier name, you can do this:
159 # for read/write attributes
160 has '_foo' => (accessor => 'foo', ...);
162 # or for read-only attributes
163 has '_bar' => (reader => 'bar', ...);
165 This will mean that Getopt will not handle a --foo param, but your
166 code can still call the C<foo> method.
168 If your class also uses a configfile-loading role based on
169 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
170 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
171 specified by the C<--configfile> option (or the default you've
172 given for the configfile attribute) for you.
174 Options specified in multiple places follow the following
175 precendence order: commandline overrides configfile, which
176 overrides explicit new_with_options parameters.
178 =head2 Supported Type Constraints
184 A I<Bool> type constraint is set up as a boolean option with
185 Getopt::Long. So that this attribute description:
187 has 'verbose' => (is => 'rw', isa => 'Bool');
189 would translate into C<verbose!> as a Getopt::Long option descriptor,
190 which would enable the following command line options:
192 % my_script.pl --verbose
193 % my_script.pl --noverbose
195 =item I<Int>, I<Float>, I<Str>
197 These type constraints are set up as properly typed options with
198 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
202 An I<ArrayRef> type constraint is set up as a multiple value option
203 in Getopt::Long. So that this attribute description:
208 default => sub { [] }
211 would translate into C<includes=s@> as a Getopt::Long option descriptor,
212 which would enable the following command line options:
214 % my_script.pl --include /usr/lib --include /usr/local/lib
218 A I<HashRef> type constraint is set up as a hash value option
219 in Getopt::Long. So that this attribute description:
224 default => sub { {} }
227 would translate into C<define=s%> as a Getopt::Long option descriptor,
228 which would enable the following command line options:
230 % my_script.pl --define os=linux --define vendor=debian
234 =head2 Custom Type Constraints
236 It is possible to create custom type constraint to option spec
237 mappings if you need them. The process is fairly simple (but a
238 little verbose maybe). First you create a custom subtype, like
241 subtype 'ArrayOfInts'
243 => where { scalar (grep { looks_like_number($_) } @$_) };
245 Then you register the mapping, like so:
247 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
248 'ArrayOfInts' => '=i@'
251 Now any attribute declarations using this type constraint will
252 get the custom option spec. So that, this:
256 isa => 'ArrayOfInts',
257 default => sub { [0] }
260 Will translate to the following on the command line:
262 % my_script.pl --nums 5 --nums 88 --nums 199
264 This example is fairly trivial, but more complex validations are
265 easily possible with a little creativity. The trick is balancing
266 the type constraint validations with the Getopt::Long validations.
268 Better examples are certainly welcome :)
270 =head2 Inferred Type Constraints
272 If you define a custom subtype which is a subtype of one of the
273 standard L</Supported Type Constraints> above, and do not explicitly
274 provide custom support as in L</Custom Type Constraints> above,
275 MooseX::Getopt will treat it like the parent type for Getopt
278 For example, if you had the same custom C<ArrayOfInts> subtype
279 from the examples above, but did not add a new custom option
280 type for it to the C<OptionTypeMap>, it would be treated just
281 like a normal C<ArrayRef> type for Getopt purposes (that is,
286 L<MooseX::Getopt> can handle more than one class which contain
287 attributes filled from CLI. In this case, you need to use explicite
288 L<MooseX::Getopt::Session> object and then the Getopt attributes will be
289 searched in any class which does L<MooseX::Getopt>.
293 with 'MooseX::Getopt';
294 has 'send' => (is => 'rw', predicate => 'has_send');
296 package My::App::Send;
298 with 'MooseX::Getopt';
299 has 'to' => (is => 'rw', isa => 'Str', default => 'localhost');
300 sub send { my $self = shift; warn "Sending mail to ", $self->to; }
302 # ... rest of the class here
307 my $getopt = MooseX::Getopt::Session->new;
309 my $app = My::App->new_with_options( getopt => $getopt );
310 if ($app->has_send) {
311 # Use the same command line
312 my $sender = My::App::Send->new_with_options( getopt => $getopt );
315 # ... rest of the script here
317 ## on the command line
318 % perl my_app_script.pl --send --to server.example.net
324 =item B<new_with_options (%params)>
326 This method will take a set of default C<%params> and then collect
327 params from the command line (possibly overriding those in C<%params>)
328 and then return a newly constructed object.
330 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
331 C<new_with_options> will throw an exception.
333 If you have L<Getopt::Long::Descriptive> a the C<usage> param is also passed to
336 =item B<get_options_from_argv (%params)>
338 This method returns the list of parameters collected from command line
339 without creating the new object.
341 =item B<get_options_from_configfile>
343 This method returns the list of parameters collected with
344 L<MooseX::ConfigFromFile> mechanism.
348 This accessor contains a reference to a copy of the C<@ARGV> array as it
349 originally existed at the time of C<new_with_options>.
351 The C<ARGV> is delegated from L<MooseX::Getopt::Session> object.
355 This accessor contains an arrayref of leftover C<@ARGV> elements that
356 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
359 The C<extra_argv> is delegated from L<MooseX::Getopt::Session> object.
363 This accessor contains a L<MooseX::Getopt::Session> object. This object can
364 be shared between more than one class which does L<MooseX::Getopt>. The new
365 object is created by default.
369 This returns the role meta object.
377 =item L<MooseX::Getopt::Strict>
379 =item L<MooseX::Getopt::Session>
381 =item L<MooseX::Getopt::Parser>
387 All complex software has bugs lurking in it, and this module is no
388 exception. If you find a bug please either email me, or add the bug
393 Stevan Little E<lt>stevan@iinteractive.comE<gt>
395 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
397 Yuval Kogman, E<lt>nothingmuch@woobling.orgE<gt>
401 Ryan D Johnson, E<lt>ryan@innerfence.comE<gt>
403 Piotr Roszatycki, E<lt>dexter@cpan.orgE<gt>
405 =head1 COPYRIGHT AND LICENSE
407 Copyright 2007-2008 by Infinity Interactive, Inc.
409 L<http://www.iinteractive.com>
411 This library is free software; you can redistribute it and/or modify
412 it under the same terms as Perl itself.