2 package MooseX::Getopt;
7 use MooseX::Getopt::OptionTypeMap;
8 use MooseX::Getopt::Meta::Attribute;
9 use MooseX::Getopt::Meta::Attribute::NoGetopt;
11 our $VERSION = '0.07';
12 our $AUTHORITY = 'cpan:STEVAN';
14 has ARGV => (is => 'rw', isa => 'ArrayRef');
15 has extra_argv => (is => 'rw', isa => 'ArrayRef');
17 sub new_with_options {
18 my ($class, @params) = @_;
20 my %processed = $class->_parse_argv(
22 $class->_attrs_to_options( @params )
26 my $params = $processed{params};
28 if($class->meta->does_role('MooseX::ConfigFromFile')
29 && defined $params->{configfile}) {
31 %{$class->get_config_from_file($params->{configfile})},
37 ARGV => $processed{argv_copy},
38 extra_argv => $processed{argv},
39 @params, # explicit params to ->new
40 %$params, # params from CLI
45 my ( $class, %params ) = @_;
47 local @ARGV = @{ $params{argv} || \@ARGV };
49 my ( @options, %name_to_init_arg, %options );
51 foreach my $opt ( @{ $params{options} } ) {
52 push @options, $opt->{opt_string};
53 $name_to_init_arg{ $opt->{name} } = $opt->{init_arg};
56 # Get a clean copy of the original @ARGV
57 my $argv_copy = [ @ARGV ];
60 local $SIG{__WARN__} = sub { die $_[0] };
61 Getopt::Long::GetOptions(\%options, @options);
64 # Get a copy of the Getopt::Long-mangled @ARGV
65 my $argv_mangled = [ @ARGV ];
68 argv_copy => $argv_copy,
69 argv => $argv_mangled,
72 $name_to_init_arg{$_} => $options{$_}
78 sub _compute_getopt_attrs {
81 $_->isa("MooseX::Getopt::Meta::Attribute")
85 !$_->isa('MooseX::Getopt::Meta::Attribute::NoGetopt')
86 } $class->meta->compute_all_applicable_attributes
89 sub _attrs_to_options {
94 foreach my $attr ($class->_compute_getopt_attrs) {
95 my $name = $attr->name;
99 if ($attr->isa('MooseX::Getopt::Meta::Attribute')) {
100 $name = $attr->cmd_flag if $attr->has_cmd_flag;
101 $aliases = $attr->cmd_aliases if $attr->has_cmd_aliases;
104 my $opt_string = $aliases
105 ? join(q{|}, $name, @$aliases)
108 if ($attr->has_type_constraint) {
109 my $type_name = $attr->type_constraint->name;
110 if (MooseX::Getopt::OptionTypeMap->has_option_type($type_name)) {
111 $opt_string .= MooseX::Getopt::OptionTypeMap->get_option_type($type_name);
117 init_arg => $attr->init_arg,
118 opt_string => $opt_string,
119 required => $attr->is_required,
120 ( $attr->has_documentation ? ( doc => $attr->documentation ) : () ),
135 MooseX::Getopt - A Moose role for processing command line options
143 with 'MooseX::Getopt';
145 has 'out' => (is => 'rw', isa => 'Str', required => 1);
146 has 'in' => (is => 'rw', isa => 'Str', required => 1);
148 # ... rest of the class here
155 my $app = My::App->new_with_options();
156 # ... rest of the script here
158 ## on the command line
159 % perl my_app_script.pl -in file.input -out file.dump
163 This is a role which provides an alternate constructor for creating
164 objects using parameters passed in from the command line.
166 This module attempts to DWIM as much as possible with the command line
167 params by introspecting your class's attributes. It will use the name
168 of your attribute as the command line option, and if there is a type
169 constraint defined, it will configure Getopt::Long to handle the option
172 You can use the attribute metaclass L<MooseX::Getopt::Meta::Attribute>
173 to get non-default commandline option names and aliases.
175 You can use the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetOpt>
176 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
178 By default, attributes which start with an underscore are not given
179 commandline argument support, unless the attribute's metaclass is set
180 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
181 to have the leading underscore in thier name, you can do this:
183 # for read/write attributes
184 has '_foo' => (accessor => 'foo', ...);
186 # or for read-only attributes
187 has '_bar' => (reader => 'bar', ...);
189 This will mean that Getopt will not handle a --foo param, but your
190 code can still call the C<foo> method.
192 If your class also uses a configfile-loading role based on
193 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
194 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
195 specified by the C<--configfile> option for you.
197 =head2 Supported Type Constraints
203 A I<Bool> type constraint is set up as a boolean option with
204 Getopt::Long. So that this attribute description:
206 has 'verbose' => (is => 'rw', isa => 'Bool');
208 would translate into C<verbose!> as a Getopt::Long option descriptor,
209 which would enable the following command line options:
211 % my_script.pl --verbose
212 % my_script.pl --noverbose
214 =item I<Int>, I<Float>, I<Str>
216 These type constraints are set up as properly typed options with
217 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
221 An I<ArrayRef> type constraint is set up as a multiple value option
222 in Getopt::Long. So that this attribute description:
227 default => sub { [] }
230 would translate into C<includes=s@> as a Getopt::Long option descriptor,
231 which would enable the following command line options:
233 % my_script.pl --include /usr/lib --include /usr/local/lib
237 A I<HashRef> type constraint is set up as a hash value option
238 in Getopt::Long. So that this attribute description:
243 default => sub { {} }
246 would translate into C<define=s%> as a Getopt::Long option descriptor,
247 which would enable the following command line options:
249 % my_script.pl --define os=linux --define vendor=debian
253 =head2 Custom Type Constraints
255 It is possible to create custom type constraint to option spec
256 mappings if you need them. The process is fairly simple (but a
257 little verbose maybe). First you create a custom subtype, like
260 subtype 'ArrayOfInts'
262 => where { scalar (grep { looks_like_number($_) } @$_) };
264 Then you register the mapping, like so:
266 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
267 'ArrayOfInts' => '=i@'
270 Now any attribute declarations using this type constraint will
271 get the custom option spec. So that, this:
275 isa => 'ArrayOfInts',
276 default => sub { [0] }
279 Will translate to the following on the command line:
281 % my_script.pl --nums 5 --nums 88 --nums 199
283 This example is fairly trivial, but more complex validations are
284 easily possible with a little creativity. The trick is balancing
285 the type constraint validations with the Getopt::Long validations.
287 Better examples are certainly welcome :)
289 =head2 Inferred Type Constraints
291 If you define a custom subtype which is a subtype of one of the
292 standard L</Supported Type Constraints> above, and do not explicitly
293 provide custom support as in L</Custom Type Constraints> above,
294 MooseX::Getopt will treat it like the parent type for Getopt
297 For example, if you had the same custom C<ArrayOfInts> subtype
298 from the examples above, but did not add a new custom option
299 type for it to the C<OptionTypeMap>, it would be treated just
300 like a normal C<ArrayRef> type for Getopt purposes (that is,
307 =item B<new_with_options (%params)>
309 This method will take a set of default C<%params> and then collect
310 params from the command line (possibly overriding those in C<%params>)
311 and then return a newly constructed object.
313 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
314 C<new_with_options> will throw an exception.
318 This accessor contains a reference to a copy of the C<@ARGV> array
319 as it originally existed at the time of C<new_with_options>.
323 This accessor contains an arrayref of leftover C<@ARGV> elements that
324 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
329 This returns the role meta object.
335 All complex software has bugs lurking in it, and this module is no
336 exception. If you find a bug please either email me, or add the bug
341 Stevan Little E<lt>stevan@iinteractive.comE<gt>
343 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
345 =head1 COPYRIGHT AND LICENSE
347 Copyright 2007 by Infinity Interactive, Inc.
349 L<http://www.iinteractive.com>
351 This library is free software; you can redistribute it and/or modify
352 it under the same terms as Perl itself.