Add extra tests and changes for config_from file.
[gitmo/MooseX-Getopt.git] / lib / MooseX / Getopt / Basic.pm
CommitLineData
33edcaa4 1
ef47fe44 2package MooseX::Getopt::Basic;
3use Moose::Role;
4
30ed85f7 5use MooseX::Getopt::OptionTypeMap;
6use MooseX::Getopt::Meta::Attribute;
7use MooseX::Getopt::Meta::Attribute::NoGetopt;
8use Carp ();
9
33edcaa4 10use Getopt::Long ();
30ed85f7 11
12has ARGV => (is => 'rw', isa => 'ArrayRef', metaclass => "NoGetopt");
13has extra_argv => (is => 'rw', isa => 'ArrayRef', metaclass => "NoGetopt");
14
3d232413 15sub _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
30ed85f7 23sub new_with_options {
24 my ($class, @params) = @_;
25
3d232413 26 my $constructor_params = ( @params == 1 ? $params[0] : {@params} );
27
28 my ($config_from_file, $configfile);
30ed85f7 29 if($class->meta->does_role('MooseX::ConfigFromFile')) {
30 local @ARGV = @ARGV;
31
3d232413 32 $configfile = $class->_get_configfile_from_cli;
33 if(!defined $configfile) {
34 $configfile = $constructor_params->{configfile};
35 }
30ed85f7 36
37 if(!defined $configfile) {
38 my $cfmeta = $class->meta->find_attribute_by_name('configfile');
39 $configfile = $cfmeta->default if $cfmeta->has_default;
33edcaa4 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 }
5ab6d553 52 }
30ed85f7 53 }
33edcaa4 54 else {
55 $config_from_file = $class->get_config_from_file($configfile);
56 }
30ed85f7 57 }
58
30ed85f7 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
3d232413 69 my $params = $config_from_file ? { configfile => $configfile, %$config_from_file, %{$processed{params}} } : $processed{params};
30ed85f7 70
71 # did the user request usage information?
72 if ( $processed{usage} && ($params->{'?'} or $params->{help} or $params->{usage}) )
73 {
33edcaa4 74 $class->_getopt_full_usage($processed{usage});
30ed85f7 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
33edcaa4 85sub _getopt_spec { shift->_traditional_spec(@_); }
8df55e62 86
30ed85f7 87sub _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
33edcaa4 97 my @warnings;
30ed85f7 98 my ( $parsed_options, $usage ) = eval {
33edcaa4 99 local $SIG{__WARN__} = sub { push @warnings, @_ };
30ed85f7 100
33edcaa4 101 return $class->_getopt_get_options(\%params, $opt_spec);
30ed85f7 102 };
103
33edcaa4 104 $class->_getopt_spec_warnings(@warnings) if @warnings;
105 $class->_getopt_spec_exception(\@warnings, $@) if $@;
30ed85f7 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
33edcaa4 124sub _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
131sub _getopt_spec_warnings { }
132
133sub _getopt_spec_exception {
134 my ($self, $warnings, $exception) = @_;
135 die @$warnings, $exception;
136}
137
138sub _getopt_full_usage {
139 my ($self, $usage) = @_;
140 $usage->die;
141}
142
30ed85f7 143sub _usage_format {
144 return "usage: %c %o";
145}
146
147sub _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
4f214b88 155 my $identifier = $opt->{name};
30ed85f7 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
30ed85f7 164sub _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
175sub _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
190sub _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
232no Moose::Role; 1;
233
33edcaa4 234__END__
ef47fe44 235
236=pod
237
238=head1 NAME
239
33edcaa4 240MooseX::Getopt::Basic - role to implement the Getopt::Long functionality
ef47fe44 241
242=head1 SYNOPSIS
243
244 ## In your class
245 package My::App;
246 use Moose;
247
ff71d314 248 with 'MooseX::Getopt::Basic';
ef47fe44 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
ff71d314 264 % perl my_app_script.pl --in file.input --out file.dump
ef47fe44 265
266=head1 DESCRIPTION
267
ff71d314 268This is like L<MooseX::Getopt> and can be used instead except that it
269doesn't make use of L<Getopt::Long::Descriptive> (or "GLD" for short).
ef47fe44 270
271=head1 METHODS
272
33edcaa4 273=head2 new_with_options
ef47fe44 274
33edcaa4 275See L<MooseX::Getopt/new_with_options>.
ff71d314 276
ef47fe44 277=head1 COPYRIGHT AND LICENSE
278
279Copyright 2007-2008 by Infinity Interactive, Inc.
280
281L<http://www.iinteractive.com>
282
283This library is free software; you can redistribute it and/or modify
284it under the same terms as Perl itself.
285
286=cut
287