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