* MooseX::Getopt: Reimplemented MooseX::ConfigFromFile support.
[gitmo/MooseX-Getopt.git] / lib / MooseX / Getopt.pm
index 8bc9399..27c17c8 100644 (file)
@@ -30,10 +30,17 @@ has getopt => (
 sub new_with_options {
     my $class = shift;
 
-    Moose->throw_error("Single parameters to new_with_options() must be a HASH ref")
+    return $class->new( $class->get_options_from_argv(@_) );
+};
+
+
+sub get_options_from_argv {
+    my $class = shift;
+
+    Moose->throw_error("Single parameters to get_options_from_argv() must be a HASH ref")
         if ref $_[0] and ref $_ ne 'HASH';
 
-    my %params = ( @_ == 1 ? %{ $_[0] } : @_ );
+    my %params = ( $class->_get_options_from_configfile, @_ == 1 ? %{ $_[0] } : @_ );
 
     my $getopt = defined $params{getopt}
                  ? $params{getopt}
@@ -42,12 +49,40 @@ sub new_with_options {
                        params => \%params,
                    );
 
-    $class->new(
-        getopt     => $getopt,
+    my %new_params = (
         %{ $getopt->params },                   # params from session object
         %params,                                # explicit params to ->new
         %{ $getopt->options },                  # params from CLI
+        getopt => $getopt,
     );
+
+    return %new_params;
+};
+
+
+sub _get_options_from_configfile {
+    my $class = shift;
+
+    my %params = ();
+
+    if ($class->meta->does_role('MooseX::ConfigFromFile')) {
+        local @ARGV = @ARGV;
+
+        my $configfile;
+        my $opt_parser = Getopt::Long::Parser->new( config => [ 'pass_through' ] );
+        $opt_parser->getoptions( "configfile=s" => \$configfile );
+
+        if (not defined $configfile) {
+            my $cfmeta = $class->meta->find_attribute_by_name('configfile');
+            $configfile = $cfmeta->default if $cfmeta->has_default;
+        };
+
+        if (defined $configfile) {
+            %params = %{ $class->get_config_from_file($configfile) };
+        };
+    };
+
+    return %params;
 };
 
 
@@ -299,6 +334,11 @@ C<new_with_options> will throw an exception.
 If you have L<Getopt::Long::Descriptive> a the C<usage> param is also passed to
 C<new>.
 
+=item B<get_options_from_argv (%params)>
+
+This method returns the list of parameters collected from command line
+without creating the new object.
+
 =item B<ARGV>
 
 This accessor contains a reference to a copy of the C<@ARGV> array as it