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