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 Moose->throw_error("Single parameters to new_with_options() must be a HASH ref")
34 if ref $_[0] and ref $_ ne 'HASH';
36 my %params = ( @_ == 1 ? %{ $_[0] } : @_ );
38 my $getopt = defined $params{getopt}
40 : $class->_default_getopt_session->new(
41 classes_filter => sub { $_ eq $class },
47 %{ $getopt->params }, # params from session object
48 %params, # explicit params to ->new
49 %{ $getopt->options }, # params from CLI
54 sub _compute_getopt_attrs {
58 $_->does('MooseX::Getopt::Meta::Attribute::Trait')
62 !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
63 } $class->meta->compute_all_applicable_attributes;
75 MooseX::Getopt - A Moose role for processing command line options
83 with 'MooseX::Getopt';
85 has 'out' => (is => 'rw', isa => 'Str', required => 1);
86 has 'in' => (is => 'rw', isa => 'Str', required => 1);
88 # ... rest of the class here
95 my $app = My::App->new_with_options();
96 # ... rest of the script here
98 ## on the command line
99 % perl my_app_script.pl -in file.input -out file.dump
103 This is a role which provides an alternate constructor for creating
104 objects using parameters passed in from the command line.
106 This module attempts to DWIM as much as possible with the command line
107 params by introspecting your class's attributes. It will use the name
108 of your attribute as the command line option, and if there is a type
109 constraint defined, it will configure Getopt::Long to handle the option
112 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait> or the
113 attribute metaclass L<MooseX::Getopt::Meta::Attribute> to get non-default
114 commandline option names and aliases.
116 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait::NoGetopt>
117 or the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetopt>
118 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
120 By default, attributes which start with an underscore are not given
121 commandline argument support, unless the attribute's metaclass is set
122 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
123 to have the leading underscore in thier name, you can do this:
125 # for read/write attributes
126 has '_foo' => (accessor => 'foo', ...);
128 # or for read-only attributes
129 has '_bar' => (reader => 'bar', ...);
131 This will mean that Getopt will not handle a --foo param, but your
132 code can still call the C<foo> method.
134 If your class also uses a configfile-loading role based on
135 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
136 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
137 specified by the C<--configfile> option (or the default you've
138 given for the configfile attribute) for you.
140 Options specified in multiple places follow the following
141 precendence order: commandline overrides configfile, which
142 overrides explicit new_with_options parameters.
144 =head2 Supported Type Constraints
150 A I<Bool> type constraint is set up as a boolean option with
151 Getopt::Long. So that this attribute description:
153 has 'verbose' => (is => 'rw', isa => 'Bool');
155 would translate into C<verbose!> as a Getopt::Long option descriptor,
156 which would enable the following command line options:
158 % my_script.pl --verbose
159 % my_script.pl --noverbose
161 =item I<Int>, I<Float>, I<Str>
163 These type constraints are set up as properly typed options with
164 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
168 An I<ArrayRef> type constraint is set up as a multiple value option
169 in Getopt::Long. So that this attribute description:
174 default => sub { [] }
177 would translate into C<includes=s@> as a Getopt::Long option descriptor,
178 which would enable the following command line options:
180 % my_script.pl --include /usr/lib --include /usr/local/lib
184 A I<HashRef> type constraint is set up as a hash value option
185 in Getopt::Long. So that this attribute description:
190 default => sub { {} }
193 would translate into C<define=s%> as a Getopt::Long option descriptor,
194 which would enable the following command line options:
196 % my_script.pl --define os=linux --define vendor=debian
200 =head2 Custom Type Constraints
202 It is possible to create custom type constraint to option spec
203 mappings if you need them. The process is fairly simple (but a
204 little verbose maybe). First you create a custom subtype, like
207 subtype 'ArrayOfInts'
209 => where { scalar (grep { looks_like_number($_) } @$_) };
211 Then you register the mapping, like so:
213 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
214 'ArrayOfInts' => '=i@'
217 Now any attribute declarations using this type constraint will
218 get the custom option spec. So that, this:
222 isa => 'ArrayOfInts',
223 default => sub { [0] }
226 Will translate to the following on the command line:
228 % my_script.pl --nums 5 --nums 88 --nums 199
230 This example is fairly trivial, but more complex validations are
231 easily possible with a little creativity. The trick is balancing
232 the type constraint validations with the Getopt::Long validations.
234 Better examples are certainly welcome :)
236 =head2 Inferred Type Constraints
238 If you define a custom subtype which is a subtype of one of the
239 standard L</Supported Type Constraints> above, and do not explicitly
240 provide custom support as in L</Custom Type Constraints> above,
241 MooseX::Getopt will treat it like the parent type for Getopt
244 For example, if you had the same custom C<ArrayOfInts> subtype
245 from the examples above, but did not add a new custom option
246 type for it to the C<OptionTypeMap>, it would be treated just
247 like a normal C<ArrayRef> type for Getopt purposes (that is,
252 L<MooseX::Getopt> can handle more than one class which contain
253 attributes filled from CLI. In this case, you need to use explicite
254 L<MooseX::Getopt::Session> object and then the Getopt attributes will be
255 searched in any class which does L<MooseX::Getopt>.
259 with 'MooseX::Getopt';
260 has 'send' => (is => 'rw', predicate => 'has_send');
262 package My::App::Send;
264 with 'MooseX::Getopt';
265 has 'to' => (is => 'rw', isa => 'Str', default => 'localhost');
266 sub send { my $self = shift; warn "Sending mail to ", $self->to; }
268 # ... rest of the class here
273 my $getopt = MooseX::Getopt::Session->new;
275 my $app = My::App->new_with_options( getopt => $getopt );
276 if ($app->has_send) {
277 # Use the same command line
278 my $sender = My::App::Send->new_with_options( getopt => $getopt );
281 # ... rest of the script here
283 ## on the command line
284 % perl my_app_script.pl --send --to server.example.net
290 =item B<new_with_options (%params)>
292 This method will take a set of default C<%params> and then collect
293 params from the command line (possibly overriding those in C<%params>)
294 and then return a newly constructed object.
296 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
297 C<new_with_options> will throw an exception.
299 If you have L<Getopt::Long::Descriptive> a the C<usage> param is also passed to
304 This accessor contains a reference to a copy of the C<@ARGV> array as it
305 originally existed at the time of C<new_with_options>.
307 The C<ARGV> is delegated from L<MooseX::Getopt::Session> object.
311 This accessor contains an arrayref of leftover C<@ARGV> elements that
312 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
315 The C<extra_argv> is delegated from L<MooseX::Getopt::Session> object.
319 This accessor contains a L<MooseX::Getopt::Session> object. This object can
320 be shared between more than one class which does L<MooseX::Getopt>. The new
321 object is created by default.
325 This returns the role meta object.
333 =item L<MooseX::Getopt::Strict>
335 =item L<MooseX::Getopt::Session>
337 =item L<MooseX::Getopt::Parser>
343 All complex software has bugs lurking in it, and this module is no
344 exception. If you find a bug please either email me, or add the bug
349 Stevan Little E<lt>stevan@iinteractive.comE<gt>
351 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
353 Yuval Kogman, E<lt>nothingmuch@woobling.orgE<gt>
357 Ryan D Johnson, E<lt>ryan@innerfence.comE<gt>
359 Piotr Roszatycki, E<lt>dexter@cpan.orgE<gt>
361 =head1 COPYRIGHT AND LICENSE
363 Copyright 2007-2008 by Infinity Interactive, Inc.
365 L<http://www.iinteractive.com>
367 This library is free software; you can redistribute it and/or modify
368 it under the same terms as Perl itself.