Karl Erisman > CLI-Framework-0.05 > CLI::Framework::Command

Download:
CLI-Framework-0.05.tar.gz

Dependencies

Annotate this POD

CPAN RT

New  1
Open  1
View/Report Bugs
Module Version: 0.04   Source  

NAME ^

CLI::Framework::Command - CLIF Command superclass

SYNOPSIS ^

    # The code below shows a few of the methods your command classes are likely
    # to override...

    package My::Journal::Command::Search;
    use base qw( CLI::Framework::Command );

    sub usage_text { q{
        search [--titles-only] <search regex>: search a journal
    } }

    sub option_spec { (
        [ 'titles-only' => 'search only journal titles' ],
    ) }

    sub validate {
        my $self, $opts, @args) = @_;
        die "exactly one argument required (search regex)" unless @args == 1;
    }

    sub run {
        my ($self, $opts, @args) = @_;

        my $db = $self->cache->get( 'db' )

        # perform search against $db...
        # $search_results = ...

        return $search_results;
    }

DESCRIPTION ^

CLI::Framework::Command (command class for use with CLI::Framework::Application) is the base class for CLIF commands. All CLIF commands inherit from this class.

CONCEPTS ^

Subcommands

Commands can have "subcommands," which are also objects of CLI::Framework::Command. Subcommands can, in turn, have their own subcommands, and this pattern may repeat indefinitely.

Note that in this documentation, the term "command" may be used to refer to both commands and subcommands.

Registration of subcommands

Subcommands are "registered" with their parent commands. The parent commands can then forward subcommand responsibilities as appropriate.

File-based commands vs. inline commands

Command classes (which inherit from CLI::Framework::Command) can be defined in their own package files or they may be declared inline in another package (e.g. a command package file could include the declaration of a subcommand package or command packages could be declared inline in the package file where the application is declared). As long as the classes have been loaded (making their way into the symbol table), CLIF can use the commands.

OBJECT CONSTRUCTION ^

manufacture( $command_package )

    # (manufacture MyApp::Command::Go and any subcommand trees beneath it)
    my $go = CLI::Framework::Command->manufacture( 'MyApp::Command::Go' );

CLI::Framework::Command is an abstract factory; manufacture() is the factory method that constructs and returns an object of the specific command class that is requested.

After instantiating an object of the requested command package, manufacture() attempts to load subcommands in the following 2 steps:

  1. Attempt to find package files representing subcommands. For every subcommand S, S is registered as a child of the parent command. Next, steps 1 and 2 repeat, this time being invoked on S (i.e. with S as the parent in an attempt to find subcommands of S).
  2. Attempt to find and register pre-compiled subcommands defined inline. Only pre-compiled subcommands are considered for registration (i.e. package files are not considered in this step). For every subcommand S, any pre-compiled subcommands that inherit directly from S are found and step 2 repeats for those classes.

Note the following rules about command class definition:

new()

    $object = $cli_framework_command_subclass->new();

Basic constructor.

SHARED CACHE DATA ^

CLIF commands may need to share data with other commands and with their associated application. These methods support those needs.

set_cache( $cache_object )

Set the internal cache object for this instance.

See cache.

cache()

Retrieve the internal cache object for this instance.

See cache for an explanation of how to use this simple cache object.

COMMAND DISPATCHING ^

get_default_usage() / set_default_usage( $default_usage_text )

Get or set the default usage message for the command. This message is used by usage.

Note: get_default_usage() merely retrieves the usage data that has already been set. CLIF only sets the default usage message for a command when processing a run request for the command. Therefore, the default usage message for a command may be empty (if a run request for the command has not been given and you have not otherwise set the default usage message).

    $cmd->set_default_usage( ... );
    $usage_msg = $cmd->get_default_usage();

usage( $subcommand_name, @subcommand_chain )

    # Command usage...
    print $cmd->usage();

    # Subcommand usage (to any level of depth)...
    $subcommand_name = 'list';
    @subcommand_chain = qw( completed );
    print $cmd->usage( $subcommand_name, @subcommand_chain );

Attempts to find and return a usage message for a command or subcommand.

If a subcommand is given, returns a usage message for that subcommand. If no subcommand is given or if the subcommand cannot produce a usage message, returns a general usage message for the command.

Logically, here is how the usage message is produced:

dispatch( $cmd_opts, @args )

For the given command request, dispatch performs any applicable validation and initialization with respect to supplied options $cmd_opts and arguments @args, then runs the command.

@args may indicate the request for a subcommand:

    { <subcmd> [subcmd-opts] {...} } [subcmd-args]

...as in the following command (where "usage" is the <subcmd>):

    $ gen-report --html stats --role=admin usage --time='2d' '/tmp/stats.html'

If a subcommand registered under the indicated command is requested, the subcommand is initialized and dispatched with its options [subcmd-opts] and arguments. Otherwise, the command itself is run.

This means that a request for a subcommand will result in the run method of only the deepest-nested subcommand (because dispatch will keep forwarding to successive subcommands until the args no longer indicate that a subcommand is requested). Furthermore, the only command that can receive args is the final subcommand in the chain (but all commands in the chain can receive options). However, Note that each command in the chain can affect the execution process through its notify_of_subcommand_dispatch method.

COMMAND REGISTRATION ^

registered_subcommand_names()

    @registered_subcommands = $cmd->registered_subcommand_names();

Return a list of the currently-registered subcommands.

registered_subcommand_object( $subcommand_name )

    $subcmd_obj = $cmd->get_registered_subcommand( 'lock' );

Given the name of a registered subcommand, return a reference to the subcommand object. If the subcommand is not registered, returns undef.

register_subcommand( $subcmd_obj )

    $cmd->register_subcommand( $subcmd_obj );

Register $subcmd_obj as a subcommand under master command $cmd.

If $subcmd_obj is not a CLI::Framework::Command, returns undef. Otherwise, returns $subcmd_obj.

package_is_registered( $package_name )

Return a true value if the named class is registered as a subcommand. Returns a false value otherwise.

name()

    $s = My::Command::Squeak->new();
    $s->name();    # => 'squeak'

name() takes no arguments and returns the name of the command. This method uses the normalized base name of the package as the command name, e.g. the command defined by the package My::Application::Command::Xyz would be named 'xyz'.

COMMAND SUBCLASS HOOKS ^

Just as CLIF Applications have hooks that subclasses can use, CLIF Commands are able to influence the command dispatch process via several hooks. Except where noted, all hooks are optional -- subclasses may choose whether or not to override them.

option_spec()

This method should return an option specification as expected by Getopt::Long::Descriptive (see Getopt::Long::Descriptive). The option specification is a list of arrayrefs that defines recognized options, types, multiplicities, etc. and specifies textual strings that are used as descriptions of each option:

    sub option_spec {
        [ "verbose|v"   => "be verbose"         ],
        [ "logfile=s"   => "path to log file"   ],
    }

Subclasses should override this method if commands accept options (otherwise, the command will not recognize any options).

subcommand_alias()

    sub subcommand_alias {
        rm  => 'remove',
        new => 'create',
        j   => 'jump',
        r   => 'run',
    }

Subcommands can have aliases to support shorthand versions of subcommand names.

Subclasses should override this method if subcommand aliases are desired. Otherwise, the subcommands will only be recognized by their full command names.

validate( $cmd_opts, @args )

To provide strict validation of a command request, a subclass may override this method. Otherwise, validation is skipped.

$cmd_opts is an options hash with the received command options as keys and their values as hash values.

@args is a list of the received command arguments.

validate() is called in void context. It is expected to throw an exception if validation fails. This allows your validation routine to provide a context-specific failure message.

Note that Getop::Long::Descriptive performs some validation of its own based on the option_spec. However, validate() allows more flexibility in validating command options and also allows validation of arguments.

notify_of_subcommand_dispatch( $subcommand, $cmd_opts, @args )

If a request for a subcommand is received, the master command itself does not run(). Instead, its notify_of_subcommand_dispatch() method is called. This gives the master command a chance to act before the subcommand is run.

For example, suppose some (admittedly contrived) application, 'queue', has a command hierarchy with multiple commands:

    enqueue
    dequeue
    print
    property
        constraint
            maxlen
        behavior
    ...

In this case, $ queue property constraint maxlen might set the max length property for a queue. If the command hierarchy was built this way, maxlen would be the only command to run in response to that request. If constraint, the master command of maxlen, needs to hook into this execution path, notify_of_subcommand_dispatch() could be overridden in the command class that implements constraint. notify_of_subcommand_dispatch() would then be called just before dispatching maxlen.

The notify_of_subcommand_dispatch() method is called in void context.

$subcommand is the subcommand object.

$cmd_opts is the options hash for the subcommand.

@args is the argument list for the subcommand.

usage_text()

    sub usage_text {
        q{
        dequeue: remove item from queue
        }
    }

If implemented, this method should simply return a string containing usage information for the command. It is used automatically to provide context-specific help.

Implementing this method is optional. See usage for details on how usage information is generated within the context of a CLIF application.

Users are encouraged to override this method.

run( $cmd_opts, @args )

This method is responsible for the main execution of a command. It is called with the following parameters:

$cmd_opts is a pre-validated options hash with command options as keys and their user-provided values as hash values.

@args is a list of the command arguments.

The default implementation of this method simply calls usage to show help information for the command. Therefore, subclasses will usually override run() (Occasionally, it is useful to have a command that does little or nothing on its own but has subcommands that define the real behavior. In such occasional cases, it may not be necessary to override run()).

If an error occurs during the execution of a command via its run() method, the run() method code should throw an exception. The exception will be caught and handled appropriately by CLIF.

The return value of run() is treated as data to be processed by the render method in your CLIF Application class. Note that nothing should be printed directly in your implementation of run. If no output is to be produced, your run() method should return undef or empty string.

DIAGNOSTICS ^

Error: failed to instantiate command package '<command pkg>' via new()

manufacture was asked to manufacture an object of class <command pkg>, but failed while trying to invoke its constructor.

Error: failed to instantiate subcommand '<class>' via method new()

Object construction for the subcommand <class> (whose package has already been require()d) was unsuccessful.

cannot opendir <dir>

While trying to manufacture subcommands in a directory tree, calling opendir() on the subdirectory with the name of the parent command failed.

CONFIGURATION & ENVIRONMENT ^

No special configuration requirements.

DEPENDENCIES ^

Carp

Getopt::Long::Descriptive

Exception::Class::TryCatch

Class::Inspector

CLI::Framework::Exceptions

SEE ALSO ^

CLI::Framework

CLI::Framework::Application

CLI::Framework::Tutorial

LICENSE AND COPYRIGHT ^

Copyright (c) 2009 Karl Erisman (kerisman@cpan.org). All rights reserved.

This is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.

AUTHOR ^

Karl Erisman (kerisman@cpan.org)

syntax highlighting: