2 package MooseX::Getopt;
5 use Moose::Util::TypeConstraints;
7 use MooseX::Getopt::OptionTypeMap;
9 use MooseX::Getopt::Parser::Long;
10 use maybe 'MooseX::Getopt::Parser::Descriptive';
12 use MooseX::Getopt::Meta::Attribute;
13 use MooseX::Getopt::Meta::Attribute::NoGetopt;
16 our $VERSION = '0.15';
17 our $AUTHORITY = 'cpan:STEVAN';
23 metaclass => 'NoGetopt',
29 metaclass => 'NoGetopt',
32 has getopt_parser => (
34 does => 'MooseX::Getopt::Parser',
35 metaclass => 'NoGetopt',
38 sub new_with_options {
39 my ($class, @params) = @_;
43 my $constructor_params = ( @params == 1 ? $params[0] : {@params} );
46 if (defined $constructor_params->{getopt_parser}) {
47 $getopt_parser = $constructor_params->{getopt_parser};
48 $getopt_parser = $getopt_parser->new if not ref $getopt_parser;
51 $getopt_parser = maybe::HAVE_MOOSEX_GETOPT_PARSER_DESCRIPTIVE
52 ? MooseX::Getopt::Parser::Descriptive->new
53 : MooseX::Getopt::Parser::Long->new;
56 if($class->meta->does_role('MooseX::ConfigFromFile')) {
60 my $opt_parser = Getopt::Long::Parser->new( config => [ qw( pass_through ) ] );
61 $opt_parser->getoptions( "configfile=s" => \$configfile );
63 if(!defined $configfile) {
64 my $cfmeta = $class->meta->find_attribute_by_name('configfile');
65 $configfile = $cfmeta->default if $cfmeta->has_default;
68 if(defined $configfile) {
69 $config_from_file = $class->get_config_from_file($configfile);
73 $class->throw_error("Single parameters to new_with_options() must be a HASH ref")
74 unless ref($constructor_params) eq 'HASH';
76 my %processed = $class->_parse_argv(
78 $class->_attrs_to_options( $config_from_file )
80 params => $constructor_params,
81 getopt_parser => $getopt_parser,
84 my $params = $config_from_file ? { %$config_from_file, %{$processed{params}} } : $processed{params};
87 ARGV => $processed{argv_copy},
88 extra_argv => $processed{argv},
89 getopt_parser => $getopt_parser,
90 @params, # explicit params to ->new
91 %$params, # params from CLI
96 my ($class, %params) = @_;
98 local @ARGV = @{ $params{argv} || \@ARGV };
100 my ( $opt_spec, $name_to_init_arg ) = ( $params{getopt_parser}->_get_getopt_spec(%params) );
102 # Get a clean copy of the original @ARGV
103 my $argv_copy = [ @ARGV ];
107 my ( $parsed_options, $usage ) = eval {
108 local $SIG{__WARN__} = sub { push @err, @_ };
110 return $params{getopt_parser}->getoptions($opt_spec);
113 die join "", grep { defined } @err, $@ if @err or $@;
115 # Get a copy of the Getopt::Long-mangled @ARGV
116 my $argv_mangled = [ @ARGV ];
118 my %constructor_args = (
120 $name_to_init_arg->{$_} => $parsed_options->{$_}
121 } keys %$parsed_options,
125 params => \%constructor_args,
126 argv_copy => $argv_copy,
127 argv => $argv_mangled,
128 ( defined($usage) ? ( usage => $usage ) : () ),
132 sub _compute_getopt_attrs {
135 $_->does("MooseX::Getopt::Meta::Attribute::Trait")
139 !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
140 } $class->meta->compute_all_applicable_attributes
143 sub _get_cmd_flags_for_attr {
144 my ( $class, $attr ) = @_;
146 my $flag = $attr->name;
150 if ($attr->does('MooseX::Getopt::Meta::Attribute::Trait')) {
151 $flag = $attr->cmd_flag if $attr->has_cmd_flag;
152 @aliases = @{ $attr->cmd_aliases } if $attr->has_cmd_aliases;
155 return ( $flag, @aliases );
158 sub _attrs_to_options {
160 my $config_from_file = shift || {};
164 foreach my $attr ($class->_compute_getopt_attrs) {
165 my ( $flag, @aliases ) = $class->_get_cmd_flags_for_attr($attr);
167 my $opt_string = join(q{|}, $flag, @aliases);
169 if ($attr->has_type_constraint) {
170 my $type = $attr->type_constraint;
171 if (MooseX::Getopt::OptionTypeMap->has_option_type($type)) {
172 $opt_string .= MooseX::Getopt::OptionTypeMap->get_option_type($type)
178 init_arg => $attr->init_arg,
179 opt_string => $opt_string,
180 required => $attr->is_required && !$attr->has_default && !$attr->has_builder && !exists $config_from_file->{$attr->name},
182 # this "feature" was breaking because
183 # Getopt::Long::Descriptive would return
184 # the default value as if it was a command
185 # line flag, which would then override the
186 # one passed into a constructor.
187 # See 100_gld_default_bug.t for an example
189 #( ( $attr->has_default && ( $attr->is_default_a_coderef xor $attr->is_lazy ) ) ? ( default => $attr->default({}) ) : () ),
190 ( $attr->has_documentation ? ( doc => $attr->documentation ) : () ),
205 MooseX::Getopt - A Moose role for processing command line options
213 with 'MooseX::Getopt';
215 has 'out' => (is => 'rw', isa => 'Str', required => 1);
216 has 'in' => (is => 'rw', isa => 'Str', required => 1);
218 # ... rest of the class here
225 my $app = My::App->new_with_options();
226 # ... rest of the script here
228 ## on the command line
229 % perl my_app_script.pl -in file.input -out file.dump
233 This is a role which provides an alternate constructor for creating
234 objects using parameters passed in from the command line.
236 This module attempts to DWIM as much as possible with the command line
237 params by introspecting your class's attributes. It will use the name
238 of your attribute as the command line option, and if there is a type
239 constraint defined, it will configure Getopt::Long to handle the option
242 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait> or the
243 attribute metaclass L<MooseX::Getopt::Meta::Attribute> to get non-default
244 commandline option names and aliases.
246 You can use the trait L<MooseX::Getopt::Meta::Attribute::Trait::NoGetopt>
247 or the attribute metaclass L<MooseX::Getopt::Meta::Attribute::NoGetopt>
248 to have C<MooseX::Getopt> ignore your attribute in the commandline options.
250 By default, attributes which start with an underscore are not given
251 commandline argument support, unless the attribute's metaclass is set
252 to L<MooseX::Getopt::Meta::Attribute>. If you don't want you accessors
253 to have the leading underscore in thier name, you can do this:
255 # for read/write attributes
256 has '_foo' => (accessor => 'foo', ...);
258 # or for read-only attributes
259 has '_bar' => (reader => 'bar', ...);
261 This will mean that Getopt will not handle a --foo param, but your
262 code can still call the C<foo> method.
264 If your class also uses a configfile-loading role based on
265 L<MooseX::ConfigFromFile>, such as L<MooseX::SimpleConfig>,
266 L<MooseX::Getopt>'s C<new_with_options> will load the configfile
267 specified by the C<--configfile> option (or the default you've
268 given for the configfile attribute) for you.
270 Options specified in multiple places follow the following
271 precendence order: commandline overrides configfile, which
272 overrides explicit new_with_options parameters.
274 =head2 Supported Type Constraints
280 A I<Bool> type constraint is set up as a boolean option with
281 Getopt::Long. So that this attribute description:
283 has 'verbose' => (is => 'rw', isa => 'Bool');
285 would translate into C<verbose!> as a Getopt::Long option descriptor,
286 which would enable the following command line options:
288 % my_script.pl --verbose
289 % my_script.pl --noverbose
291 =item I<Int>, I<Float>, I<Str>
293 These type constraints are set up as properly typed options with
294 Getopt::Long, using the C<=i>, C<=f> and C<=s> modifiers as appropriate.
298 An I<ArrayRef> type constraint is set up as a multiple value option
299 in Getopt::Long. So that this attribute description:
304 default => sub { [] }
307 would translate into C<includes=s@> as a Getopt::Long option descriptor,
308 which would enable the following command line options:
310 % my_script.pl --include /usr/lib --include /usr/local/lib
314 A I<HashRef> type constraint is set up as a hash value option
315 in Getopt::Long. So that this attribute description:
320 default => sub { {} }
323 would translate into C<define=s%> as a Getopt::Long option descriptor,
324 which would enable the following command line options:
326 % my_script.pl --define os=linux --define vendor=debian
330 =head2 Custom Type Constraints
332 It is possible to create custom type constraint to option spec
333 mappings if you need them. The process is fairly simple (but a
334 little verbose maybe). First you create a custom subtype, like
337 subtype 'ArrayOfInts'
339 => where { scalar (grep { looks_like_number($_) } @$_) };
341 Then you register the mapping, like so:
343 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
344 'ArrayOfInts' => '=i@'
347 Now any attribute declarations using this type constraint will
348 get the custom option spec. So that, this:
352 isa => 'ArrayOfInts',
353 default => sub { [0] }
356 Will translate to the following on the command line:
358 % my_script.pl --nums 5 --nums 88 --nums 199
360 This example is fairly trivial, but more complex validations are
361 easily possible with a little creativity. The trick is balancing
362 the type constraint validations with the Getopt::Long validations.
364 Better examples are certainly welcome :)
366 =head2 Inferred Type Constraints
368 If you define a custom subtype which is a subtype of one of the
369 standard L</Supported Type Constraints> above, and do not explicitly
370 provide custom support as in L</Custom Type Constraints> above,
371 MooseX::Getopt will treat it like the parent type for Getopt
374 For example, if you had the same custom C<ArrayOfInts> subtype
375 from the examples above, but did not add a new custom option
376 type for it to the C<OptionTypeMap>, it would be treated just
377 like a normal C<ArrayRef> type for Getopt purposes (that is,
384 =item B<new_with_options (%params)>
386 This method will take a set of default C<%params> and then collect
387 params from the command line (possibly overriding those in C<%params>)
388 and then return a newly constructed object.
390 If L<Getopt::Long/GetOptions> fails (due to invalid arguments),
391 C<new_with_options> will throw an exception.
393 If you have L<Getopt::Long::Descriptive> a the C<usage> param is also passed to
398 This accessor contains a reference to a copy of the C<@ARGV> array
399 as it originally existed at the time of C<new_with_options>.
403 This accessor contains an arrayref of leftover C<@ARGV> elements that
404 L<Getopt::Long> did not parse. Note that the real C<@ARGV> is left
409 This returns the role meta object.
415 All complex software has bugs lurking in it, and this module is no
416 exception. If you find a bug please either email me, or add the bug
421 Stevan Little E<lt>stevan@iinteractive.comE<gt>
423 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
425 Yuval Kogman, E<lt>nothingmuch@woobling.orgE<gt>
429 Ryan D Johnson, E<lt>ryan@innerfence.comE<gt>
431 =head1 COPYRIGHT AND LICENSE
433 Copyright 2007-2008 by Infinity Interactive, Inc.
435 L<http://www.iinteractive.com>
437 This library is free software; you can redistribute it and/or modify
438 it under the same terms as Perl itself.