blib/lib/Devel/Trepan/CmdProcessor/Command/Subcmd/SubMgr.pm untested

filter: Statementstmt 0.0% 0 / 210 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 21 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 347 CC 32 SCAR 33.4
CC
32
Cov
0%
new
56.0
help
56.0
lookup
42.0
CRAP 28.1
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2011-2015 Rocky Bernstein <rocky@cpan.org>
3  
4 use warnings; use utf8;
5  
6 package Devel::Trepan::CmdProcessor::Command::SubcmdMgr;
7  
8 use File::Basename;
9 use File::Spec;
10 use if !@ISA, Devel::Trepan::CmdProcessor::Command;
11  
12 use strict;
13 use vars qw(@ISA @EXPORT $HELP $NAME @ALIASES);
14 @ISA = @CMD_ISA;
15 use vars @CMD_VARS; # Value inherited from parent
16  
17 $NAME = '?'; # FIXME: Need to define this, but should
18 # pick this up from class/file name.
19  
20 our $MIN_ARGS = 0;
21 our $MAX_ARGS = undef;
22 our $NEED_STACK = 0;
23  
24 # attr_accessor :subcmds # Trepan::Subcmd
25 # attr_reader :name # Name of command
26 # attr_reader :last_args # Last arguments seen
27  
28 no warnings 'redefine';
29  
30 # Because we use Exporter we want to silence:
31 # Use of inherited AUTOLOAD for non-method ... is deprecated
32 sub AUTOLOAD
33 {
34 my $name = our $AUTOLOAD;
35 $name =~ s/.*:://; # lose package name
36 my $target = "DynaLoader::$name";
37 goto &$target;
38 }
39  
40 # Initialize show subcommands. Note: instance variable name
41 # has to be setcmds ('set' + 'cmds') for subcommand completion
42 # to work.
43 sub new($$)
44 {
45 my ($class, $proc, $name) = @_;
46 my @prefix = split('::', $class);
47 shift @prefix; shift @prefix; shift @prefix; shift @prefix;
48 my $self = {
49 subcmds => {},
50 name => $name,
51 proc => $proc,
52 prefix => \@prefix,
53 cmd_str => join(' ', map {lc $_} @prefix)
54 };
55 # Initialization
56 my $base_prefix="Devel::Trepan::CmdProcessor::Command::";
57 my $excluded_cmd_vars = {'$HELP' => 1, '$NAME'=>2};
58 for my $field (@CMD_VARS) {
59 next if exists $excluded_cmd_vars->{$field} &&
60 $excluded_cmd_vars->{$field} == 2;
61 my $sigil = substr($field, 0, 1);
62 my $new_field = index('$@', $sigil) >= 0 ? substr($field, 1) : $field;
63 if ($sigil eq '$') {
64 my $lc_field = lc $new_field;
65 $self->{$lc_field} = eval "\$${class}::${new_field}";
66 next if exists $excluded_cmd_vars->{$field} ||
67 exists $self->{$lc_field};
68 $self->{$lc_field} = "\$${base_prefix}${new_field}";
69 }
70 }
71 no warnings;
72 my @ary = eval "${class}::ALIASES()";
73 $self->{aliases} = @ary ? [@ary] : [];
74 no strict 'refs';
75 *{"${class}::Category"} = eval "sub { ${class}::CATEGORY() }";
76 my $short_help = eval "${class}::SHORT_HELP()";
77 $self->{short_help} = $short_help if $short_help;
78 bless $self, $class;
79 $self->load_debugger_subcommands;
80 $self;
81 }
82  
83 sub load_debugger_subcommand($$)
84 {
85 my ($self, $parent_name, $pm) = @_;
86  
87 return unless -r $pm;
88 my $rc = '';
89 eval { $rc = do $pm; };
90 return if !$rc or $rc eq 'Skip me!';
91  
92 my $basename = basename($pm, '.pm');
93 my $item = sprintf("%s::%s", ucfirst($parent_name), ucfirst($basename));
94 if (-d File::Spec->catfile(dirname($pm), $basename . '_Subcmd')) {
95 push @{$self->{subcmd_names}}, $item;
96 } else {
97 push @{$self->{cmd_names}}, $item;
98 push @{$self->{cmd_basenames}}, $basename;
99 }
100 if (eval "require '$pm'; 1") {
101 return $self->setup_subcommand($parent_name, $basename);
102 } else {
103 $self->errmsg("Trouble reading ${pm}:");
104 $self->errmsg($@);
105 return 0;
106 }
107 }
108  
109 # Create an instance of each of the debugger subcommands. Commands are
110 # found by importing files in the directory 'name' + '_Subcmd'. Some
111 # files are excluded via an array set in initialize. For each of the
112 # remaining files, we 'require' them and scan for class names inside
113 # those files and for each class name, we will create an instance of
114 # that class. The set of TrepanCommand class instances form set of
115 # possible debugger commands.
116 sub load_debugger_subcommands($)
117 {
118 my ($self) = @_;
119 $self->{cmd_names} = ();
120 $self->{subcmd_names} = ();
121 $self->{cmd_basenames} = ();
122 my $cmd_dir = dirname(__FILE__);
123 my $parent_name = ucfirst $self->{name};
124 my $subcmd_dir = File::Spec->catfile($cmd_dir, '..',
125 $parent_name . '_Subcmd');
126 if (-d $subcmd_dir) {
127 my @files = glob(File::Spec->catfile($subcmd_dir, '*.pm'));
128 for my $pm (@files) {
129 $self->load_debugger_subcommand($parent_name, $pm);
130 }
131 }
132 }
133  
134 sub setup_subcommand($$$$)
135 {
136 my ($self, $parent_name, $name) = @_;
137 my $cmd_obj;
138 my $cmd_name = lc $name;
139 my $new_cmd = "\$cmd_obj=Devel::Trepan::CmdProcessor::Command::" .
140 "${parent_name}::${name}->new(\$self, '$cmd_name'); 1";
141 if (eval $new_cmd) {
142 # Add to hash of commands, and list of subcmds
143 $self->{subcmds}->{$cmd_name} = $cmd_obj;
144 $self->add($cmd_obj, $cmd_name);
145 return 1;
146 } else {
147 $self->errmsg("Error instantiating ${parent_name}::$name");
148 $self->errmsg($@);
149 return 0;
150 }
151  
152 }
153  
154 # Find subcmd in self.subcmds
155 sub lookup($$;$)
156 {
157 my ($self, $subcmd_prefix, $use_regexp) = @_;
158 $use_regexp = 0 if scalar @_ < 3;
159 my $compare;
160 if (!$self->{proc}{settings}{abbrev}) {
161 $compare = sub($) { my $name = shift; $name eq $subcmd_prefix};
162 } elsif ($use_regexp) {
163 $compare = sub($) { my $name = shift; $name =~ /^${subcmd_prefix}/};
164 } else {
165 $compare = sub($) {
166 my $name = shift; 0 == index($name, $subcmd_prefix)
167 };
168 }
169 my @candidates = ();
170 while (my ($subcmd_name, $subcmd) = each %{$self->{subcmds}}) {
171 if ($compare->($subcmd_name) &&
172 length($subcmd_prefix) >= $subcmd->{min_abbrev}) {
173 push @candidates, $subcmd;
174 }
175 }
176 if (scalar @candidates == 1) {
177 return $candidates[0];
178 }
179 return undef;
180 }
181  
182 # Show short help for a subcommand.
183 sub short_help($$$;$)
184 {
185 my ($self, $subcmd_cb, $subcmd_name, $label) = @_;
186 $label = 0 unless defined $label;
187 my $entry = $self->lookup($subcmd_name);
188 if ($entry) {
189 my $prefix = '';
190 $prefix = $entry->{name} if $label;
191 if (exist $entry->{short_help}) {
192 $prefix .= ' -- ' if $prefix;
193 $self->{proc}->msg($prefix . $entry->{short_help});
194 }
195 } else {
196 $self->{proc}->undefined_subcmd("help", $subcmd_name);
197 }
198 }
199  
200 # Add subcmd to the available subcommands for this object.
201 # It will have the supplied docstring, and subcmd_cb will be called
202 # when we want to run the command. min_len is the minimum length
203 # allowed to abbreviate the command. in_list indicates with the
204 # show command will be run when giving a list of all sub commands
205 # of this object. Some commands have long output like "show commands"
206 # so we might not want to show that.
207 sub add($$;$)
208 {
209 my ($self, $subcmd_cb, $subcmd_name) = @_;
210 $subcmd_name ||= $subcmd_cb->{name};
211  
212 # We keep a list of subcommands to assist command completion
213 push @{$self->{cmdlist}}, $subcmd_name;
214 }
215  
216 sub help($$)
217 {
218 my ($self, $args) = @_;
219 if (scalar @$args <= 2) {
220 # "help cmd". Give the general help for the command part.
221 return $self->{help};
222 }
223  
224 my $subcmd_name = $args->[2];
225 my @help_text = ();
226 my $subcmds_ref = $self->{subcmds};
227 my @subcmds = $self->list();
228  
229 if ('*' eq $subcmd_name) {
230 @help_text = (sprintf("B<List of subcommands for command I<%s>:>",
231 $self->{name}));
232 my $subcmds = $self->columnize_commands(\@subcmds); chomp $subcmds;
233 push @help_text, $subcmds;
234 return join("\n\n", @help_text);
235 }
236  
237 # "help cmd subcmd". Give help specific for that subcommand.
238 my $cmd = $self->lookup($subcmd_name, 0);
239 if (defined $cmd) {
240 if ($cmd->can("help")) {
241 return $cmd->help($args);
242 } else {
243 return $cmd->{help};
244 }
245 } else {
246 my $proc = $self->{proc};
247 my @matches = sort(grep /^$subcmd_name/, @subcmds);
248 my $name = $self->{name};
249 if (0 == scalar @matches) {
250 $proc->errmsg("No ${name} subcommands found matching /^{$subcmd_name}/. Try \"help $name *\".");
251 return undef;
252 } elsif (1 == scalar @matches) {
253 $args->[-1] = $matches[0];
254 $self->help($args);
255 } else {
256 # pod2text formatting used below. That's why B<>, I<> and
257 # \n\n for \n.
258 @help_text = ("B<Subcommands of I<$name> matching /^$subcmd_name/:>");
259 my @sort_matches = sort @matches;
260 push @help_text, $self->columnize_commands(\@sort_matches);
261 return join("\n\n", @help_text);
262 }
263 }
264 }
265  
266 sub list($) {
267 my $self = shift;
268 sort keys %{$self->{subcmds}};
269 }
270  
271 # # Return an Array of subcommands that can start with +arg+. If none
272 # # found we just return +arg+.
273 # # FIXME: Not used any more?
274 # sub complete(prefix)
275 # Trepan::Complete.complete_token(@subcmds.subcmds.keys, prefix)
276 # }
277  
278 sub complete_token_with_next($$;$)
279 {
280 my ($self, $prefix, $cmd_prefix) = @_;
281 my $subcmds = $self->{subcmds};
282 Devel::Trepan::Complete::complete_token_with_next($subcmds, $prefix);
283 }
284  
285 sub run($$)
286 {
287 my ($self, $args) = @_;
288 $self->{last_args} = $args;
289 my $args_len = scalar @$args;
290 if ($args_len < 2 || $args_len == 2 && $args->[-1] eq '*') {
291 $self->{proc}->summary_list($self->{name}, $self->{subcmds});
292 return 0;
293 }
294  
295 my $subcmd_prefix = $args->[1];
296 # We were given: cmd subcmd ...
297 # Run that.
298 my $subcmd = $self->lookup($subcmd_prefix);
299 if ($subcmd) {
300 if ($self->{proc}->ok_for_running($subcmd, $subcmd->{cmd_str},
301 $args_len-2)) {
302 $subcmd->run($args);
303 }
304 } else {
305 $self->{proc}->undefined_subcmd($self->{name}, $subcmd_prefix);
306 }
307 }
308  
309 unless(caller) {
310 # Demo it.
311 require Devel::Trepan::CmdProcessor;
312 my $cmdproc = Devel::Trepan::CmdProcessor->new(undef, 'bogus');
313 require Devel::Trepan::CmdProcessor::Command::Set;
314 my $mgr = Devel::Trepan::CmdProcessor::Command::Set->new($cmdproc, 'set');
315 printf "name: %s, cmd_str: %s\n", $mgr->{name}, $mgr->{cmd_str};
316 print "subcmds: ", join(', ', $mgr->list), "\n";
317 print $mgr->lookup('abbrev'), "\n";
318 }
319  
320 1;