2 package MooseX::Getopt;
4 our $VERSION = '0.150001';
5 our $AUTHORITY = 'cpan:STEVAN';
9 use Moose::Util::TypeConstraints;
11 use MooseX::Getopt::OptionTypeMap;
13 use MooseX::Getopt::Session;
15 use MooseX::Getopt::Meta::Attribute;
16 use MooseX::Getopt::Meta::Attribute::NoGetopt;
22 use constant _default_getopt_session => 'MooseX::Getopt::Session';
27 isa => 'MooseX::Getopt::Session',
28 metaclass => 'NoGetopt',
29 handles => [ 'ARGV', 'extra_argv' ],
33 sub new_with_options {
36 return $class->new( $class->get_options_from_argv(@_) );
40 sub get_options_from_argv {
44 "Single parameters to get_options_from_argv() must be a HASH ref"
45 ) if ref $_[0] and ref $_ ne 'HASH';
47 my %args = @_ == 1 ? %{ $_[0] } : @_;
49 my $getopt = defined $args{getopt}
51 : $class->_default_getopt_session->new(
52 classes_filter => sub { $_ eq $class },
55 # Combine explicit options and resend to session object
57 %{ $getopt->options }, # options from getopt session
58 $class->get_options_from_configfile, # options from --configfile
59 %args, # options from @_
61 $getopt->options( { %options } );
63 # Call Getopt parser only once.
64 $getopt->build_options if not $getopt->has_status;
66 # Combine final options
68 %options, # explicit options
69 %{ $getopt->options }, # options from CLI
70 getopt => $getopt, # session object itself
73 return wantarray ? %new_options : \%new_options;
77 sub get_options_from_configfile {
82 if ( $class->meta->does_role('MooseX::ConfigFromFile') ) {
86 my $opt_parser = Getopt::Long::Parser->new( config => ['pass_through'] );
87 $opt_parser->getoptions( "configfile=s" => \$configfile );
89 if ( not defined $configfile ) {
90 my $cfmeta = $class->meta->find_attribute_by_name('configfile');
91 $configfile = $cfmeta->default if $cfmeta->has_default;
94 if ( defined $configfile ) {
95 %options = %{ $class->get_config_from_file($configfile) };
99 return wantarray ? %options : \%options;
103 sub _compute_getopt_attrs {
107 $_->does('MooseX::Getopt::Meta::Attribute::Trait')
110 !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
111 } $class->meta->compute_all_applicable_attributes;
124 MooseX::Getopt - A Moose role for processing command line options
132 with 'MooseX::Getopt';
134 has 'out' => (is => 'rw', isa => 'Str', required => 1);
135 has 'in' => (is => 'rw', isa => 'Str', required => 1);
137 # ... rest of the class here
144 my $app = My::App->new_with_options();
145 # ... rest of the script here
147 ## on the command line
148 % perl my_app_script.pl -in file.input -out file.dump
152 This is a role which provides an alternate constructor for creating
153 objects using parameters passed in from the command line.
155 This module attempts to DWIM as much as possible with the command line
156 params by introspecting your class's attributes. It will use the name
157 of your attribute as the command line option, and if there is a type
158 constraint defined, it will configure Getopt::Long to handle the option
161 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait> or the
162 attribute metaclass L<MooseX::Getopt::Meta::Attribute> to get non-default
163 commandline option names and aliases.
165 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait::NoGetopt>
166 or the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetopt>
167 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
169 By default, attributes which start with an underscore are not given
170 commandline argument support, unless the attribute's metaclass is set
171 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
172 to have the leading underscore in thier name, you can do this:
174 # for read/write attributes
175 has '_foo' => (accessor => 'foo', ...);
177 # or for read-only attributes
178 has '_bar' => (reader => 'bar', ...);
180 This will mean that Getopt will not handle a --foo param, but your
181 code can still call the C<foo> method.
183 If your class also uses a configfile-loading role based on
184 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
185 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
186 specified by the C<--configfile> option (or the default you've
187 given for the configfile attribute) for you.
189 Options specified in multiple places follow the following
190 precendence order: commandline overrides configfile, which
191 overrides explicit new_with_options parameters.
193 =head2 Supported Type Constraints
199 A I<Bool> type constraint is set up as a boolean option with
200 Getopt::Long. So that this attribute description:
202 has 'verbose' => (is => 'rw', isa => 'Bool');
204 would translate into C<verbose!> as a Getopt::Long option descriptor,
205 which would enable the following command line options:
207 % my_script.pl --verbose
208 % my_script.pl --noverbose
210 =item I<Int>, I<Float>, I<Str>
212 These type constraints are set up as properly typed options with
213 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
215 =item I<Defined|Int>, I<Defined|Float>, I<Defined|Str>
217 These type constaints are set up as properly typed options with
218 Getopt::Long, using the C<:i>, C<:f> and C<:s> modifiers as appropriate.
222 An I<ArrayRef> type constraint is set up as a multiple value option
223 in Getopt::Long. So that this attribute description:
228 default => sub { [] }
231 would translate into C<includes=s@> as a Getopt::Long option descriptor,
232 which would enable the following command line options:
234 % my_script.pl --include /usr/lib --include /usr/local/lib
238 A I<HashRef> type constraint is set up as a hash value option
239 in Getopt::Long. So that this attribute description:
244 default => sub { {} }
247 would translate into C<define=s%> as a Getopt::Long option descriptor,
248 which would enable the following command line options:
250 % my_script.pl --define os=linux --define vendor=debian
254 =head2 Custom Type Constraints
256 It is possible to create custom type constraint to option spec
257 mappings if you need them. The process is fairly simple (but a
258 little verbose maybe). First you create a custom subtype, like
261 subtype 'ArrayOfInts'
263 => where { scalar (grep { looks_like_number($_) } @$_) };
265 Then you register the mapping, like so:
267 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
268 'ArrayOfInts' => '=i@'
271 Now any attribute declarations using this type constraint will
272 get the custom option spec. So that, this:
276 isa => 'ArrayOfInts',
277 default => sub { [0] }
280 Will translate to the following on the command line:
282 % my_script.pl --nums 5 --nums 88 --nums 199
284 This example is fairly trivial, but more complex validations are
285 easily possible with a little creativity. The trick is balancing
286 the type constraint validations with the Getopt::Long validations.
288 Better examples are certainly welcome :)
290 =head2 Inferred Type Constraints
292 If you define a custom subtype which is a subtype of one of the
293 standard L</Supported Type Constraints> above, and do not explicitly
294 provide custom support as in L</Custom Type Constraints> above,
295 MooseX::Getopt will treat it like the parent type for Getopt
298 For example, if you had the same custom C<ArrayOfInts> subtype
299 from the examples above, but did not add a new custom option
300 type for it to the C<OptionTypeMap>, it would be treated just
301 like a normal C<ArrayRef> type for Getopt purposes (that is,
306 L<MooseX::Getopt> can handle more than one class which contain
307 attributes filled from CLI. In this case, you need to use explicite
308 L<MooseX::Getopt::Session> object and then the Getopt attributes will be
309 searched in any class which does L<MooseX::Getopt>.
313 with 'MooseX::Getopt';
314 has 'send' => (is => 'rw', predicate => 'has_send');
316 package My::App::Send;
318 with 'MooseX::Getopt';
319 has 'to' => (is => 'rw', isa => 'Str', default => 'localhost');
320 sub send { my $self = shift; warn "Sending mail to ", $self->to; }
322 # ... rest of the class here
327 my $getopt = MooseX::Getopt::Session->new;
329 my $app = My::App->new_with_options( getopt => $getopt );
330 if ($app->has_send) {
331 # Use the same command line
332 my $sender = My::App::Send->new_with_options( getopt => $getopt );
335 # ... rest of the script here
337 ## on the command line
338 % perl my_app_script.pl --send --to server.example.net
344 =item B<new_with_options (%params)>
346 This method will take a set of default C<%params> and then collect
347 params from the command line (possibly overriding those in C<%params>)
348 and then return a newly constructed object.
350 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
351 C<new_with_options> will throw an exception.
353 If you have L<Getopt::Long::Descriptive> a the C<usage> param is also passed to
356 =item B<get_options_from_argv (%params)>
358 This method returns the list of parameters collected from command line
359 without creating the new object.
361 =item B<get_options_from_configfile>
363 This method returns the list of parameters collected with
364 L<MooseX::ConfigFromFile> mechanism.
368 This accessor contains a reference to a copy of the C<@ARGV> array as it
369 originally existed at the time of C<new_with_options>.
371 The C<ARGV> is delegated from L<MooseX::Getopt::Session> object.
375 This accessor contains an arrayref of leftover C<@ARGV> elements that
376 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
379 The C<extra_argv> is delegated from L<MooseX::Getopt::Session> object.
383 This accessor contains a L<MooseX::Getopt::Session> object. This object can
384 be shared between more than one class which does L<MooseX::Getopt>. The new
385 object is created by default.
389 This returns the role meta object.
397 =item L<MooseX::Getopt::Strict>
399 =item L<MooseX::Getopt::Session>
401 =item L<MooseX::Getopt::Parser>
407 All complex software has bugs lurking in it, and this module is no
408 exception. If you find a bug please either email me, or add the bug
413 Stevan Little E<lt>stevan@iinteractive.comE<gt>
415 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
417 Yuval Kogman, E<lt>nothingmuch@woobling.orgE<gt>
419 Piotr Roszatycki, E<lt>dexter@cpan.orgE<gt>
423 Ryan D Johnson, E<lt>ryan@innerfence.comE<gt>
425 =head1 COPYRIGHT AND LICENSE
427 Copyright 2007-2008 by Infinity Interactive, Inc.
429 L<http://www.iinteractive.com>
431 This library is free software; you can redistribute it and/or modify
432 it under the same terms as Perl itself.