2 package MooseX::Getopt;
7 use MooseX::Getopt::OptionTypeMap;
8 use MooseX::Getopt::Meta::Attribute;
10 our $VERSION = '0.06';
11 our $AUTHORITY = 'cpan:STEVAN';
13 has ARGV => (is => 'rw', isa => 'ArrayRef');
14 has extra_argv => (is => 'rw', isa => 'ArrayRef');
16 sub new_with_options {
17 my ($class, %params) = @_;
19 my %processed = $class->_parse_argv(
21 $class->_attrs_to_options( %params )
26 ARGV => $processed{argv_copy},
27 extra_argv => $processed{argv},
28 %params, # explicit params to ->new
29 %{ $processed{params} }, # params from CLI
34 my ( $class, %params ) = @_;
36 local @ARGV = @{ $params{argv} || \@ARGV };
38 my ( @options, %name_to_init_arg, %options );
40 foreach my $opt ( @{ $params{options} } ) {
41 push @options, $opt->{opt_string};
42 $name_to_init_arg{ $opt->{name} } = $opt->{init_arg};
45 # Get a clean copy of the original @ARGV
46 my $argv_copy = [ @ARGV ];
49 local $SIG{__WARN__} = sub { die $_[0] };
50 Getopt::Long::GetOptions(\%options, @options);
53 # Get a copy of the Getopt::Long-mangled @ARGV
54 my $argv_mangled = [ @ARGV ];
57 argv_copy => $argv_copy,
58 argv => $argv_mangled,
61 $name_to_init_arg{$_} => $options{$_}
67 sub _attrs_to_options {
72 foreach my $attr ($class->meta->compute_all_applicable_attributes) {
73 my $name = $attr->name;
77 if ($attr->isa('MooseX::Getopt::Meta::Attribute')) {
78 $name = $attr->cmd_flag if $attr->has_cmd_flag;
79 $aliases = $attr->cmd_aliases if $attr->has_cmd_aliases;
82 next if $name =~ /^_/;
83 next if $attr->isa('MooseX::Getopt::Meta::NoGetopt');
86 my $opt_string = $aliases
87 ? join(q{|}, $name, @$aliases)
90 if ($attr->has_type_constraint) {
91 my $type_name = $attr->type_constraint->name;
92 if (MooseX::Getopt::OptionTypeMap->has_option_type($type_name)) {
93 $opt_string .= MooseX::Getopt::OptionTypeMap->get_option_type($type_name);
99 init_arg => $attr->init_arg,
100 opt_string => $opt_string,
101 required => $attr->is_required,
102 ( $attr->has_documentation ? ( doc => $attr->documentation ) : () ),
117 MooseX::Getopt - A Moose role for processing command line options
125 with 'MooseX::Getopt';
127 has 'out' => (is => 'rw', isa => 'Str', required => 1);
128 has 'in' => (is => 'rw', isa => 'Str', required => 1);
130 # ... rest of the class here
137 my $app = My::App->new_with_options();
138 # ... rest of the script here
140 ## on the command line
141 % perl my_app_script.pl -in file.input -out file.dump
145 This is a role which provides an alternate constructor for creating
146 objects using parameters passed in from the command line.
148 This module attempts to DWIM as much as possible with the command line
149 params by introspecting your class's attributes. It will use the name
150 of your attribute as the command line option, and if there is a type
151 constraint defined, it will configure Getopt::Long to handle the option
154 You can use the attribute metaclass L<MooseX::Getopt::Meta::Attribute>
155 to get non-default commandline option names and aliases.
157 By default, attributes which start with an underscore are not given
158 commandline argument support, unless the attribute's metaclass is set
159 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
160 to have the leading underscore in thier name, you can do this:
162 # for read/write attributes
163 has '_foo' => (accessor => 'foo', ...);
165 # or for read-only attributes
166 has '_bar' => (reader => 'bar', ...);
168 This will mean that Getopt will not handle a --foo param, but your
169 code can still call the C<foo> method.
171 =head2 Supported Type Constraints
177 A I<Bool> type constraint is set up as a boolean option with
178 Getopt::Long. So that this attribute description:
180 has 'verbose' => (is => 'rw', isa => 'Bool');
182 would translate into C<verbose!> as a Getopt::Long option descriptor,
183 which would enable the following command line options:
185 % my_script.pl --verbose
186 % my_script.pl --noverbose
188 =item I<Int>, I<Float>, I<Str>
190 These type constraints are set up as properly typed options with
191 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
195 An I<ArrayRef> type constraint is set up as a multiple value option
196 in Getopt::Long. So that this attribute description:
201 default => sub { [] }
204 would translate into C<includes=s@> as a Getopt::Long option descriptor,
205 which would enable the following command line options:
207 % my_script.pl --include /usr/lib --include /usr/local/lib
211 A I<HashRef> type constraint is set up as a hash value option
212 in Getopt::Long. So that this attribute description:
217 default => sub { {} }
220 would translate into C<define=s%> as a Getopt::Long option descriptor,
221 which would enable the following command line options:
223 % my_script.pl --define os=linux --define vendor=debian
227 =head2 Custom Type Constraints
229 It is possible to create custom type constraint to option spec
230 mappings if you need them. The process is fairly simple (but a
231 little verbose maybe). First you create a custom subtype, like
234 subtype 'ArrayOfInts'
236 => where { scalar (grep { looks_like_number($_) } @$_) };
238 Then you register the mapping, like so:
240 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
241 'ArrayOfInts' => '=i@'
244 Now any attribute declarations using this type constraint will
245 get the custom option spec. So that, this:
249 isa => 'ArrayOfInts',
250 default => sub { [0] }
253 Will translate to the following on the command line:
255 % my_script.pl --nums 5 --nums 88 --nums 199
257 This example is fairly trivial, but more complex validations are
258 easily possible with a little creativity. The trick is balancing
259 the type constraint validations with the Getopt::Long validations.
261 Better examples are certainly welcome :)
263 =head2 Inferred Type Constraints
265 If you define a custom subtype which is a subtype of one of the
266 standard L</Supported Type Constraints> above, and do not explicitly
267 provide custom support as in L</Custom Type Constraints> above,
268 MooseX::Getopt will treat it like the parent type for Getopt
271 For example, if you had the same custom C<ArrayOfInts> subtype
272 from the examples above, but did not add a new custom option
273 type for it to the C<OptionTypeMap>, it would be treated just
274 like a normal C<ArrayRef> type for Getopt purposes (that is,
281 =item B<new_with_options (%params)>
283 This method will take a set of default C<%params> and then collect
284 params from the command line (possibly overriding those in C<%params>)
285 and then return a newly constructed object.
287 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
288 C<new_with_options> will throw an exception.
292 This accessor contains a reference to a copy of the C<@ARGV> array
293 as it originally existed at the time of C<new_with_options>.
297 This accessor contains an arrayref of leftover C<@ARGV> elements that
298 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
303 This returns the role meta object.
309 All complex software has bugs lurking in it, and this module is no
310 exception. If you find a bug please either email me, or add the bug
315 Stevan Little E<lt>stevan@iinteractive.comE<gt>
317 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
319 =head1 COPYRIGHT AND LICENSE
321 Copyright 2007 by Infinity Interactive, Inc.
323 L<http://www.iinteractive.com>
325 This library is free software; you can redistribute it and/or modify
326 it under the same terms as Perl itself.