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