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