CLI-Framework
view release on metacpan or search on metacpan
lib/CLI/Framework/Application.pm view on Meta::CPAN
package CLI::Framework::Application;
use strict;
use warnings;
our $VERSION = '0.04';
use Getopt::Long::Descriptive;
use Exception::Class::TryCatch;
use CLI::Framework::Exceptions qw( :all );
use CLI::Framework::Command;
# Certain built-in commands are required:
use constant REQUIRED_BUILTINS_PKGS => qw(
CLI::Framework::Command::Help
);
use constant REQUIRED_BUILTINS_NAMES => qw(
help
);
# Certain built-in commands are required only in interactive mode:
use constant REQUIRED_BUILTINS_PKGS_INTERACTIVE => qw(
CLI::Framework::Command::Menu
);
use constant REQUIRED_BUILTINS_NAMES_INTERACTIVE => qw(
menu
);
#FIXME-TODO-CLASS_GENERATION:
#sub import {
# my ($class, $app_pkg, $app_def) = @_;
#
# # If caller has supplied import args, CLIF's "inline form" is being used.
# # The application class must be generated dynamically...
#
#}
#-------
sub new {
my ($class, %args) = @_;
my $interactive = $args{ interactive }; # boolean: interactive mode?
my $cache = CLI::Framework::Cache->new();
my $app = {
_registered_command_objects => undef, # (k,v)=(cmd pkg name,cmd obj) for all registered commands
_default_command => 'help', # name of default command
_current_command => undef, # name of current (or last) command to run
_interactive => $interactive, # boolean: interactive state
_cache => $cache, # storage for data shared between app and cmd
_initialized => 0, # initialization status
};
bless $app, $class;
# Validate some hook methods so we can assume that they behave properly...
$app->_validate_hooks();
return $app;
}
sub _validate_hooks {
my ($app) = @_;
# Ensure that hook methods return expected data structure types according
# to their preconditions...
my $class = ref $app;
# Ensure that command_map() succeeds...
eval { $app->command_map() };
if( catch my $e ) {
throw_app_hook_exception( error =>
"method 'command_map' in class '$class' fails" );
}
# Ensure that command_map() returns a "hash-worthy" list...
else {
eval { $app->_list_to_hashref( 'command_map' ) };
if( catch my $e ) {
$e->isa( 'CLI::Framework::Exception' ) && do{ $e->rethrow() };
throw_app_hook_exception( error => $e );
}
lib/CLI/Framework/Application.pm view on Meta::CPAN
my @valid_aliases = ( $app->_valid_command_names() );
push @valid_aliases, REQUIRED_BUILTINS_NAMES;
push @valid_aliases, REQUIRED_BUILTINS_NAMES_INTERACTIVE
if $app->get_interactivity_mode();
return grep { $cmd_name eq $_ } @valid_aliases;
}
sub registered_command_names {
my ($app) = @_;
my @names;
# For each registered command package (name)...
for my $cmd_pkg_name (keys %{ $app->{_registered_command_objects} }) {
# Find command names that this command package was registered under...
push @names, grep { $_ } map {
$_ if $app->command_map_hashref->{$_} eq $cmd_pkg_name
} $app->_valid_command_names
}
return @names;
}
sub registered_command_object {
my ($app, $cmd_name) = @_;
return unless $cmd_name;
my $cmd_pkg = $app->command_map_hashref->{$cmd_name};
return unless $cmd_pkg
&& exists $app->{_registered_command_objects}
&& exists $app->{_registered_command_objects}->{$cmd_pkg};
return $app->{_registered_command_objects}->{$cmd_pkg};
}
sub register_command {
my ($app, $cmd) = @_;
return unless $cmd;
if( ref $cmd && $app->is_valid_command_pkg(ref $cmd) ) {
# Register by reference...
return unless $cmd->isa( 'CLI::Framework::Command' );
$app->{_registered_command_objects}->{ref $cmd} = $cmd;
}
elsif( $app->is_valid_command_pkg($app->command_map_hashref->{$cmd}) ) {
# Register by command name...
my $pkg = $app->command_map_hashref->{$cmd};
$cmd = CLI::Framework::Command->manufacture( $pkg );
$app->{_registered_command_objects}->{ref $cmd} = $cmd;
}
#FIXME:use REQUIRED_BUILTINS_PKGS_INTERACTIVE & REQUIRED_BUILTINS_NAMES_INTERACTIVE
elsif( $cmd eq 'help' ) {
# Required built-in is always valid...
$cmd = CLI::Framework::Command->manufacture( 'CLI::Framework::Command::Help' );
$app->{_registered_command_objects}->{'CLI::Framework::Command::Help'} = $cmd;
}
elsif( $app->get_interactivity_mode() && $cmd eq 'menu' ) {
# Required built-in for interactive usage is always valid...
$cmd = CLI::Framework::Command->manufacture( 'CLI::Framework::Command::Menu' );
$app->{_registered_command_objects}->{'CLI::Framework::Command::Menu'} = $cmd;
}
else {
throw_cmd_registration_exception(
error => "Error: failed attempt to register invalid command '$cmd'" );
}
# Metacommands should be app-aware...
$cmd->set_app( $app ) if $cmd->isa( 'CLI::Framework::Command::Meta' );
return $cmd;
}
sub get_default_command { $_[0]->{_default_command} }
sub set_default_command { $_[0]->{_default_command} = $_[1] }
sub get_current_command { $_[0]->{_current_command} }
sub set_current_command { $_[0]->{_current_command} = $_[1] }
sub get_default_usage { $_[0]->{_default_usage} }
sub set_default_usage { $_[0]->{_default_usage} = $_[1] }
###############################
#
# PARSING & RUNNING COMMANDS
#
###############################
sub usage {
my ($app, $command_name, @args) = @_;
# Allow aliases in place of command name...
$app->_canonicalize_cmd( $command_name );
my $usage_text;
if( $command_name && $app->is_valid_command_name($command_name) ) {
# Get usage from Command object...
my $cmd = $app->registered_command_object( $command_name )
|| $app->register_command( $command_name );
$usage_text = $cmd->usage(@args);
}
else {
# Get usage from Application object...
$usage_text = $app->usage_text();
}
# Finally, fall back to default application usage message...
$usage_text ||= $app->get_default_usage();
return $usage_text;
}
sub _canonicalize_cmd {
my ($self, $input) = @_;
# Translate shorthand aliases for commands to full names...
return unless $input;
my $command_name;
my %aliases = $self->command_alias();
return unless %aliases;
$command_name = $aliases{$input} || $input;
lib/CLI/Framework/Application.pm view on Meta::CPAN
#
###############################
sub get_interactivity_mode { $_[0]->{_interactive} }
sub set_interactivity_mode { $_[0]->{_interactive} = $_[1] }
sub is_interactive_command {
my ($app, $command_name) = @_;
my @noninteractive_commands = $app->noninteractive_commands();
# Command must be valid...
return 0 unless $app->is_valid_command_name( $command_name );
# Command must NOT be non-interactive...
return 1 unless grep { $command_name eq $_ } @noninteractive_commands;
return 0;
}
sub get_interactive_commands {
my ($app) = @_;
my @valid_commands = $app->_valid_command_names;
# All valid commands are enabled in non-interactive mode...
return @valid_commands unless( $app->get_interactivity_mode() );
# ...otherwise, in interactive mode, include only interactive commands...
my @command_names;
for my $c ( @valid_commands ) {
push @command_names, $c if $app->is_interactive_command( $c );
}
return @command_names;
}
sub run_interactive {
my ($app, %param) = @_;
# Auto-instantiate if necessary...
unless( ref $app ) {
my $class = $app;
$app = $class->new();
}
$app->set_interactivity_mode(1);
# If default command is non-interactive, reset it, remembering default...
my $orig_default_command = $app->get_default_command();
if( grep { $orig_default_command eq $_ } $app->noninteractive_commands() ) {
$app->set_default_command( 'help' );
}
# If initialization indicated, run init() and handle existing input...
eval { $app->_parse_request( initialize => $param{initialize} )
if $param{initialize}
};
if( catch my $e ) { $app->handle_exception($e); return }
# Find how many prompts to display in sequence between displaying menu...
my $menu_cmd = $app->registered_command_object('menu')
|| $app->register_command( 'menu' );
$menu_cmd->isa( 'CLI::Framework::Command::Menu' )
or throw_type_exception(
error => "Menu command must be a subtype of " .
"CLI::Framework::Command::Menu" );
my $invalid_request_threshold = $param{invalid_request_threshold}
|| $menu_cmd->line_count(); # num empty prompts b4 re-displaying menu
$app->_run_cmd_processing_loop(
menu_cmd => $menu_cmd,
invalid_request_threshold => $invalid_request_threshold
);
# Restore original default command...
$app->set_default_command( $orig_default_command );
}
sub _run_cmd_processing_loop {
my ($app, %param) = @_;
my $menu_cmd = $param{menu_cmd};
my $invalid_request_threshold = $param{invalid_request_threshold};
$app->render( $menu_cmd->run() );
my ($cmd_succeeded, $invalid_request_count, $done) = (0,0,0);
until( $done ) {
if( $invalid_request_count >= $invalid_request_threshold ) {
# Reached threshold for invalid cmd requests => re-display menu...
$invalid_request_count = 0;
$app->render( $menu_cmd->run() );
}
elsif( $cmd_succeeded ) {
# Last command request was successful => re-display menu...
$app->render( $menu_cmd->run() );
$cmd_succeeded = $invalid_request_count = 0;
}
# Read a command request...
$app->read_cmd();
if( @ARGV ) {
# Recognize quit requests...
if( $app->is_quit_signal($ARGV[0]) ) {
undef @ARGV;
last;
}
$app->_canonicalize_cmd($ARGV[0]); # translate cmd aliases
if( $app->is_interactive_command($ARGV[0]) ) {
if( $app->run() ) {
$cmd_succeeded = 1;
}
else { $invalid_request_count++ }
}
else {
$app->render( 'unrecognized command request: ' . join(' ',@ARGV) . "\n");
$invalid_request_count++;
}
}
else { $invalid_request_count++ }
}
}
sub read_cmd {
my ($app) = @_;
lib/CLI/Framework/Application.pm view on Meta::CPAN
# # Arrange for command-line completion...
# my $attribs = $term->Attribs;
# $attribs->{completion_function} = $app->_cmd_request_completions();
}
# Prompt for the name of a command and read input from STDIN.
# Store the individual tokens that are read in @ARGV.
my $command_request = $term->readline('> ');
if(! defined $command_request ) {
# Interpret CTRL-D (EOF) as a quit signal...
@ARGV = $app->quit_signals();
print "\n"; # since EOF character is rendered as ''
}
else {
# Prepare command for usual parsing...
@ARGV = Text::ParseWords::shellwords( $command_request );
$term->addhistory($command_request)
if $command_request =~ /\S/ and !$term->Features->{autohistory};
}
return 1;
}
##FIXME-TODO-CMDLINE_COMPLETION:this should only return interactive commands; it should pay attention
##to its text/line/start args, ...; also: make it work with subcommands
## --see Term::Readline::Gnu
#sub _cmd_request_completions {
# my ($app) = @_;
# return sub {
# my ($text, $line, $start) = @_;
# return $app->_valid_command_names;
# }
#}
sub is_quit_signal {
my ($app, $command_name) = @_;
my @quit_signals = $app->quit_signals();
return grep { $command_name eq $_ } @quit_signals;
}
###############################
#
# APPLICATION SUBCLASS HOOKS
#
###############################
#XXX-CONSIDER: consider making default implementation of init():
# $app->set_current_command('help') if $opts->{help}
sub init { 1 }
sub pre_dispatch { }
sub usage_text { }
sub option_spec { }
sub validate_options { 1 }
sub command_map {
help => 'CLI::Framework::Command::Help',
console => 'CLI::Framework::Command::Console',
menu => 'CLI::Framework::Command::Menu',
list => 'CLI::Framework::Command::List',
'dump' => 'CLI::Framework::Command::Dump',
tree => 'CLI::Framework::Command::Tree',
alias => 'CLI::Framework::Command::Alias',
}
sub command_alias { }
sub noninteractive_commands { qw( console menu ) }
sub quit_signals { qw( q quit exit ) }
sub handle_exception {
my ($app, $e) = @_;
$app->render( $e->description . "\n\n" . $e->error );
return;
}
sub render {
my ($app, $output) = @_;
#XXX-CONSIDER: consider built-in features to help simplify associating templates
#with commands (each command would probably have its own template for its
#output)
print $output;
}
###############################
#
# CACHING
#
###############################
package CLI::Framework::Cache;
use strict;
use warnings;
sub new {
my ($class) = @_;
bless { _cache => { } }, $class;
}
sub get {
my ($self, $k) = @_;
my $v = $self->{_cache}->{$k};
return $v;
}
sub set {
my ($self, $k, $v) = @_;
$self->{_cache}->{$k} = $v;
return $v;
}
#-------
1;
__END__
=pod
=head1 NAME
CLI::Framework::Application - CLIF Application superclass
=head1 SYNOPSIS
# The code below shows a few of the methods your application class is likely
# to override...
package My::Journal;
use base qw( CLI::Framework );
sub usage_text { q{
$0 [--verbose|v]
OPTIONS
--db [path] : path to SQLite database file
-v --verbose : be verbose
-h --help : show help
COMMANDS
help - show application or command-specific help
menu - print command menu
entry - work with journal entries
publish - publish a journal
console - start a command console for the application
} }
sub option_spec {
[ 'help|h' => 'show help' ],
[ 'verbose|v' => 'be verbose' ],
[ 'db=s' => 'path to SQLite database file' ],
}
sub command_map {
help => 'CLI::Framework::Command::Help',
menu => 'My::Journal::Command::Menu',
entry => 'My::Journal::Command::Entry',
publish => 'My::Journal::Command::Publish',
console => 'CLI::Framework::Command::Console',
}
sub command_alias {
h => 'help',
m => 'menu',
e => 'entry',
p => 'publish',
sh => 'console',
c => 'console',
}
sub init {
my ($self, $opts) = @_;
my $db = DBI->connect( ... );
$self->cache->set( db => $db );
return 1;
}
1;
=head1 OBJECT CONSTRUCTION
=head2 new( [interactive => 1] )
$app = My::Application->new( interactive => 1 );
C<interactive>: Optional parameter. Set this to a true value if the application
is to be run interactively (or call C<set_interactivity_mode> later)
Constructs and returns a new CLIF Application object. As part of this
process, some validation is performed on L<SUBCLASS HOOKS|/SUBCLASS HOOKS>
defined in the application class. If validation fails, an exception is thrown.
=head1 COMMAND INTROSPECTION & REGISTRATION
The methods in this section are responsible for providing access to the
commands in an application.
=head2 command_map_hashref()
$h = $app->command_map_hashref();
Returns a HASH ref built from the command_map for an Application (by direct
conversion from the command map array).
If the list returned by the definition of L<command_map|/command_map()> in the
application is not hash-worthy, an exception is thrown.
=head2 is_valid_command_pkg( $package_name )
$app->is_valid_command_pkg( 'My::Command::Swim' );
Returns a true value if the specified command class (package name) is valid
within the application. Returns a false value otherwise.
A command class is "valid" if it is included in L<command_map|/command_map()> or
if it is a built-in command that was included automatically in the
application.
lib/CLI/Framework/Application.pm view on Meta::CPAN
# Explicitly specify whether or not initialization should be done:
$app->run( initialize => 0 );
This method controls the request processing and dispatching of a single
command. It takes its input from @ARGV (which may be populated by a
script running non-interactively on the command line) and dispatches the
indicated command, capturing its return value. The command's return value
represents the output produced by the command. This value is passed to
L<render|/render( $output )> for final display.
If errors occur, they result in exceptions that are handled by
L<handle_exception|/handle_exception( $e )>.
The following parameters are accepted:
C<initialize>: This controls whether or not application initialization (via
L<init|/init( $options_hash )>) should be performed. If not specified,
initialization is performed upon the first call to C<run>. Should there be
subsequent calls, initialization is not repeated. Passing C<initialize>
explicitly can modify this behavior.
=head1 INTERACTIVITY
=head2 get_interactivity_mode() / set_interactivity_mode( $is_interactive )
C<get_interactivity_mode> returns a true value if the application is in an
interactive state and a false value otherwise.
print "running interactively" if $app->get_interactivity_mode();
C<set_interactivity_mode> sets the interactivity state of the application. One
parameter is recognized: a true or false value to indicate whether the
application state should be interactive or non-interactive, respectively.
$app->set_interactivity_mode(1);
=head2 is_interactive_command( $command_name )
$help_command_is_interactive = $app->is_interactive_command( 'help' );
Returns a true value if there is a valid command with the specified name that
is an interactive command (i.e. a command that is enabled for this application
in interactive mode). Returns a false value otherwise.
=head2 get_interactive_commands()
my @interactive_commands = $app->get_interactive_commands();
Return a list of all commands that are to be available in interactive mode
("interactive commands").
=head2 run_interactive( [%param] )
MyApp->run_interactive();
# ...or as an object method:
$app->run_interactive();
Start an event processing loop to prompt for and run commands in sequence. The
C<menu> command is used to display available command selections (the built-in
C<menu> command, L<CLI::Framework::Command::Menu>, will be used unless the
application defines its own C<menu> command).
Within this loop, valid input is the same as in non-interactive mode except
that application options are not accepted (any application options should be
handled upon application initialization and before the interactive B<command>
loop is entered -- see the description of the C<initialize> parameter below).
The following parameters are recognized:
C<initialize>: causes any application options that are present in C<@ARGV> to be
procesed/validated and causes L<init|/init( $options_hash )> to be invoked
prior to entering the interactive event loop to recognize commands. If
C<run_interactive()> is called after application options have already been
handled, this parameter can be omitted.
C<invalid_request_threshold>: the number of unrecognized command requests the
user can enter before the menu is re-displayed.
=head2 read_cmd()
$app->read_cmd();
This method is responsible for retrieving a command request and placing the
user input into C<@ARGV>. It is called in void context.
The default implementation uses L<Term::ReadLine> to prompt the user and read a
command request, supporting command history.
Subclasses are free to override this method if a different means of
accepting user input is desired. This makes it possible to read command
selections without assuming that the console is being used for I/O.
=head2 is_quit_signal()
until( $app->is_quit_signal(read_string_from_user()) ) { ... }
Given a string, return a true value if it is a quit signal (indicating that
the application should exit) and a false value otherwise.
L<quit_signals|/quit_signals()> is an application subclass hook that
defines what strings signify that the interactive session should exit.
=head1 SUBCLASS HOOKS
There are several hooks that allow CLIF applications to influence the command
execution process. This makes customizing the critical aspects of an
application as easy as overriding methods.
Except where noted, all hooks are optional -- subclasses may choose not to
override them (in fact, runnable CLIF applications can be created with very
minimal subclasses).
=head2 init( $options_hash )
This hook is called in void context with one parameter:
C<$options_hash> is a hash of pre-validated application options received and
parsed from the command line. The options hash has already been checked
against the options defined to be accepted by the application in
L<option_spec|/option_spec()>.
lib/CLI/Framework/Application.pm view on Meta::CPAN
a configuration file.
=head2 pre_dispatch( $command_object )
This hook is called in void context. It allows applications to perform actions
after each command object has been prepared for dispatch but before the command
dispatch actually takes place. Its purpose is to allow applications to do
whatever may be necessary to prepare for running the command. For example, a
log entry could be inserted in a database to store a record of every command
that is run.
=head2 option_spec()
An example definition of this hook is as follows:
sub option_spec {
[ 'verbose|v' => 'be verbose' ],
[ 'logfile=s' => 'path to log file' ],
}
This method should return an option specification as expected by
L<Getopt::Long::Descriptive|Getopt::Long::Descriptive/opt_spec>. The option
specification defines what options are allowed and recognized by the
application.
=head2 validate_options( $options_hash )
This hook is called in void context. It is provided so that applications can
perform validation of received options.
C<$options_hash> is an options hash parsed from the command-line.
This method should throw an exception if the options are invalid (throwing the
exception using C<die()> is sufficient).
B<Note> that L<Getopt::Long::Descriptive>, which is used internally for part of
the options processing, will perform some validation of its own based on the
L<option_spec|/option_spec()>. However, the C<validate_options> hook allows for
additional flexibility in validating application options.
=head2 command_map()
Return a mapping between command names and Command classes (classes that inherit
from L<CLI::Framework::Command>). The mapping is a list of key-value pairs.
The list should be "hash-worthy", meaning that it can be directly converted to
a hash.
Note that the order of the commands in this list determines the order that the
commands are displayed in the built-in interactive menu.
The keys are names that should be used to install the commands in the
application. The values are the names of the packages that implement the
corresponding commands, as in this example:
sub command_map {
# custom commands:
fly => 'My::Command::Fly',
run => 'My::Command::Run',
# overridden built-in commands:
menu => 'My::Command::Menu',
# built-in commands:
help => 'CLI::Framework::Command::Help',
list => 'CLI::Framework::Command::List',
tree => 'CLI::Framework::Command::Tree',
'dump' => 'CLI::Framework::Command::Dump',
console => 'CLI::Framework::Command::Console',
alias => 'CLI::Framework::Command::Alias',
}
=head2 command_alias()
This hook allows aliases for commands to be specified. The aliases will be
recognized in place of the actual command names. This is useful for setting
up shortcuts to longer command names.
C<command_alias> should return a "hash-worthy" list where the keys are aliases
and the values are command names.
An example of its definition:
sub command_alias {
h => 'help',
l => 'list',
ls => 'list',
sh => 'console',
c => 'console',
}
=head2 noninteractive_commands()
sub noninteractive_commands { qw( console menu ) }
Certain commands do not make sense to run interactively (e.g. the "console"
command, which itself puts the application into interactive mode). This method
should return a list of their names. These commands will be disabled during
interactive mode. By default, all commands are interactive commands except for
C<console> and C<menu>.
=head2 quit_signals()
sub quit_signals { qw( q quit exit ) }
An application can specify exactly what input represents a request to end an
interactive session. By default, the example definition above is used.
=head2 handle_exception( $e )
sub handle_exception {
my ($app, $e) = @_;
# Handle the exception represented by object $e...
$app->my_error_logger( error => $e->error, pid => $e->pid, gid => $e->gid, ... );
warn "caught error ", $e->error, ", continuing...";
return;
}
Error conditions are caught by CLIF and forwarded to this exception handler.
It receives an exception object (see L<Exception::Class::Base> for methods
( run in 1.237 second using v1.01-cache-2.11-cpan-39bf76dae61 )