allow for has configfile => ( init_arg => 0 )
[gitmo/MooseX-Getopt.git] / lib / MooseX / Getopt / Basic.pm
1 package MooseX::Getopt::Basic;
2 # ABSTRACT: MooseX::Getopt::Basic - role to implement the Getopt::Long functionality
3
4 use Moose::Role;
5
6 use MooseX::Getopt::OptionTypeMap;
7 use MooseX::Getopt::Meta::Attribute;
8 use MooseX::Getopt::Meta::Attribute::NoGetopt;
9 use MooseX::Getopt::ProcessedArgv;
10 use Try::Tiny;
11 use Carp ();
12
13 use Getopt::Long 2.37 ();
14
15 has ARGV       => (is => 'rw', isa => 'ArrayRef', traits => ['NoGetopt']);
16 has extra_argv => (is => 'rw', isa => 'ArrayRef', traits => ['NoGetopt']);
17
18 sub process_argv {
19     my ($class, @params) = @_;
20
21     my $constructor_params = ( @params == 1 ? $params[0] : {@params} );
22
23     my $config_from_file;
24     if($class->meta->does_role('MooseX::ConfigFromFile')) {
25         local @ARGV = @ARGV;
26
27         # just get the configfile arg now out of @ARGV; the rest of the args
28         # will be fetched later
29         my $configfile;
30         my $opt_parser = Getopt::Long::Parser->new( config => [ qw( no_auto_help pass_through no_auto_version ) ] );
31         $opt_parser->getoptions( "configfile=s" => \$configfile );
32
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;
39             $configfile = $constructor_params->{$key} if defined $key;
40         }
41
42         if(!defined $configfile) {
43             $configfile = $cfmeta->default if $cfmeta->has_default;
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) {
50                 $config_from_file = try {
51                     $class->get_config_from_file($configfile);
52                 }
53                 catch {
54                     die $_ unless /Specified configfile '\Q$configfile\E' does not exist/;
55                 };
56             }
57         }
58         else {
59             $config_from_file = $class->get_config_from_file($configfile);
60         }
61     }
62
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?
76     if ( $processed{usage} and $params->{help_flag} ) {
77         $class->print_usage_text($processed{usage});
78     }
79
80     return MooseX::Getopt::ProcessedArgv->new(
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
86     );
87 }
88
89 sub new_with_options {
90     my ($class, @params) = @_;
91
92     my $pa = $class->process_argv(@params);
93
94     $class->new(
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
100     );
101 }
102
103 sub _getopt_spec { shift->_traditional_spec(@_); }
104
105 sub _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
115     my @warnings;
116     my ( $parsed_options, $usage ) = try {
117         local $SIG{__WARN__} = sub { push @warnings, @_ };
118
119         return $class->_getopt_get_options(\%params, $opt_spec);
120     }
121     catch {
122         $class->_getopt_spec_exception(\@warnings, $_);
123     };
124
125     $class->_getopt_spec_warnings(@warnings) if @warnings;
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
144 sub _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
151 sub _getopt_spec_warnings { }
152
153 sub _getopt_spec_exception {
154     my ($self, $warnings, $exception) = @_;
155     die @$warnings, $exception;
156 }
157
158 # maintained for backwards compatibility only
159 sub _getopt_full_usage
160 {
161     my ($self, $usage) = @_;
162     print $usage->text;
163     exit 0;
164 }
165 #(this is already documented in MooseX::Getopt. But FIXME later, via RT#82195)
166 =for Pod::Coverage
167     print_usage_text
168 =cut
169 sub print_usage_text { shift->_getopt_full_usage(@_) }
170
171 sub _usage_format {
172     return "usage: %c %o";
173 }
174
175 sub _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
183         my $identifier = $opt->{name};
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
192 sub _compute_getopt_attrs {
193     my $class = shift;
194     sort { $a->insertion_order <=> $b->insertion_order }
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
204 sub _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
219 sub _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:
246             # this "feature" was breaking because
247             # Getopt::Long::Descriptive would return
248             # the default value as if it was a command
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
261 no Moose::Role;
262 1;
263
264 =head1 SYNOPSIS
265
266   ## In your class
267   package My::App;
268   use Moose;
269
270   with 'MooseX::Getopt::Basic';
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
286   % perl my_app_script.pl --in file.input --out file.dump
287
288 =head1 DESCRIPTION
289
290 This is like L<MooseX::Getopt> and can be used instead except that it
291 doesn't make use of L<Getopt::Long::Descriptive> (or "GLD" for short).
292
293 =method new_with_options
294
295 See L<MooseX::Getopt/new_with_options>.
296
297 =method process_argv
298
299 See L<MooseX::Getopt/process_argv>.
300
301 =cut