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