2 package MooseX::Getopt;
5 use Getopt::Long::Descriptive ();
7 use MooseX::Getopt::OptionTypeMap;
8 use MooseX::Getopt::Meta::Attribute;
9 use MooseX::Getopt::Meta::Attribute::NoGetopt;
11 our $VERSION = '0.08';
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, @args ) = @_;
47 my ( $params, $argv_copy, $argv_mangled ) = $class->_call_getopt(@args);
50 argv_copy => $argv_copy,
51 argv => $argv_mangled,
57 my ( $class, %params ) = @_;
59 local @ARGV = @{ $params{argv} || \@ARGV };
61 my ( $opt_spec, $name_to_init_arg ) = $class->_gld_spec(%params);
63 # Get a clean copy of the original @ARGV
64 my $argv_copy = [ @ARGV ];
68 my ( $parsed_options, $usage ) = eval {
69 local $SIG{__WARN__} = sub { push @err, @_ };
70 Getopt::Long::Descriptive::describe_options("usage: %c %o", @$opt_spec)
73 die join "", grep { defined } @err, $@ if @err or $@;
75 # Get a copy of the Getopt::Long-mangled @ARGV
76 my $argv_mangled = [ @ARGV ];
78 my %constructor_args = (
80 $name_to_init_arg->{$_} => $parsed_options->{$_}
81 } keys %$parsed_options,
84 return ( \%constructor_args, $argv_copy, $argv_mangled );
88 my ( $class, %params ) = @_;
90 my ( @options, %name_to_init_arg );
92 foreach my $opt ( @{ $params{options} } ) {
95 $opt->{doc} || ' ', # FIXME new GLD shouldn't need this hack
97 ( $opt->{required} ? (required => $opt->{required}) : () ),
98 ( exists $opt->{default} ? (default => $opt->{default}) : () ),
102 $name_to_init_arg{ $opt->{name} } = $opt->{init_arg};
105 return ( \@options, \%name_to_init_arg );
108 sub _compute_getopt_attrs {
111 $_->isa("MooseX::Getopt::Meta::Attribute")
115 !$_->isa('MooseX::Getopt::Meta::Attribute::NoGetopt')
116 } $class->meta->compute_all_applicable_attributes
119 sub _attrs_to_options {
124 foreach my $attr ($class->_compute_getopt_attrs) {
125 my $name = $attr->name;
129 if ($attr->isa('MooseX::Getopt::Meta::Attribute')) {
130 $name = $attr->cmd_flag if $attr->has_cmd_flag;
131 $aliases = $attr->cmd_aliases if $attr->has_cmd_aliases;
134 my $opt_string = $aliases
135 ? join(q{|}, $name, @$aliases)
138 if ($attr->has_type_constraint) {
139 my $type_name = $attr->type_constraint->name;
140 if (MooseX::Getopt::OptionTypeMap->has_option_type($type_name)) {
141 $opt_string .= MooseX::Getopt::OptionTypeMap->get_option_type($type_name)
147 init_arg => $attr->init_arg,
148 opt_string => $opt_string,
149 required => $attr->is_required,
150 ( ( $attr->has_default && ( $attr->is_default_a_coderef xor $attr->is_lazy ) ) ? ( default => $attr->default({}) ) : () ),
151 ( $attr->has_documentation ? ( doc => $attr->documentation ) : () ),
166 MooseX::Getopt - A Moose role for processing command line options
174 with 'MooseX::Getopt';
176 has 'out' => (is => 'rw', isa => 'Str', required => 1);
177 has 'in' => (is => 'rw', isa => 'Str', required => 1);
179 # ... rest of the class here
186 my $app = My::App->new_with_options();
187 # ... rest of the script here
189 ## on the command line
190 % perl my_app_script.pl -in file.input -out file.dump
194 This is a role which provides an alternate constructor for creating
195 objects using parameters passed in from the command line.
197 This module attempts to DWIM as much as possible with the command line
198 params by introspecting your class's attributes. It will use the name
199 of your attribute as the command line option, and if there is a type
200 constraint defined, it will configure Getopt::Long to handle the option
203 You can use the attribute metaclass L<MooseX::Getopt::Meta::Attribute>
204 to get non-default commandline option names and aliases.
206 You can use the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetOpt>
207 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
209 By default, attributes which start with an underscore are not given
210 commandline argument support, unless the attribute's metaclass is set
211 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
212 to have the leading underscore in thier name, you can do this:
214 # for read/write attributes
215 has '_foo' => (accessor => 'foo', ...);
217 # or for read-only attributes
218 has '_bar' => (reader => 'bar', ...);
220 This will mean that Getopt will not handle a --foo param, but your
221 code can still call the C<foo> method.
223 If your class also uses a configfile-loading role based on
224 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
225 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
226 specified by the C<--configfile> option for you.
228 =head2 Supported Type Constraints
234 A I<Bool> type constraint is set up as a boolean option with
235 Getopt::Long. So that this attribute description:
237 has 'verbose' => (is => 'rw', isa => 'Bool');
239 would translate into C<verbose!> as a Getopt::Long option descriptor,
240 which would enable the following command line options:
242 % my_script.pl --verbose
243 % my_script.pl --noverbose
245 =item I<Int>, I<Float>, I<Str>
247 These type constraints are set up as properly typed options with
248 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
252 An I<ArrayRef> type constraint is set up as a multiple value option
253 in Getopt::Long. So that this attribute description:
258 default => sub { [] }
261 would translate into C<includes=s@> as a Getopt::Long option descriptor,
262 which would enable the following command line options:
264 % my_script.pl --include /usr/lib --include /usr/local/lib
268 A I<HashRef> type constraint is set up as a hash value option
269 in Getopt::Long. So that this attribute description:
274 default => sub { {} }
277 would translate into C<define=s%> as a Getopt::Long option descriptor,
278 which would enable the following command line options:
280 % my_script.pl --define os=linux --define vendor=debian
284 =head2 Custom Type Constraints
286 It is possible to create custom type constraint to option spec
287 mappings if you need them. The process is fairly simple (but a
288 little verbose maybe). First you create a custom subtype, like
291 subtype 'ArrayOfInts'
293 => where { scalar (grep { looks_like_number($_) } @$_) };
295 Then you register the mapping, like so:
297 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
298 'ArrayOfInts' => '=i@'
301 Now any attribute declarations using this type constraint will
302 get the custom option spec. So that, this:
306 isa => 'ArrayOfInts',
307 default => sub { [0] }
310 Will translate to the following on the command line:
312 % my_script.pl --nums 5 --nums 88 --nums 199
314 This example is fairly trivial, but more complex validations are
315 easily possible with a little creativity. The trick is balancing
316 the type constraint validations with the Getopt::Long validations.
318 Better examples are certainly welcome :)
320 =head2 Inferred Type Constraints
322 If you define a custom subtype which is a subtype of one of the
323 standard L</Supported Type Constraints> above, and do not explicitly
324 provide custom support as in L</Custom Type Constraints> above,
325 MooseX::Getopt will treat it like the parent type for Getopt
328 For example, if you had the same custom C<ArrayOfInts> subtype
329 from the examples above, but did not add a new custom option
330 type for it to the C<OptionTypeMap>, it would be treated just
331 like a normal C<ArrayRef> type for Getopt purposes (that is,
338 =item B<new_with_options (%params)>
340 This method will take a set of default C<%params> and then collect
341 params from the command line (possibly overriding those in C<%params>)
342 and then return a newly constructed object.
344 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
345 C<new_with_options> will throw an exception.
349 This accessor contains a reference to a copy of the C<@ARGV> array
350 as it originally existed at the time of C<new_with_options>.
354 This accessor contains an arrayref of leftover C<@ARGV> elements that
355 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
360 This returns the role meta object.
366 All complex software has bugs lurking in it, and this module is no
367 exception. If you find a bug please either email me, or add the bug
372 Stevan Little E<lt>stevan@iinteractive.comE<gt>
374 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
376 =head1 COPYRIGHT AND LICENSE
378 Copyright 2007 by Infinity Interactive, Inc.
380 L<http://www.iinteractive.com>
382 This library is free software; you can redistribute it and/or modify
383 it under the same terms as Perl itself.