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