blib/lib/MOP4Import/Base/CLI_Opts.pm untested

filter: Statementstmt 0.0% 0 / 316 Branchbran 0.0% 0 / 140 Conditioncond 0.0% 0 / 59 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 554 CC 70 SCAR 54.9
CC
70
Cov
0%
parse_opts_for_cli_opts
600.0
configure_for_cli_opts
342.0
declare_options
90.0
CRAP 242.0
1 package MOP4Import::Base::CLI_Opts;
2 use strict;
3 use warnings;
4 use MOP4Import::Base::CLI -as_base
5 # , [extend => FieldSpec => qw/type alias/]
6 , [fields => qw/_cmd __cmd/]
7 ;
8 use MOP4Import::Opts;
9 use Carp ();
10 use Data::Dumper;
11  
12 use constant DEBUG => $ENV{DEBUG_MOP4IMPORT};
13  
14 use MOP4Import::Types::Extend
15 FieldSpec => [[fields => qw/type alias command real_name required for_subcmd/]];
16  
17 print STDERR "FieldSpec = ", FieldSpec, "\n" if DEBUG;
18  
19 sub new {
20 my MY $self = fields::new(shift);
21 my $pre = {};
22 $self->configure_for_cli_opts($pre, @_);
23 $self->after_new;
24 $self;
25 }
26  
27 sub invoke {
28 my ( $self, $cmd, @args ) = @_;
29 $self->{_cmd} = $cmd;
30 if ( my $subref = $self->can("cmd_$cmd") ) {
31 $self->configure_for_cli_opts({for_subcmd => 1}, @args);
32 $subref->($self, @args);
33 }
34 else {
35 Carp::croak("Cmd `$cmd` is not implemented.\n");
36 }
37 }
38  
39  
40 use MOP4Import::Opts qw/Opts m4i_args m4i_opts/;
41 use MOP4Import::Util;
42  
43 sub import {
44 my ($myPack, @decls) = @_;
45  
46 m4i_log_start() if DEBUG;
47  
48 if ( (grep { $_ eq '-as_base' } @decls) && not (grep { $_ eq 'options' } map { ref($_) ? @$_ : $_ } @decls) ) {
49 DEBUG && print STDERR "Because of no 'options', we set 'help' and 'version' automatically.\n";
50 push @decls, [
51 options =>
52 ['help|h', 'command', 'help'],
53 ['version', 'command', 'version'],
54 ];
55 }
56  
57 my Opts $opts = m4i_opts([caller]);
58  
59 @decls = $myPack->default_exports unless @decls;
60  
61 $myPack->dispatch_declare($opts, $myPack->always_exports, @decls);
62  
63 m4i_log_end($opts->{callpack}) if DEBUG;
64 }
65  
66  
67 sub default_options {
68 return (
69 help => ['command' => 'help', 'type' => 'flag', 'alias' => 'h'],
70 version => ['command' => 'version', 'type' => 'flag'],
71 );
72 }
73  
74  
75 sub _default_opt {
76 my ( $myPack, $decls ) = @_;
77 my %auto = $myPack->default_options;
78 my %rev_alias = map { # aliasの逆リンクをつくる
79 my %pair = @{ $auto{$_} };
80 defined $pair{alias} ? ($pair{alias} => $_) : ();
81 } keys %auto;
82  
83 for my $dec (@$decls) {
84 if ( $dec->[0] =~ /^([-a-zA-Z0-9]+)(?:\|([a-zA-Z0-9]))?(?:=[is]@?)?$/ ) {
85 my $optname = $1;
86 my $alias = $2 // '';
87 for my $k ( $optname, $alias ) {
88 my $rev_alias = $rev_alias{$k};
89 my %opt = @{$auto{$k} || []};
90 if ( exists $opt{alias} ) { # オプションがユーザー定義されているならaliasも不要
91 delete $auto{$opt{alias}};
92 }
93 if ( $rev_alias ) {
94 my %pair = @{ $auto{$rev_alias} || [] };
95 delete $pair{alias};
96 $auto{$rev_alias} = [%pair] if exists $auto{$rev_alias};
97 }
98 delete $auto{$k};
99 }
100 }
101 }
102  
103 for my $k ( sort keys %auto ) {
104 push @$decls, [$k, @{$auto{$k}}];
105 }
106 #print "decls:", Dumper($decls);
107 }
108  
109 sub declare_options {
110 (my $myPack, my Opts $opts, my (@decls)) = m4i_args(@_);
111  
112 $myPack->_default_opt(\@decls);
113  
114 $myPack->declare_fields($opts, map {
115 my $o = ref $_ ? $_ : [$_];
116  
117 unless ( $o->[0] =~ /([-\w]+)(?:\|([-\w]+))?(?:=([is]@?))?/ ) {
118 Carp::croak("Invalid option format - " . $o->[0]);
119 }
120  
121 my ($optline, %pair) = @$o;
122 if (exists $pair{'for_subcmd'}) {
123 if ( ref $pair{'for_subcmd'} ) {
124 $pair{'for_subcmd'} = +{ map { $_ => 1 } @{ $pair{'for_subcmd'} } };
125 }
126 elsif ( $pair{'for_subcmd'} ne '1' ) {
127 $pair{'for_subcmd'} = { $pair{'for_subcmd'} => 1 };
128 }
129 @$o = ($optline, %pair);
130 }
131  
132 my ($name, $alias, $type) = ($1, $2, $3);
133 $type ||= 'flag';
134 if (DEBUG) {
135 print STDERR $name;
136 if (defined $alias) {print " - $alias"}
137 print STDERR " = $type";
138 print "\n";
139 }
140 push @$o, real_name => $name;
141 $name =~ s/-/_/g;
142 $o->[0] = $name;
143 push @$o, alias => $alias if defined $alias;
144 push @$o, type => $type;
145 $o;
146 } @decls);
147 }
148  
149 sub parse_opts_for_cli_opts {
150 my ($class, $list, $result, @rest) = @_;
151 my $fields = MOP4Import::Declare::fields_hash($class);
152 print STDERR "fields for $class : ", Data::Dumper->new([$fields])->Dump, "\n" if DEBUG;
153  
154 my %alias;
155 my $form = {};
156 my $preserve = (ref($result) && scalar(@$result) && $result->[0]) ? shift(@$result) : {};
157 unshift @{ $result }, { %$preserve, without_value => {} }; # SUPER::parse_optsで失われると困る情報を保持
158  
159 {
160 foreach my $name (keys %$fields) {
161 my FieldSpec $spec = $fields->{$name};
162 if ( UNIVERSAL::isa($spec, FieldSpec) ) {
163 if ( $preserve->{for_subcmd} ) { # at this time, $class is a created object.
164 next if not $spec->{for_subcmd};
165 if ( ref $spec->{for_subcmd} ) {
166 next unless $spec->{for_subcmd}->{ $class->{_cmd} };
167 }
168 }
169 elsif ( $spec->{for_subcmd} ) {
170 next;
171 }
172  
173 $form->{ $name } = $spec if $spec->{type};
174 if ( $spec->{alias} ) {
175 $alias{$spec->{alias}} = $name;
176 $form->{ $spec->{alias} } = $form->{ $name };
177 }
178 }
179 }
180 }
181 print STDERR "option format: ", Data::Dumper->new([$form])->Dump, "\n" if DEBUG;
182 my $key = 1;
183 my @stack;
184 my $cmd;
185 my $req_value;
186 for my $arg ( @$list ) {
187 if ( $key ) {
188 if ( $arg =~ /^-([^=]+)=(.+)$/ ) { # -f=foo
189 push @stack, $arg;
190 }
191 elsif ( $arg =~ /^--([^=]+)=(.+)$/ ) { # --foo=baz
192 push @stack, $arg;
193 }
194 elsif ( !$cmd && $arg =~ /^-([^-=]+)/ ) { # -fb( value)
195 my $myaby_opts = $1;
196 for my $s (split//, $myaby_opts) {
197 if ( not defined $form->{$s} ) {
198 Carp::croak("Invalid option format - " . $arg);
199 }
200 if ( $form->{$s}->{type} ne 'flag' ) {
201 push @stack, '-' . $s;
202 $key = 0;
203 if (not $req_value) {
204 $req_value = $myaby_opts;
205 }
206 }
207 else {
208 push @stack, '-' . $s;
209 }
210 }
211 }
212 elsif ( !$cmd && $arg =~ /^--([^=]+)/ ) { # --bar( value)
213 if ( not defined $form->{_hyphen2underscore($1)} ) {
214 Carp::croak("Invalid option format - " . $arg);
215 }
216 if ( $form->{_hyphen2underscore($1)}->{type} ne 'flag' ) {
217 push @stack, $arg;
218 $key = 0;
219 if (not $req_value) {
220 $req_value = _hyphen2underscore($1);
221 }
222 }
223 else {
224 push @stack, $arg;
225 }
226 }
227 else { # perhaps this is command!
228 $cmd = $arg;
229 push @stack, $arg;
230 }
231 }
232 else { # change to Base::CLI aware format
233 $stack[-1] .= '=' . $arg;
234 $key = 1;
235 $req_value = '';
236 }
237 }
238 #print Dumper($list);
239 #print Dumper(\@stack);
240 @$list = @stack;
241  
242 if ($req_value) {
243 $result->[0]->{without_value}->{ $req_value } = 1;
244 }
245  
246 $class->parse_opts($list, $result, \%alias, @rest);
247 }
248  
249  
250 sub configure_for_cli_opts {
251 my ( $self, @args ) = @_;
252 my $fields = MOP4Import::Declare::fields_hash($self);
253 my @res;
254 my %map;
255 my $command;
256  
257 my $preserved = shift @args;
258  
259 my (%required, %default);
260 for my $spec ( values %$fields ) {
261 next unless UNIVERSAL::isa($spec, FieldSpec);
262 next if ( $preserved->{for_subcmd} and not $spec->{for_subcmd} );
263 next if ( not $preserved->{for_subcmd} and $spec->{for_subcmd} );
264 if ( $preserved->{for_subcmd} and ref($spec->{for_subcmd}) and not $spec->{for_subcmd}->{ $self->{_cmd} } ) {
265 next;
266 }
267 $required{ $spec->{name} } = $spec->{required} if exists $spec->{required};
268 $default{ $spec->{name} } = $spec->{default} if exists $spec->{default};
269 if ( $spec->{alias} && exists $preserved->{without_value}->{ $spec->{alias} } ) {
270 $preserved->{without_value}->{ $spec->{name} } = $preserved->{without_value}->{ $spec->{alias} };
271 delete $preserved->{without_value}->{ $spec->{alias} };
272 }
273 }
274  
275 while ( defined(my $name = shift @args) ) {
276 my $type = $fields->{$name}->{type} // '';
277 my $val = shift(@args);
278  
279 if ( $type =~ /(.)@/ ) {
280 if ( $1 eq 'i' ) {
281 if ( $val !~ /^[0-9]+$/ ) {
282 Carp::croak("option `$name` takes integer.");
283 }
284 }
285  
286 if (not exists $map{$name}) {
287 push @res, $name;
288 push @res, [$val];
289 $map{$name} = $#res;
290 }
291 else {
292 push @{ $res[ $map{$name} ] }, $val;
293 }
294 next;
295 }
296 elsif ( $type eq 'i' ) {
297 if ( $val !~ /^[0-9]+$/ ) {
298 Carp::croak("option `$name` takes integer.");
299 }
300 }
301  
302 if ( $fields->{$name}->{command} ) {
303 if ( defined $command ) {
304 Carp::croak("command invoking option was already called before `$name`.");
305 }
306 $command = $fields->{$name}->{command};
307 $self->{__cmd} = [$command, $val];
308 next;
309 }
310  
311 delete $required{$name} if not exists $preserved->{without_value}->{ $name };
312 delete $default{$name};
313  
314 push @res, $name;
315 push @res, $val;
316 }
317  
318 for my $key (keys %default) {
319 push @res, $key, $default{$key};
320 delete $required{$key};
321 }
322 if (%required) {
323 my $opt = (sort keys %required)[0];
324 Carp::croak("$opt is required.");
325 }
326 #print Dumper([@res]);
327 $self->configure(@res);
328 }
329  
330  
331 sub cmd_default { }
332  
333 sub cmd_version {
334 my $v = shift->VERSION // '0.0';
335 print "$v\n";
336 }
337  
338 sub cmd_help { # From MOP4Import::Base::CLI, original cmd_help do 'die'
339 my $self = shift;
340 my $pack = ref $self || $self;
341 my $fields = MOP4Import::Declare::fields_hash($self);
342 my $names = MOP4Import::Declare::fields_array($self);
343  
344 require MOP4Import::Util::FindMethods;
345  
346 my @methods = MOP4Import::Util::FindMethods::FindMethods($pack, sub {s/^cmd_//});
347  
348 print join("\n", <<END);
349 Usage: @{[File::Basename::basename($0)]} [--opt=value].. <command> [--opt=value].. ARGS...
350  
351 Commands:
352 @{[join("\n ", @methods)]}
353 END
354  
355 my $max_len = 0;
356 my %opt;
357 for my $name ( grep {/^[a-z]/} @$names ) {
358 my FieldSpec $fs = $fields->{$name};
359 my $cmds = ['__common__'];
360 my $str;
361 if (ref $fs) {
362 $str =
363 do{ ' --' . (UNIVERSAL::isa($fs, FieldSpec) ? ($fs->{real_name} // '') : $name) } .
364 do{ UNIVERSAL::isa($fs, FieldSpec) and $fs->{ alias } ? ', -' . $fs->{ alias } : '' },
365 ;
366 if ( exists $fs->{for_subcmd} ) {
367 if ( ref $fs->{for_subcmd} ) {
368 $cmds = [ sort keys %{ $fs->{for_subcmd} } ];
369 }
370 }
371 }
372 else {
373 $str = $name;
374 }
375 $max_len = length $str if length $str > $max_len;
376  
377 next if $str eq ' --';
378  
379 for my $name ( @$cmds ) {
380 push @{ $opt{ $name } }, [$str, $fs->{doc} ? $fs->{doc} : ''];
381 }
382 }
383  
384 my @opts = [ 'common option', delete $opt{'__common__'} ];
385 push @opts, map { [ 'for ' . $_ => $opt{$_} ] } sort keys %opt;
386  
387 print join("\n", <<END);
388  
389 Options:
390 END
391  
392 $max_len += 2;
393 for my $optset ( @opts ) {
394 my ( $subcmd, $opts ) = @$optset;
395 print " [$subcmd]\n";
396 for my $opt (@$opts) {
397 printf( "%-${max_len}s%s\n", @$opt );
398 }
399 print "\n";
400 }
401  
402 exit();
403 }
404  
405 sub run {
406 my ($class, $arglist) = @_;
407 my $default_cmd = 'default';
408 my $fields = MOP4Import::Declare::fields_hash($class);
409 # $arglist を parse し、 $class->new 用のパラメータリストを作る
410 my @opts = $class->parse_opts_for_cli_opts($arglist);
411 my MY $obj = fields::new($class);
412 $obj->configure_for_cli_opts(@opts);
413 $obj->after_new;
414 # 次の引数を取り出して、サブコマンドとして解釈を試みる
415 my $cmd = shift @$arglist || _set_cmd_by_option($obj, $arglist) || $default_cmd;
416 $obj->{_cmd} = $cmd;
417 my $result = [ { for_subcmd => 1 } ];
418 $obj->configure_for_cli_opts(@{ $obj->parse_opts_for_cli_opts($arglist, $result) });
419 # サブコマンド毎の処理を行う
420 # 結果を何らかの形式で出力する
421 # 望ましい終了コードを返す(差し当たり、必要ならば各メソッド内で指定する)
422 if (my $sub = $obj->can("cmd_$cmd")) {
423 $sub->($obj, @$arglist);
424 } else {
425 print STDERR "Cmd `$cmd` is not implemented.\n";
426 exit(1);
427 }
428 }
429  
430 sub _hyphen2underscore {
431 my ($v) = @_;
432 $v =~ tr/-/_/;
433 return $v;
434 }
435  
436 sub _set_cmd_by_option {
437 my ($obj, $arglist) = @_;
438 return unless $obj->{__cmd};
439 push @$arglist, $obj->{__cmd}->[1];
440 return $obj->{__cmd}->[0];
441 }
442  
443 1;