CLI::F...ication(3pm)
CLI::Framework::Application ๐
okay bestie, welcome to the CLIF Application superclass โ this is the base class your whole CLI app is gonna inherit from. This page lives in the User Contributed Perl Documentation corner of CLI::F...ication(3pm) (yes the man name is abbreviated, don't @ me), and it's a long one, so buckle up โ we're doing this in parts. ๐
โจ NAME โจ
CLI::Framework::Application โ the CLIF Application superclass. That's it, that's the vibe. ๐
๐ธ SYNOPSIS ๐ธ
The code below shows a few of the methods your application class is likely to override... (lowkey this is the whole personality of your app in one file)
# 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;
๐ฆ OBJECT CONSTRUCTION ๐ฆ
new( [interactive => 1] )
$app = My::Application->new( interactive => 1 );
interactiveโ Optional parameter, bestie. Set this to a true value if the application is gonna be run interactively (orrrr you can just callset_interactivity_modelater, no pressure ๐ ).
Constructs and returns a brand-new CLIF Application object. โจ And listen โ as part of this whole process, some validation gets performed on the SUBCLASS HOOKS defined in your application class. If validation fails, an exception is thrown. So like, fix your hooks. ๐ญ
๐ COMMAND INTROSPECTION & REGISTRATION ๐
The methods in this section are responsible for providing access to the commands in an application. iykyk โ this is the group chat where your app keeps track of all its commands. ๐ซถ
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).
And if the list returned by the definition of command_map in the application is not hash-worthy? An exception is thrown. ๐
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's included in command_map, or if it's a built-in command that was included automatically in the application. That's the whole vibe check. โญ
is_valid_command_name( $command_name )
$app->is_valid_command_name( 'swim' );
Returns a true value if the specified command name is valid within the application. Returns a false value otherwise.
Same deal as above: a command name is "valid" if it's included in command_map, or if it's a built-in command that was included automatically in the application. ๐
registered_command_names()
@registered_commands = $app->registered_command_names();
Returns a list of the names of all registered commands. These are the names that each command was given in command_map (plus any auto-registered built-ins). The full roster, no gatekeeping. ๐
registered_command_object( $command_name )
$command_object = $app->registered_command_object( 'fly' );
Given the name of a registered command, returns the CLI::Framework::Command object that is registered in the application under that name. If the command isn't registered, it returns undef. ๐
register_command( $cmd )
# Register by name...
$command_object = $app->register_command( $command_name );
# ...or register by object reference...
$command_object = CLI::Framework::Command->new( ... );
$app->register_command( $command_object );
Register a command to be recognized by the application. This method accepts either the name of a command or a reference to a CLI::Framework::Command object. So flexible, we love her. ๐
- If
$cmdis aCLI::Framework::Commandobject and it's one of the command types specified incommand_mapto be valid, the command object is registered and returned. - If
$cmdis the name of a valid command specified incommand_map, an object of the corresponding command class is registered and returned. - If
$cmdis not recognized, an exception is thrown. periodt.
get_default_command() / set_default_command( $default_cmd )
get_defualt_command() retrieves the name of the command that is currently set as the default command for the application. (yes, that spelling is exactly how it's written in the source, i'm not touching it, it's iconic now ๐ซถ)
my $default_command = $app->get_default_command();
Given a command name, set_default_command makes it the default command for the application.
$app->set_default_command( 'jump' );
get_current_command() / set_current_command( $current )
get_current_command returns the name of the current command (or the one that was most recently run).
$status = $app->run();
print 'The command named: ', $app->get_current_command(), ' was just run';
Given a command name, set_current_command forwards execution to that command. This might be useful (for instance) to "redirect" to another command. main character energy, honestly. โจ
$app->set_current_command( 'fly' );
get_default_usage() / set_default_usage( $default_usage )
The "default usage" message is used as a last resort when usage information is unavailable by other means. See usage below. ๐
get_default_usage gets the default usage message for the application.
$usage_msg = $app->get_default_usage();
set_default_usage sets the default usage message for the application.
$app->set_default_usage( $usage_message );
๐ PARSING & RUNNING COMMANDS ๐
usage( $command_name, @subcommand_chain )
# Application usage...
print $app->usage();
# Command-specific usage...
$command_name = 'task';
@subcommand_chain = qw( list completed );
print $app->usage( $command_name, @subcommand_chain );
Returns a usage message for the application or a specific (sub)command. ๐
If a command name is given (optionally with subcommands), it returns a usage message string for that (sub)command. If no command name is given, or if no usage message is defined for the specified (sub)command, it returns a general usage message for the application.
Here's how the usage message is produced, step by step, bestie:
- If a valid command name (or alias) is given, attempt to get a usage message from the command (this step takes into account
@subcommand_chainso that a subcommand usage message will be shown if applicable); if no usage message is defined for the command, use the application usage message instead. - If the application object has defined
usage_text, use its return value as the usage message. - Finally, fall back to using the default usage message returned by
get_default_usage.
Note: It is advisable to defineusage_textbecause the default usage message, produced viaGetopt::Long::Descriptive, is terse and is not context-specific to the command request. so like... define your usage text, bestie, it's giving "bare minimum" otherwise. ๐ญ
cache()
CLIF Applications may have the need to share data between individual CLIF Commands and the Application object itself. cache() provides a way for this data to be stored, retrieved, and shared between components. a lil shared google doc for your app, fr fr. ๐
$cache_object = $app->cache();
cache() returns a cache object. The following methods demonstrate usage of the resulting object:
$cache_object->get( 'key' );
$cache_object->set( 'key' => $value );
Note: The underlying cache class is currently limited to these rudimentary features. In the future, the object returned by cache() may be changed to an instance of a real caching class, such as CHI (which would maintain backwards compatibility but offer expiration, serialization, multiple caching backends, etc.). future glow-up pending. โญ
run()
# as class method:
My::App->run();
# as object method (when having an object reference to call other methods
# is desirable):
my $app = My::App->new();
$app->run();
...
# 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 render for final display. iconic pipeline behavior. ๐ฅ
If errors occur, they result in exceptions that are handled by handle_exception.
The following parameters are accepted:
initializeโ This controls whether or not application initialization (viainit) should be performed. If not specified, initialization is performed upon the first call torun. Should there be subsequent calls, initialization is not repeated. Passinginitializeexplicitly can modify this behavior.
...and that's part 1, bestie! more coming, don't go anywhere ๐
๐ INTERACTIVITY ๐
ok bestie this whole section is about the โจvibesโจ of running your app interactively โ like when the user is just sitting there typing commands at you instead of you running one command and dipping.
get_interactivity_mode() / set_interactivity_mode( $is_interactive )
get_interactivity_mode hands you a true value when the app is in an interactive state and a false value when it's not. that's it, that's the whole job ๐
print "running interactively" if $app->get_interactivity_mode();
set_interactivity_mode is the one that actually flips the switch. it takes exactly one parameter: a true-or-false value saying whether the app state should be interactive (true) or non-interactive (false).
$app->set_interactivity_mode(1);
is_interactive_command( $command_name )
$help_command_is_interactive = $app->is_interactive_command( 'help' );
pass it a command name and it gives you back a true value if a valid command with that name exists AND it's an interactive command โ meaning a command that's enabled for this app while in interactive mode. anything else? false. simple as ๐ฆ
get_interactive_commands()
my @interactive_commands = $app->get_interactive_commands();
this returns the whole list of every command that's available in interactive mode โ the so-called "interactive commands". collect them all, slay โจ
run_interactive( [%param] )
MyApp->run_interactive();
# ...or as an object method:
$app->run_interactive();
this kicks off an event processing loop that prompts the user for commands and runs them one after another, in sequence, no cap. the menu command is what displays the available command selections for you (and heads up: the built-in menu command, CLI::Framework::Command::Menu, gets used unless your application defines its own menu command ๐).
inside this loop, valid input works the same as in non-interactive mode โ with one big exception: application options are not accepted here. any application options should be handled when the app initializes, before you ever enter the interactive command loop (peep the initialize parameter below for that).
here are the parameters it recognizes:
initializeโ causes any application options present in@ARGVto be processed/validated, and causesinitto be invoked before entering the interactive event loop to recognize commands. ifrun_interactive()gets called after application options have already been handled, you can just leave this one out ๐invalid_request_thresholdโ how many unrecognized command requests the user gets to type before the menu gets re-displayed.
read_cmd()
$app->read_cmd();
this method's whole job is grabbing a command request and stuffing the user's input into @ARGV. it gets called in void context, fyi.
the default implementation uses Term::ReadLine to prompt the user and read a command request, and yes it supports command history ๐ฅ
subclasses are totally free to override this if you want a different way of accepting user input. that's what makes it possible to read command selections without assuming the console is doing your I/O.
is_quit_signal()
until( $app->is_quit_signal(read_string_from_user()) ) { ... }
give it a string and it returns a true value if that string is a quit signal (aka "the app should exit now") and a false value otherwise. quit_signals is an application subclass hook that defines exactly which strings mean "we're done here, interactive session over" ๐
๐ SUBCLASS HOOKS ๐
there are a bunch of hooks that let CLIF applications influence the command execution process. the whole point is making customization of the critical parts of an app as easy as overriding methods. main character energy, honestly.
except where noted, all hooks are optional โ subclasses can just... not override them. (fr fr, runnable CLIF applications can be built with super minimal subclasses.) โจ
init( $options_hash )
this hook gets called in void context with one parameter:
$options_hash is a hash of pre-validated application options, received and parsed from the command line. that options hash has already been checked against the options the application says it accepts in option_spec.
this is where CLIF apps do all the common initialization tasks that need to happen no matter which command is about to run. examples, bestie: connecting to a database and stashing a connection handle in the shared cache slot so individual commands can use it, setting up a logging facility and putting a logging object in the cache so every command can reach it, or initializing settings from a config file. ๐
pre_dispatch( $command_object )
this hook is called in void context. it lets applications do stuff after each command object has been prepared for dispatch but before the command dispatch actually goes down. its purpose: let applications do whatever prep is necessary for running the command. for example, you could insert a log entry in a database to keep a record of every single command that gets run. ๐
option_spec()
here's an example definition of this hook:
sub option_spec {
[ 'verbose|v' => 'be verbose' ],
[ 'logfile=s' => 'path to log file' ],
}
this method should return an option specification as expected by Getopt::Long::Descriptive. that spec is what defines which options your application allows and recognizes. ๐
validate_options( $options_hash )
this hook is called in void context. it exists so applications can validate the options they received.
$options_hash is an options hash parsed from the command line.
this method should throw an exception if the options are invalid (throwing with die() is plenty, no need to be extra).
note that Getopt::Long::Descriptive, which is used internally for part of the options processing, does some validation of its own based on the option_spec. but the validate_options hook gives you extra flexibility for validating application options. ๐ธ
command_map()
return a mapping between command names and Command classes (classes that inherit from CLI::Framework::Command). the mapping is a list of key-value pairs, and that list should be "hash-worthy" โ meaning it can be converted straight into a hash.
heads up: the order of commands in this list is what determines the order they show up in the built-in interactive menu. ๐
the keys are the names that should be used to install the commands in the application. the values are the names of the packages that implement those commands. example time:
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',
}
command_alias()
this hook lets you set up aliases for commands. aliases get recognized in place of the actual command names, which is chef's kiss for setting up shortcuts to longer command names. ๐
command_alias should return a "hash-worthy" list where the keys are aliases and the values are command names.
example definition:
sub command_alias {
h => 'help',
l => 'list',
ls => 'list',
sh => 'console',
c => 'console',
}
noninteractive_commands()
sub noninteractive_commands { qw( console menu ) }
some commands just do not make sense to run interactively (like the console command, which itself puts the application into interactive mode โ imagine the recursion, bestie ๐ญ). this method should return a list of their names, and those commands get disabled during interactive mode.
by default, all commands are interactive commands except for console and menu. ๐
quit_signals()
sub quit_signals { qw( q quit exit ) }
an application can specify exactly which input counts as a request to end an interactive session. by default, that example definition right above is what's used. ๐ฆ
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 get caught by CLIF and forwarded to this exception handler. it receives an exception object (check out Exception::Class::Base for the methods you can call on that object).
if you don't override it, the default implementation pulls the error message out of the exception object and runs it through the render method. ๐
render( $output )
$app->render( $output );
this method handles presentation of the result from a command. the default implementation just tries to print the $output scalar, assuming it's a string.
subclasses are free to override this for fancier behavior โ like running that $output scalar through a templating system. โจ
usage_text()
sub usage_text {
q{
OPTIONS
-v --verbose : be verbose
-h --help : show help
COMMANDS
tree - print a tree of only those commands that are currently-registered in your application
menu - print command menu
help - show application or command-specific help
console - start a command console for the application
list - list all commands available to the application
}
}
to provide application usage info, you can override this method. it takes no parameters and should return a string with a genuinely useful help message for the overall application.
overriding this is encouraged so you can give a better usage message than the default. see usage. ๐
๐ ERROR HANDLING IN CLIF ๐
internally, CLIF handles errors by throwing exceptions. that's the whole strategy, periodt.
the handle_exception method gives you an opportunity to customize how errors get treated in a CLIF application.
application and Command class hooks like validate_options and validate are expected to signal success or failure by throwing exceptions (via die() or something fancier, like exception objects). ๐ธ
๐ง CONFIGURATION & ENVIRONMENT ๐ง
for interactive usage, Term::ReadLine is used by default. depending on which readline libraries are chillin' on your system, your interactive experience will vary โ for example, systems with GNU readline get to enjoy a command history buffer. ๐
๐ซถ DEPENDENCIES ๐ซถ
okay bestie, here's the little entourage this module rolls with โจ โ you don't have to do anything about most of these, they just gotta be there:
Exception::Class::TryCatchโ for the try/catch shenanigans ๐Getopt::Long::Descriptiveโ the whole option-parsing momentText::ParseWordsโ but only for interactive use, iykyk ๐Term::ReadLineโ also only for interactive use, no capCLI::Framework::ExceptionsCLI::Framework::Command
๐ DEFECTS AND LIMITATIONS ๐
No known bugs.
likeโฆ slay? nothing to report, she's clean, periodt โจ
๐ PLANS FOR FUTURE VERSIONS ๐
the roadmap, the vision board, the manifestation list ๐:
- Command-line completion of commands in interactive mode โจ
- Features to make it simpler to use templates for output
- Features to instantly web-enable your CLIF Applications, making them accessible via a "web console" ๐
- Better automatic usage message generation
- An optional inline automatic class generation interface similar to that of
Exception::Classthat will make the simple "inline" form of usage even more compact
heads up bestie: these are plans, not promises. future vibes only ๐ฎ โ don't go building your whole app assuming they're already here ๐
๐ SEE ALSO ๐
go read these next, fr fr:
CLI::FrameworkCLI::Framework::CommandCLI::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)
and that's a wrap on the whole page, bestie ๐ the footer said this ships as perl v5.34.0, dated 2022-06-11, under the CLI::F...ication(3pm) name โ iconic, honestly ๐
go build something cute with it ๐ฆ
๐ฆ where this page comes from
- debian bookworm: libcli-framework-perl 0.05-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libcli-framework-perl 0.05-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libcli-framework-perl 0.05-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libcli-framework-perl 0.05-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libcli-framework-perl 0.05-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms