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