Add extra tests and changes for config_from file.
[gitmo/MooseX-Getopt.git] / lib / MooseX / Getopt / Basic.pm
1
2 package MooseX::Getopt::Basic;
3 use Moose::Role;
4
5 use MooseX::Getopt::OptionTypeMap;
6 use MooseX::Getopt::Meta::Attribute;
7 use MooseX::Getopt::Meta::Attribute::NoGetopt;
8 use Carp ();
9
10 use Getopt::Long ();
11
12 has ARGV       => (is => 'rw', isa => 'ArrayRef', metaclass => "NoGetopt");
13 has extra_argv => (is => 'rw', isa => 'ArrayRef', metaclass => "NoGetopt");
14
15 sub _get_configfile_from_cli {
16     my $class = shift;
17     my $configfile;
18     my $opt_parser = Getopt::Long::Parser->new( config => [ qw( pass_through ) ] );
19     $opt_parser->getoptions( "configfile=s" => \$configfile );
20     return $configfile;
21 }
22
23 sub new_with_options {
24     my ($class, @params) = @_;
25
26     my $constructor_params = ( @params == 1 ? $params[0] : {@params} );
27
28     my ($config_from_file, $configfile);
29     if($class->meta->does_role('MooseX::ConfigFromFile')) {
30         local @ARGV = @ARGV;
31
32         $configfile = $class->_get_configfile_from_cli;
33         if(!defined $configfile) {
34             $configfile = $constructor_params->{configfile};
35         }
36
37         if(!defined $configfile) {
38             my $cfmeta = $class->meta->find_attribute_by_name('configfile');
39             $configfile = $cfmeta->default if $cfmeta->has_default;
40             if (ref $configfile eq 'CODE') {
41                 # not sure theres a lot you can do with the class and may break some assumptions
42                 # warn?
43                 $configfile = &$configfile($class);
44             }
45             if (defined $configfile) {
46                 $config_from_file = eval {
47                     $class->get_config_from_file($configfile);
48                 };
49                 if ($@) {
50                     die $@ unless $@ =~ /Specified configfile '\Q$configfile\E' does not exist/;
51                 }
52             }
53         }
54         else {
55             $config_from_file = $class->get_config_from_file($configfile);
56         }
57     }
58
59     Carp::croak("Single parameters to new_with_options() must be a HASH ref")
60         unless ref($constructor_params) eq 'HASH';
61
62     my %processed = $class->_parse_argv(
63         options => [
64             $class->_attrs_to_options( $config_from_file )
65         ],
66         params => $constructor_params,
67     );
68
69     my $params = $config_from_file ? { configfile => $configfile, %$config_from_file, %{$processed{params}} } : $processed{params};
70
71     # did the user request usage information?
72     if ( $processed{usage} && ($params->{'?'} or $params->{help} or $params->{usage}) )
73     {
74         $class->_getopt_full_usage($processed{usage});
75     }
76
77     $class->new(
78         ARGV       => $processed{argv_copy},
79         extra_argv => $processed{argv},
80         %$constructor_params, # explicit params to ->new
81         %$params, # params from CLI
82     );
83 }
84
85 sub _getopt_spec { shift->_traditional_spec(@_); }
86
87 sub _parse_argv {
88     my ( $class, %params ) = @_;
89
90     local @ARGV = @{ $params{params}{argv} || \@ARGV };
91
92     my ( $opt_spec, $name_to_init_arg ) = $class->_getopt_spec(%params);
93
94     # Get a clean copy of the original @ARGV
95     my $argv_copy = [ @ARGV ];
96
97     my @warnings;
98     my ( $parsed_options, $usage ) = eval {
99         local $SIG{__WARN__} = sub { push @warnings, @_ };
100
101         return $class->_getopt_get_options(\%params, $opt_spec);
102     };
103
104     $class->_getopt_spec_warnings(@warnings) if @warnings;
105     $class->_getopt_spec_exception(\@warnings, $@) if $@;
106
107     # Get a copy of the Getopt::Long-mangled @ARGV
108     my $argv_mangled = [ @ARGV ];
109
110     my %constructor_args = (
111         map {
112             $name_to_init_arg->{$_} => $parsed_options->{$_}
113         } keys %$parsed_options,
114     );
115
116     return (
117         params    => \%constructor_args,
118         argv_copy => $argv_copy,
119         argv      => $argv_mangled,
120         ( defined($usage) ? ( usage => $usage ) : () ),
121     );
122 }
123
124 sub _getopt_get_options {
125     my ($class, $params, $opt_spec) = @_;
126     my %options;
127     Getopt::Long::GetOptions(\%options, @$opt_spec);
128     return ( \%options, undef );
129 }
130
131 sub _getopt_spec_warnings { }
132
133 sub _getopt_spec_exception {
134     my ($self, $warnings, $exception) = @_;
135     die @$warnings, $exception;
136 }
137
138 sub _getopt_full_usage {
139     my ($self, $usage) = @_;
140     $usage->die;
141 }
142
143 sub _usage_format {
144     return "usage: %c %o";
145 }
146
147 sub _traditional_spec {
148     my ( $class, %params ) = @_;
149
150     my ( @options, %name_to_init_arg, %options );
151
152     foreach my $opt ( @{ $params{options} } ) {
153         push @options, $opt->{opt_string};
154
155         my $identifier = $opt->{name};
156         $identifier =~ s/\W/_/g; # Getopt::Long does this to all option names
157
158         $name_to_init_arg{$identifier} = $opt->{init_arg};
159     }
160
161     return ( \@options, \%name_to_init_arg );
162 }
163
164 sub _compute_getopt_attrs {
165     my $class = shift;
166     grep {
167         $_->does("MooseX::Getopt::Meta::Attribute::Trait")
168             or
169         $_->name !~ /^_/
170     } grep {
171         !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
172     } $class->meta->get_all_attributes
173 }
174
175 sub _get_cmd_flags_for_attr {
176     my ( $class, $attr ) = @_;
177
178     my $flag = $attr->name;
179
180     my @aliases;
181
182     if ($attr->does('MooseX::Getopt::Meta::Attribute::Trait')) {
183         $flag = $attr->cmd_flag if $attr->has_cmd_flag;
184         @aliases = @{ $attr->cmd_aliases } if $attr->has_cmd_aliases;
185     }
186
187     return ( $flag, @aliases );
188 }
189
190 sub _attrs_to_options {
191     my $class = shift;
192     my $config_from_file = shift || {};
193
194     my @options;
195
196     foreach my $attr ($class->_compute_getopt_attrs) {
197         my ( $flag, @aliases ) = $class->_get_cmd_flags_for_attr($attr);
198
199         my $opt_string = join(q{|}, $flag, @aliases);
200
201         if ($attr->name eq 'configfile') {
202             $opt_string .= '=s';
203         }
204         elsif ($attr->has_type_constraint) {
205             my $type = $attr->type_constraint;
206             if (MooseX::Getopt::OptionTypeMap->has_option_type($type)) {
207                 $opt_string .= MooseX::Getopt::OptionTypeMap->get_option_type($type)
208             }
209         }
210
211         push @options, {
212             name       => $flag,
213             init_arg   => $attr->init_arg,
214             opt_string => $opt_string,
215             required   => $attr->is_required && !$attr->has_default && !$attr->has_builder && !exists $config_from_file->{$attr->name},
216             # NOTE:
217             # this "feature" was breaking because 
218             # Getopt::Long::Descriptive would return 
219             # the default value as if it was a command 
220             # line flag, which would then override the
221             # one passed into a constructor.
222             # See 100_gld_default_bug.t for an example
223             # - SL
224             #( ( $attr->has_default && ( $attr->is_default_a_coderef xor $attr->is_lazy ) ) ? ( default => $attr->default({}) ) : () ),
225             ( $attr->has_documentation ? ( doc => $attr->documentation ) : () ),
226         }
227     }
228
229     return @options;
230 }
231
232 no Moose::Role; 1;
233
234 __END__
235
236 =pod
237
238 =head1 NAME
239
240 MooseX::Getopt::Basic - role to implement the Getopt::Long functionality
241
242 =head1 SYNOPSIS
243
244   ## In your class
245   package My::App;
246   use Moose;
247
248   with 'MooseX::Getopt::Basic';
249
250   has 'out' => (is => 'rw', isa => 'Str', required => 1);
251   has 'in'  => (is => 'rw', isa => 'Str', required => 1);
252
253   # ... rest of the class here
254
255   ## in your script
256   #!/usr/bin/perl
257
258   use My::App;
259
260   my $app = My::App->new_with_options();
261   # ... rest of the script here
262
263   ## on the command line
264   % perl my_app_script.pl --in file.input --out file.dump
265
266 =head1 DESCRIPTION
267
268 This is like L<MooseX::Getopt> and can be used instead except that it
269 doesn't make use of L<Getopt::Long::Descriptive> (or "GLD" for short).
270
271 =head1 METHODS
272
273 =head2 new_with_options
274
275 See L<MooseX::Getopt/new_with_options>.
276
277 =head1 COPYRIGHT AND LICENSE
278
279 Copyright 2007-2008 by Infinity Interactive, Inc.
280
281 L<http://www.iinteractive.com>
282
283 This library is free software; you can redistribute it and/or modify
284 it under the same terms as Perl itself.
285
286 =cut
287