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