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