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.06';
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 )
27 ARGV => $processed{argv_copy},
28 extra_argv => $processed{argv},
29 @params, # explicit params to ->new
30 %{ $processed{params} }, # params from CLI
35 my ( $class, %params ) = @_;
37 local @ARGV = @{ $params{argv} || \@ARGV };
39 my ( @options, %name_to_init_arg, %options );
41 foreach my $opt ( @{ $params{options} } ) {
42 push @options, $opt->{opt_string};
43 $name_to_init_arg{ $opt->{name} } = $opt->{init_arg};
46 # Get a clean copy of the original @ARGV
47 my $argv_copy = [ @ARGV ];
50 local $SIG{__WARN__} = sub { die $_[0] };
51 Getopt::Long::GetOptions(\%options, @options);
54 # Get a copy of the Getopt::Long-mangled @ARGV
55 my $argv_mangled = [ @ARGV ];
58 argv_copy => $argv_copy,
59 argv => $argv_mangled,
62 $name_to_init_arg{$_} => $options{$_}
68 sub _compute_getopt_attrs {
71 $_->isa("MooseX::Getopt::Meta::Attribute")
75 !$_->isa('MooseX::Getopt::Meta::Attribute::NoGetopt')
76 } $class->meta->compute_all_applicable_attributes
79 sub _attrs_to_options {
84 foreach my $attr ($class->_compute_getopt_attrs) {
85 my $name = $attr->name;
89 if ($attr->isa('MooseX::Getopt::Meta::Attribute')) {
90 $name = $attr->cmd_flag if $attr->has_cmd_flag;
91 $aliases = $attr->cmd_aliases if $attr->has_cmd_aliases;
94 my $opt_string = $aliases
95 ? join(q{|}, $name, @$aliases)
98 if ($attr->has_type_constraint) {
99 my $type_name = $attr->type_constraint->name;
100 if (MooseX::Getopt::OptionTypeMap->has_option_type($type_name)) {
101 $opt_string .= MooseX::Getopt::OptionTypeMap->get_option_type($type_name);
107 init_arg => $attr->init_arg,
108 opt_string => $opt_string,
109 required => $attr->is_required,
110 ( $attr->has_documentation ? ( doc => $attr->documentation ) : () ),
125 MooseX::Getopt - A Moose role for processing command line options
133 with 'MooseX::Getopt';
135 has 'out' => (is => 'rw', isa => 'Str', required => 1);
136 has 'in' => (is => 'rw', isa => 'Str', required => 1);
138 # ... rest of the class here
145 my $app = My::App->new_with_options();
146 # ... rest of the script here
148 ## on the command line
149 % perl my_app_script.pl -in file.input -out file.dump
153 This is a role which provides an alternate constructor for creating
154 objects using parameters passed in from the command line.
156 This module attempts to DWIM as much as possible with the command line
157 params by introspecting your class's attributes. It will use the name
158 of your attribute as the command line option, and if there is a type
159 constraint defined, it will configure Getopt::Long to handle the option
162 You can use the attribute metaclass L<MooseX::Getopt::Meta::Attribute>
163 to get non-default commandline option names and aliases.
165 You can use the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetOpt>
166 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
168 By default, attributes which start with an underscore are not given
169 commandline argument support, unless the attribute's metaclass is set
170 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
171 to have the leading underscore in thier name, you can do this:
173 # for read/write attributes
174 has '_foo' => (accessor => 'foo', ...);
176 # or for read-only attributes
177 has '_bar' => (reader => 'bar', ...);
179 This will mean that Getopt will not handle a --foo param, but your
180 code can still call the C<foo> method.
182 =head2 Supported Type Constraints
188 A I<Bool> type constraint is set up as a boolean option with
189 Getopt::Long. So that this attribute description:
191 has 'verbose' => (is => 'rw', isa => 'Bool');
193 would translate into C<verbose!> as a Getopt::Long option descriptor,
194 which would enable the following command line options:
196 % my_script.pl --verbose
197 % my_script.pl --noverbose
199 =item I<Int>, I<Float>, I<Str>
201 These type constraints are set up as properly typed options with
202 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
206 An I<ArrayRef> type constraint is set up as a multiple value option
207 in Getopt::Long. So that this attribute description:
212 default => sub { [] }
215 would translate into C<includes=s@> as a Getopt::Long option descriptor,
216 which would enable the following command line options:
218 % my_script.pl --include /usr/lib --include /usr/local/lib
222 A I<HashRef> type constraint is set up as a hash value option
223 in Getopt::Long. So that this attribute description:
228 default => sub { {} }
231 would translate into C<define=s%> as a Getopt::Long option descriptor,
232 which would enable the following command line options:
234 % my_script.pl --define os=linux --define vendor=debian
238 =head2 Custom Type Constraints
240 It is possible to create custom type constraint to option spec
241 mappings if you need them. The process is fairly simple (but a
242 little verbose maybe). First you create a custom subtype, like
245 subtype 'ArrayOfInts'
247 => where { scalar (grep { looks_like_number($_) } @$_) };
249 Then you register the mapping, like so:
251 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
252 'ArrayOfInts' => '=i@'
255 Now any attribute declarations using this type constraint will
256 get the custom option spec. So that, this:
260 isa => 'ArrayOfInts',
261 default => sub { [0] }
264 Will translate to the following on the command line:
266 % my_script.pl --nums 5 --nums 88 --nums 199
268 This example is fairly trivial, but more complex validations are
269 easily possible with a little creativity. The trick is balancing
270 the type constraint validations with the Getopt::Long validations.
272 Better examples are certainly welcome :)
274 =head2 Inferred Type Constraints
276 If you define a custom subtype which is a subtype of one of the
277 standard L</Supported Type Constraints> above, and do not explicitly
278 provide custom support as in L</Custom Type Constraints> above,
279 MooseX::Getopt will treat it like the parent type for Getopt
282 For example, if you had the same custom C<ArrayOfInts> subtype
283 from the examples above, but did not add a new custom option
284 type for it to the C<OptionTypeMap>, it would be treated just
285 like a normal C<ArrayRef> type for Getopt purposes (that is,
292 =item B<new_with_options (%params)>
294 This method will take a set of default C<%params> and then collect
295 params from the command line (possibly overriding those in C<%params>)
296 and then return a newly constructed object.
298 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
299 C<new_with_options> will throw an exception.
303 This accessor contains a reference to a copy of the C<@ARGV> array
304 as it originally existed at the time of C<new_with_options>.
308 This accessor contains an arrayref of leftover C<@ARGV> elements that
309 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
314 This returns the role meta object.
320 All complex software has bugs lurking in it, and this module is no
321 exception. If you find a bug please either email me, or add the bug
326 Stevan Little E<lt>stevan@iinteractive.comE<gt>
328 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
330 =head1 COPYRIGHT AND LICENSE
332 Copyright 2007 by Infinity Interactive, Inc.
334 L<http://www.iinteractive.com>
336 This library is free software; you can redistribute it and/or modify
337 it under the same terms as Perl itself.