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';
25 metaclass => 'NoGetopt',
31 metaclass => 'NoGetopt',
36 isa => 'MooseX::Getopt::Session',
37 metaclass => 'NoGetopt',
41 sub new_with_options {
44 Moose->throw_error("Single parameters to new_with_options() must be a HASH ref")
45 if ref $_[0] and ref $_ ne 'HASH';
47 my %params = ( @_ == 1 ? %{ $_[0] } : @_ );
49 my $getopt = defined $params{getopt}
51 : $class->_default_getopt_session->new(
52 classes_filter => sub { $_ eq $class },
56 my %options = $getopt->options;
59 ARGV => [ $getopt->argv ], # backward compatibility
60 extra_argv => [ $getopt->extra_argv ], # backward compatibility
62 %{ $getopt->params }, # params from session object
63 %params, # explicit params to ->new
64 %options, # params from CLI
69 sub _compute_getopt_attrs {
73 $_->does('MooseX::Getopt::Meta::Attribute::Trait')
77 !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
78 } $class->meta->compute_all_applicable_attributes;
90 MooseX::Getopt - A Moose role for processing command line options
98 with 'MooseX::Getopt';
100 has 'out' => (is => 'rw', isa => 'Str', required => 1);
101 has 'in' => (is => 'rw', isa => 'Str', required => 1);
103 # ... rest of the class here
110 my $app = My::App->new_with_options();
111 # ... rest of the script here
113 ## on the command line
114 % perl my_app_script.pl -in file.input -out file.dump
118 This is a role which provides an alternate constructor for creating
119 objects using parameters passed in from the command line.
121 This module attempts to DWIM as much as possible with the command line
122 params by introspecting your class's attributes. It will use the name
123 of your attribute as the command line option, and if there is a type
124 constraint defined, it will configure Getopt::Long to handle the option
127 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait> or the
128 attribute metaclass L<MooseX::Getopt::Meta::Attribute> to get non-default
129 commandline option names and aliases.
131 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait::NoGetopt>
132 or the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetopt>
133 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
135 By default, attributes which start with an underscore are not given
136 commandline argument support, unless the attribute's metaclass is set
137 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
138 to have the leading underscore in thier name, you can do this:
140 # for read/write attributes
141 has '_foo' => (accessor => 'foo', ...);
143 # or for read-only attributes
144 has '_bar' => (reader => 'bar', ...);
146 This will mean that Getopt will not handle a --foo param, but your
147 code can still call the C<foo> method.
149 If your class also uses a configfile-loading role based on
150 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
151 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
152 specified by the C<--configfile> option (or the default you've
153 given for the configfile attribute) for you.
155 Options specified in multiple places follow the following
156 precendence order: commandline overrides configfile, which
157 overrides explicit new_with_options parameters.
159 =head2 Supported Type Constraints
165 A I<Bool> type constraint is set up as a boolean option with
166 Getopt::Long. So that this attribute description:
168 has 'verbose' => (is => 'rw', isa => 'Bool');
170 would translate into C<verbose!> as a Getopt::Long option descriptor,
171 which would enable the following command line options:
173 % my_script.pl --verbose
174 % my_script.pl --noverbose
176 =item I<Int>, I<Float>, I<Str>
178 These type constraints are set up as properly typed options with
179 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
183 An I<ArrayRef> type constraint is set up as a multiple value option
184 in Getopt::Long. So that this attribute description:
189 default => sub { [] }
192 would translate into C<includes=s@> as a Getopt::Long option descriptor,
193 which would enable the following command line options:
195 % my_script.pl --include /usr/lib --include /usr/local/lib
199 A I<HashRef> type constraint is set up as a hash value option
200 in Getopt::Long. So that this attribute description:
205 default => sub { {} }
208 would translate into C<define=s%> as a Getopt::Long option descriptor,
209 which would enable the following command line options:
211 % my_script.pl --define os=linux --define vendor=debian
215 =head2 Custom Type Constraints
217 It is possible to create custom type constraint to option spec
218 mappings if you need them. The process is fairly simple (but a
219 little verbose maybe). First you create a custom subtype, like
222 subtype 'ArrayOfInts'
224 => where { scalar (grep { looks_like_number($_) } @$_) };
226 Then you register the mapping, like so:
228 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
229 'ArrayOfInts' => '=i@'
232 Now any attribute declarations using this type constraint will
233 get the custom option spec. So that, this:
237 isa => 'ArrayOfInts',
238 default => sub { [0] }
241 Will translate to the following on the command line:
243 % my_script.pl --nums 5 --nums 88 --nums 199
245 This example is fairly trivial, but more complex validations are
246 easily possible with a little creativity. The trick is balancing
247 the type constraint validations with the Getopt::Long validations.
249 Better examples are certainly welcome :)
251 =head2 Inferred Type Constraints
253 If you define a custom subtype which is a subtype of one of the
254 standard L</Supported Type Constraints> above, and do not explicitly
255 provide custom support as in L</Custom Type Constraints> above,
256 MooseX::Getopt will treat it like the parent type for Getopt
259 For example, if you had the same custom C<ArrayOfInts> subtype
260 from the examples above, but did not add a new custom option
261 type for it to the C<OptionTypeMap>, it would be treated just
262 like a normal C<ArrayRef> type for Getopt purposes (that is,
269 =item B<new_with_options (%params)>
271 This method will take a set of default C<%params> and then collect
272 params from the command line (possibly overriding those in C<%params>)
273 and then return a newly constructed object.
275 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
276 C<new_with_options> will throw an exception.
278 If you have L<Getopt::Long::Descriptive> a the C<usage> param is also passed to
283 This accessor contains a reference to a copy of the C<@ARGV> array
284 as it originally existed at the time of C<new_with_options>.
288 This accessor contains an arrayref of leftover C<@ARGV> elements that
289 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
294 This returns the role meta object.
300 All complex software has bugs lurking in it, and this module is no
301 exception. If you find a bug please either email me, or add the bug
306 Stevan Little E<lt>stevan@iinteractive.comE<gt>
308 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
310 Yuval Kogman, E<lt>nothingmuch@woobling.orgE<gt>
314 Ryan D Johnson, E<lt>ryan@innerfence.comE<gt>
316 =head1 COPYRIGHT AND LICENSE
318 Copyright 2007-2008 by Infinity Interactive, Inc.
320 L<http://www.iinteractive.com>
322 This library is free software; you can redistribute it and/or modify
323 it under the same terms as Perl itself.