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