From: Gordon Irving Date: Sat, 1 Aug 2009 19:17:49 +0000 (+0100) Subject: really commit X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=gitmo%2FMooseX-Getopt.git;a=commitdiff_plain;h=topic%2Fcreate_via_new really commit --- diff --git a/lib/MooseX/Getopt.pm b/lib/MooseX/Getopt.pm index b400247..d463fd4 100644 --- a/lib/MooseX/Getopt.pm +++ b/lib/MooseX/Getopt.pm @@ -66,6 +66,58 @@ sub new_with_options { ); } +sub BUILDARGS { + + my ($class, @params) = @_; + + my $config_from_file; + if($class->meta->does_role('MooseX::ConfigFromFile')) { + local @ARGV = @ARGV; + + my $configfile; + my $opt_parser = Getopt::Long::Parser->new( config => [ qw( pass_through ) ] ); + $opt_parser->getoptions( "configfile=s" => \$configfile ); + + if(!defined $configfile) { + my $cfmeta = $class->meta->find_attribute_by_name('configfile'); + $configfile = $cfmeta->default if $cfmeta->has_default; + } + + if(defined $configfile) { + $config_from_file = $class->get_config_from_file($configfile); + } + } + + my $constructor_params = ( @params == 1 ? $params[0] : {@params} ); + + Carp::croak("Single parameters to new_with_options() must be a HASH ref") + unless ref($constructor_params) eq 'HASH'; + + my %processed = $class->_parse_argv( + options => [ + $class->_attrs_to_options( $config_from_file ) + ], + params => $constructor_params, + ); + + my $params = $config_from_file ? { %$config_from_file, %{$processed{params}} } : $processed{params}; + + # did the user request usage information? + if ( $processed{usage} && ($params->{'?'} or $params->{help} or $params->{usage}) ) + { + $processed{usage}->die(); + } + + # BUILDALL needs to return a hash ref of args used to build + return { + ARGV => $processed{argv_copy}, + extra_argv => $processed{argv}, + %$constructor_params, # explicit params to ->new + %$params, # params from CLI + } +} + + sub _parse_argv { my ( $class, %params ) = @_;