| 1 | package CLI::Framework::Command::Tree; | ||
| 2 | use base qw( CLI::Framework::Command::Meta ); | ||
| 3 | |||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | |||
| 7 | our $VERSION = 0.01; | ||
| 8 | |||
| 9 | #------- | ||
| 10 | |||
| 11 | sub usage_text { | ||
| 12 | q{ | ||
| 13 | tree: tree view of the names of only those commands that are currently registered in the application | ||
| 14 | } | ||
| 15 | } | ||
| 16 | |||
| 17 | sub run { | ||
| 18 | my ($self, $opts, @args) = @_; | ||
| 19 | |||
| 20 | my $app = $self->get_app(); # metacommand is app-aware | ||
| 21 | |||
| 22 | my $tree = command_tree( $app ); | ||
| 23 | $tree =~ s/^/\t/gm; | ||
| 24 | return $tree; | ||
| 25 | } | ||
| 26 | |||
| 27 | #------- | ||
| 28 | |||
| 29 | sub command_tree { | ||
| 30 | my ($app, $root, $indent, $tree) = @_; | ||
| 31 | |||
| 32 | $root ||= $app; | ||
| 33 | $indent ||= 0; | ||
| 34 | |||
| 35 | # (output object) | ||
| 36 | $tree = { text => '' } unless ref $tree; | ||
| 37 | |||
| 38 | $indent += 4 if( $root->isa( 'CLI::Framework::Command' ) ); | ||
| 39 | |||
| 40 | # For every command registered into the root object (either a CLIF | ||
| 41 | # Application or a CLIF Command), append its tree representation to the | ||
| 42 | # output object... | ||
| 43 | |||
| 44 | # Use proper accessors for object type... | ||
| 45 | my $registered_command_names_accessor = 'registered_command_names'; | ||
| 46 | my $registered_command_obj_accessor = 'registered_command_object'; | ||
| 47 | if( $root->isa('CLI::Framework::Command') ) { | ||
| 48 | $registered_command_names_accessor = 'registered_subcommand_names'; | ||
| 49 | $registered_command_obj_accessor = 'registered_subcommand_object'; | ||
| 50 | } | ||
| 51 | my @command_names; | ||
| 52 | { no strict 'refs'; | ||
| 53 | @command_names = $root->$registered_command_names_accessor; | ||
| 54 | } | ||
| 55 | for my $command_name (@command_names) { | ||
| 56 | #XXX-ALTERNATIVE: show a tree of command names | ||
| 57 | # $tree->{text} .= ' 'x$indent . $command_name . "\n"; | ||
| 58 | |||
| 59 | my $command_obj; | ||
| 60 | { no strict 'refs'; | ||
| 61 | $command_obj = $root->$registered_command_obj_accessor( $command_name ); | ||
| 62 | } | ||
| 63 | |||
| 64 | #XXX-ALTERNATIVE: show a tree of Perl package names defining the commands (including | ||
| 65 | # source files they were defined in): | ||
| 66 | my $source = Class::Inspector->loaded_filename( ref $command_obj ); | ||
| 67 | $source ||= 'defined inline'; | ||
| 68 | my $x = ref ($command_obj) . " ($source)"; | ||
| 69 | $tree->{text} .= ' 'x$indent . $x . "\n"; | ||
| 70 | |||
| 71 | # Recursive call (NOTE: passing output object reference which will act | ||
| 72 | # as an accumulator)... | ||
| 73 | command_tree( $app, $command_obj, $indent, $tree ); | ||
| 74 | } | ||
| 75 | return $tree->{text} . "\n"; | ||
| 76 | } | ||
| 77 | |||
| 78 | #------- | ||
| 79 | 1; | ||
| 80 | |||
| 81 | __END__ |