print --usage, --help to stdout not stderr
[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;
f3615693 9use MooseX::Getopt::ProcessedArgv;
30ed85f7 10use Carp ();
11
669588e2 12use Getopt::Long 2.37 ();
30ed85f7 13
14has ARGV => (is => 'rw', isa => 'ArrayRef', metaclass => "NoGetopt");
15has extra_argv => (is => 'rw', isa => 'ArrayRef', metaclass => "NoGetopt");
16
f3615693 17sub process_argv {
30ed85f7 18 my ($class, @params) = @_;
19
20 my $config_from_file;
21 if($class->meta->does_role('MooseX::ConfigFromFile')) {
22 local @ARGV = @ARGV;
23
94c4db8f 24 # just get the configfile arg now; the rest of the args will be
25 # fetched later
30ed85f7 26 my $configfile;
7a8392d6 27 my $opt_parser = Getopt::Long::Parser->new( config => [ qw( no_auto_help pass_through no_auto_version ) ] );
30ed85f7 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;
33edcaa4 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 }
5ab6d553 45 }
30ed85f7 46 }
33edcaa4 47 else {
48 $config_from_file = $class->get_config_from_file($configfile);
49 }
30ed85f7 50 }
51
52 my $constructor_params = ( @params == 1 ? $params[0] : {@params} );
8df55e62 53
30ed85f7 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?
f9b21bbf 67 if ( $processed{usage} and $params->{help_flag} ) {
33edcaa4 68 $class->_getopt_full_usage($processed{usage});
30ed85f7 69 }
70
f9b21bbf 71 return MooseX::Getopt::ProcessedArgv->new(
f3615693 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
f9b21bbf 77 );
f3615693 78}
79
80sub new_with_options {
81 my ($class, @params) = @_;
82
f9b21bbf 83 my $pa = $class->process_argv(@params);
f3615693 84
30ed85f7 85 $class->new(
f3615693 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
f9b21bbf 91 );
30ed85f7 92}
93
33edcaa4 94sub _getopt_spec { shift->_traditional_spec(@_); }
8df55e62 95
30ed85f7 96sub _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
33edcaa4 106 my @warnings;
30ed85f7 107 my ( $parsed_options, $usage ) = eval {
33edcaa4 108 local $SIG{__WARN__} = sub { push @warnings, @_ };
30ed85f7 109
33edcaa4 110 return $class->_getopt_get_options(\%params, $opt_spec);
30ed85f7 111 };
112
33edcaa4 113 $class->_getopt_spec_warnings(@warnings) if @warnings;
114 $class->_getopt_spec_exception(\@warnings, $@) if $@;
30ed85f7 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
33edcaa4 133sub _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
140sub _getopt_spec_warnings { }
141
142sub _getopt_spec_exception {
143 my ($self, $warnings, $exception) = @_;
144 die @$warnings, $exception;
145}
146
147sub _getopt_full_usage {
148 my ($self, $usage) = @_;
c885acae 149 print $usage->text;
150 exit 0;
33edcaa4 151}
152
30ed85f7 153sub _usage_format {
154 return "usage: %c %o";
155}
156
157sub _traditional_spec {
158 my ( $class, %params ) = @_;
159
160 my ( @options, %name_to_init_arg, %options );
161
162 foreach my $opt ( @{ $params{options} } ) {
163 push @options, $opt->{opt_string};
164
4f214b88 165 my $identifier = $opt->{name};
30ed85f7 166 $identifier =~ s/\W/_/g; # Getopt::Long does this to all option names
167
168 $name_to_init_arg{$identifier} = $opt->{init_arg};
169 }
170
171 return ( \@options, \%name_to_init_arg );
172}
173
30ed85f7 174sub _compute_getopt_attrs {
175 my $class = shift;
73038480 176 sort { $a->insertion_order <=> $b->insertion_order }
30ed85f7 177 grep {
178 $_->does("MooseX::Getopt::Meta::Attribute::Trait")
179 or
180 $_->name !~ /^_/
181 } grep {
182 !$_->does('MooseX::Getopt::Meta::Attribute::Trait::NoGetopt')
183 } $class->meta->get_all_attributes
184}
185
186sub _get_cmd_flags_for_attr {
187 my ( $class, $attr ) = @_;
188
189 my $flag = $attr->name;
190
191 my @aliases;
192
193 if ($attr->does('MooseX::Getopt::Meta::Attribute::Trait')) {
194 $flag = $attr->cmd_flag if $attr->has_cmd_flag;
195 @aliases = @{ $attr->cmd_aliases } if $attr->has_cmd_aliases;
196 }
197
198 return ( $flag, @aliases );
199}
200
201sub _attrs_to_options {
202 my $class = shift;
203 my $config_from_file = shift || {};
204
205 my @options;
206
207 foreach my $attr ($class->_compute_getopt_attrs) {
208 my ( $flag, @aliases ) = $class->_get_cmd_flags_for_attr($attr);
209
210 my $opt_string = join(q{|}, $flag, @aliases);
211
212 if ($attr->name eq 'configfile') {
213 $opt_string .= '=s';
214 }
215 elsif ($attr->has_type_constraint) {
216 my $type = $attr->type_constraint;
217 if (MooseX::Getopt::OptionTypeMap->has_option_type($type)) {
218 $opt_string .= MooseX::Getopt::OptionTypeMap->get_option_type($type)
219 }
220 }
221
222 push @options, {
223 name => $flag,
224 init_arg => $attr->init_arg,
225 opt_string => $opt_string,
226 required => $attr->is_required && !$attr->has_default && !$attr->has_builder && !exists $config_from_file->{$attr->name},
227 # NOTE:
2557b526 228 # this "feature" was breaking because
229 # Getopt::Long::Descriptive would return
230 # the default value as if it was a command
30ed85f7 231 # line flag, which would then override the
232 # one passed into a constructor.
233 # See 100_gld_default_bug.t for an example
234 # - SL
235 #( ( $attr->has_default && ( $attr->is_default_a_coderef xor $attr->is_lazy ) ) ? ( default => $attr->default({}) ) : () ),
236 ( $attr->has_documentation ? ( doc => $attr->documentation ) : () ),
237 }
238 }
239
240 return @options;
241}
242
669588e2 243no Moose::Role;
2441;
ef47fe44 245
246=head1 SYNOPSIS
247
248 ## In your class
249 package My::App;
250 use Moose;
251
ff71d314 252 with 'MooseX::Getopt::Basic';
ef47fe44 253
254 has 'out' => (is => 'rw', isa => 'Str', required => 1);
255 has 'in' => (is => 'rw', isa => 'Str', required => 1);
256
257 # ... rest of the class here
258
259 ## in your script
260 #!/usr/bin/perl
261
262 use My::App;
263
264 my $app = My::App->new_with_options();
265 # ... rest of the script here
266
267 ## on the command line
ff71d314 268 % perl my_app_script.pl --in file.input --out file.dump
ef47fe44 269
270=head1 DESCRIPTION
271
ff71d314 272This is like L<MooseX::Getopt> and can be used instead except that it
273doesn't make use of L<Getopt::Long::Descriptive> (or "GLD" for short).
ef47fe44 274
669588e2 275=method new_with_options
ef47fe44 276
33edcaa4 277See L<MooseX::Getopt/new_with_options>.
ff71d314 278
e8e1e4b3 279=method process_argv
280
281See L<MooseX::Getopt/process_agv>.
282
ef47fe44 283=cut