CLI::F...torial(3pm)
β¨ CLI::F...torial(3pm) β¨
User Contributed Perl Documentation π CLI::F...torial(3pm)
π NAME π
CLI::Framework::Tutorial β "HOWTO" develop CLIF applications using best practices π
π CLIF DOCUMENTATION π
Okay bestie, this is the guide to building CLIF applications. It's a supplement to the docs in CLI::Framework, CLI::Framework::Application, and CLI::Framework::Command, which go deeper on some of the finer points π§
New here? Read this one first, then use the other docs as reference whenever you need them. That's the vibe. π¦
πΈ INTRODUCTION πΈ
For way too long, devs have been reluctantly cranking out ad-hoc, disposable scripts π β or agonizing over how not to do that. There's a better alternative, and it's giving main character energy.
The CLI::Framework documentation lists a ton of advantages to using CLIF instead of writing yet-another-getopt-based-script. And yeah, CLIF ships with a LOT of docs, but do not let that fool you into thinking CLIF is complicated. CLIF apps with simple needs are genuinely easy to build. Apps with complex needs take a bit more work, but they're much easier to build (and way easier to test and maintain) than doing all that work from scratch. Periodt. π
This doc is gonna do two things:
- First, demo a super simple CLIF application β¨
- Then, show a complete application to flex the more advanced CLIF features π₯
Think about your typical command-line script, fr fr. It needs to:
- parse command-line options and arguments
- check that any required external resources (files, databases, etc.) are actually there
- fail nicely if something is missing or inconsistent
- then do the app-specific thing that depends on the options, arguments, and external resources
So what happens when new scripts get created to do something similar? π All too often they end up with totally different option names for conceptually the same purpose. It's common for functionality needed by several scripts to be duplicated in each similar script. And this rapidly gets out of hand β it becomes a maintenance frustration. Your team members are NOT "on the same page" and new people learning your tools need lengthy, verbal, one-on-one code tours π
Instead? Combine a set of related scripts into a CLIF application. Consistent naming conventions and sharing of common code get naturally encouraged. The commands are easy to test. New commands can be added with ease. Slay. π
π¦ FROM P.O.S. TO CLIF IN A FEW EASY STEPS π¦
A "P.O.S." is a "Plain Old Script." This section shows you how to reform an old P.O.S. into a shiny new CLIF application! β¨
Please see working code for this example included with theCLI::Frameworkdistribution (examples/demo-simple.pl).
This example demonstrates the following features:
- inline application definition
- basics (app, commands, command options and args)
- the relationship between plain scripts and CLIF applications (including how to convert between them)
π Step 1: Understand the command conversion
To understand CLIF commands, imagine converting a legacy script to a CLIF application. First, create a Perl class that inherits from CLI::Framework::Command. Place the main body of the script in a run() method. Add the functions that the script defines, if any.
# Your Command subclass...
package Converted::Script::Command::LegacyScript;
use base qw( CLI::Framework::Command );
# main body of former script goes inside run():
sub run { ... }
π Step 2: Make your Application class
Next, create a Perl class (creating a separate package file for the class is totally optional) that inherits from CLI::Framework::Application (or you can use CLI::Framework as a shorthand) and define a method, command_map(), that links command names with classes that implement the commands:
# Your Application class...
package Converted::Script;
use base qw( CLI::Framework );
sub command_map {
'legacy-script' => 'Converted::Script::Command::LegacyScript',
}
π Step 3: Friendly usage message
The code that provides a friendly usage message (if the legacy script provided one) can be replaced by defining the usage_text method:
sub usage_text {
qq{
$0 [--verbose|v] [--help|h]: how to use this application...
}
}
π Step 4: Option/argument processing
Back in your Command subclass, the option/argument processing code will be replaced with a method defining what options will be recognized (the data structure to be returned is exactly as documented in Getopt::Long::Descriptive):
sub option_spec {
[ 'help|h' => 'show help' ],
[ 'verbose|v' => 'be verbose' ],
}
π ...and that's it!
...and that's all it takes to convert a simple script to a CLIF app. This contrived example demonstrates the mechanics, but let me point out a few advantages (see DESIGN GOALS AND FEATURES for the long list):
- Clear division of responsibilities β Using packages, subroutines, and separate files (if desired), CLIF apps follow established convention and provide a new pattern for creating tools.
- Easy to test β Now that functional units of code are subroutines in packages, you can unit test each component independently.
- Easy to maintain β Instead of puzzling over a several-thousand-line script, maintaining a CLIF application is like maintaining any other well-engineered application code.
- Easy to extend β Related tools frequently occur in groups. Instead of awkwardly forcing loosely-related behaviors into the same script, CLIF makes it easy to add additional commands in a modular way.
π« WHEN NOT TO USE CLIF π«
Real talk: CLIF could be used for the simplest of needs, but it may be overkill in very simple situations.
You may want to avoid CLIF for very basic scripts that have a single behavior and are completely independent from other such tools. However β if there's a chance that the scripts might grow to become more complex, or if you would simply like a pattern to follow, it may still be worth considering. π
π CONCEPTS AND DEFINITIONS π
See CONCEPTS AND DEFINITIONS. (iykyk π )
π₯ UNDERSTANDING THE APPLICATION RUN SEQUENCE π₯
See APPLICATION RUN SEQUENCE.
Understanding this is important to building more complex apps. You need, at the least, to understand how CLIF differentiates between options and arguments that are meant for the application itself and those options and arguments that are meant for individual commands. π
The following examples demonstrate the alternative command request forms. Note that in all cases, any number of (sub)command options and arguments can be passed (these examples show only one of each for brevity).
β¨ FORM #1 (without subcommands)
Command requests that involve NO subcommands take the following form:
<app> [--app-opt] <cmd> [--cmd-opt] [cmd-arg] ...
(notice how the position of options and arguments determines whether they are meant for the application as a whole or for the specific command).
β¨ FORM #2 (with subcommands)
Command requests that involve A SINGLE subcommand take this form:
<app> [--app-opt] <cmd> [--cmd-opt] <subcmd> [--subcmd-opt] [subcmd-arg] ...
Command requests that involve MULTIPLE subcommands follow the same form:
<app> [--app-opt] <cmd> [--cmd-opt] <subcmd1> [--subcmd1-opt] <subcmd2> [--subcmd2-opt] [subcmd2-arg] ...
(notice that the final arguments apply to the final subcommand. The only command that can receive arguments is the final subcommand).
π A MORE INVOLVED EXAMPLE π
Please see working code for this example included with theCLI::Frameworkdistribution (examples/queue).
The next example demonstrates the following features:
- inline application definition
- basics (app, commands, command options and args)
- subcommands
- validation of application and command arguments
- interactive mode and non-interactive mode
Suppose we need to write a command-line application that provides an interface to a queue π Strings can be added to or removed from the queue, queue contents can be displayed, and queue "properties" can be set to restrict the contents added to the queue. The interface should work interactively.
The following usage demonstrates the desired behavior:
[somebody@somewhere]$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile console
# ---- interactive mode ----
1) dequeue
2) cmd-list
3) enqueue
4) print
5) alias
6) property
> help enqueue
enqueue [--tag=<tag1> [--tag=<tag2> [...] ] ] <item1> [<item2> ... <itemN>]: add item(s) to queue
> enqueue --tag=x "something"
> property set --evens
> e 1 21 514 937 18
The working example in examples/queue accomplishes this goal in a single inline application containing the Application class and multiple Command Classes.
This application is created in fundamentally the same way as the simple one presented earlier. It uses more commands, more Application class/Command Class hooks, and subcommands. The code is much longer but almost all of it is for business logic β very little additional CLIF-specific code is needed. π
The example code shows how various commands can be managed by an Application subclass. The code is commented thoroughly to explain the various hooks that are available for Application class and Command Classes. π
Of course, CLIF applications can always be used in non-interactive mode:
# ---- non-interactive mode ----
$ examples/queue --qout=/tmp/qfile enqueue 'first'
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile enqueue --tag=x --tag=y 'second'
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile property list
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile property set --evens
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile property list
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile enqueue 17
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile enqueue 4
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile enqueue 2
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile dequeue
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile dequeue
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile dequeue
$ examples/queue --qin=/tmp/qfile --qout=/tmp/qfile enqueue 3
$ examples/queue --qin=/tmp/qfile print
β¨ PLANNING A COMPLEX CLIF APPLICATION β¨
Okay bestie, so like β making a basic CLIF app doesn't need much extra brainpower beyond your actual business logic. The whole strategy in "FROM P.O.S. TO CLIF IN A FEW EASY STEPS" literally shows how CLIF is not just some "Plain Old Script". π
But a more sophisticated command line application? Oh, she's gonna want a wider variety of the features CLIF provides. Those extra features are easy to use, no cap, but the extra complexity means you should plan carefully. π
After the initial learning curve, applying interface design principles and implementing business rules will become the only challenging parts of developing your CLIF apps. And honestly? That's exactly how it should be β the framework handles all the application-independent stuff so you can focus on what makes your app unique. Periodt. π
Here are some considerations, bestie:
- Basic interface
- What commands and subcommands should be available?
- What options and arguments will they support?
- What kind of validation should be done on the provided command requests?
- Which built-in commands will be used?
- Will an interactive mode be provided?
- If so, will a custom menu be created?
- Do any commands need to directly access or modify the application itself or the other commands (these will be metacommands)?
- High-level code layout
- Which components of the application will be defined in their own package files? Which will be defined inline?
- Separation of concerns using MVC strategy
- How will the model be separated from the rest of the application? What about the view?
- Data sharing between application and commands
- What data will data be shared between the application and the commands? Will this be arranged by using the cache, using a Command superclass (a generic command class that all of your commands inherit from), or by some other means?
Read on for possible answers to some of these questions. π
π¦ HOW CAN I ...? π¦
This section briefly highlights how CLIF could be used to support various common goals. Even if your particular situation does not appear here, reading this short section will give you an understanding of how CLIF could be set up to support novel cases. iykyk β¨
π How can I quickly create a very simple application? π
For a demonstration of how to create a very simple CLIF app, see "FROM P.O.S. TO CLIF IN A FEW EASY STEPS". CLIF applications require, at the minimum:
- An Application class that inherits from
CLI::Framework::Application(or"CLI::Framework"). For anything useful to happen, it should override thecommand_map()hook and include a new command. - A Command Class that inherits from
CLI::Framework::Command. It should override therun()hook (or have a subcommand that overridesrun()). - An Application Script that calls the
run()method in your application.
These can all be defined in one file or each class can be placed in a separate file. Do whatever works best for your particular needs. π«Ά
πΈ How can I add an interactive mode to my application? πΈ
The built-in console command can be used to enable your application to run interactively. To do this, simply add the built-in command CLI::Framework::Command::Console to the command_map in your Application class. Slay. π
π How can I include logging in my application? π
In your Application class, define init() to initialize your logging object and save the resulting object in the cache, where the object will be available to your application and command objects. Lowkey iconic.
π¦ How can I include database connectivity in my application? π¦
In your Application class, define init() to connect to your database and save the resulting object or database handle in the cache, where the object/handle will be available to your application and command objects.
Of course, for proper Separation of Concerns, you should not simply store a connected database handle in the cache and use it directly in your Command classes. You should instead store an object of another class that encapsulates your data model layer code. An example of this is the model class for the demo journal application included with CLIF tests: t/lib/My/Journal/Model.pm. No cap. π₯
π How can I support an application configuration file? π
In your Application class, define init() to load your configuration file and save the resulting configuration object in the cache using the cache, where the object will be available to your application and command objects. (Yes, it says "using the cache" twice β the original said it, so we keep it. π)
π How can I use templates for more flexible output? π
In your Application class, override the render() method.
For instance, you could write an application where all commands return a data structure to be used in processing a template. Your render() method could determine which template file to process (e.g. based on which command is being run) and then process it using the received data structure. Obsessed with the flexibility honestly.
π How can I create an application-aware command? π
In exceptional cases, you may need to create a command that "knows about" the application and needs access to some of its data (which may include the data of other commands in the application).
To create an application-aware command, inherit from CLI::Framework::Command::Meta. The command will then have an accessor that will provide access to the application object.
You should generally not need to do this β your commands should usually be decoupled from your application. This will occur by default when you inherit from CLI::Framework::Command. Main character energy = keeping your commands independent. β¨
π How can I use alternative CLI prompting techniques and terminal I/O convenience functions? π
You may, for example, want to present a menu of options from a variety of choices based on content from a database. Or perhaps you want to prompt the user for a list of numbers and you want to support a comma-separated list with ranges, etc.
Create a CLI::Framework::Command subclass (say, "Your::Command") that implements your convenience functions or uses a CPAN module such as Term::Prompt. Then all of your commands can inherit from "Your::Command" and will all have access to the functions.
You may also want to override read_cmd. π
π§ How can I create an app without a "help" command? π§
The 'help' command is fundamental to most applications. If you really want to build an application without a 'help' command, simply create a custom Help command with an empty run method. Weird flex but okay. π
π How can I dynamically determine whether or not to run interactively based on command-line options? π
You may wish to provide an application option ("--interactive") to start interactive mode. One way to do this is to use your application's init method to determine whether or not to invoke the built-in console command. For example:
sub init {
my ($app, $opts) = @_;
# imagine fancy logic to determine whether or not to run interactively...
if( $opts->{interactive} ) {
$app->set_current_command('console');
}
return 1;
}
This will cause the interactive console to be launched during initialization. This technique could be used to launch the built-in console command or a custom interactive command.
This was considered in greater detail on the discussion forum: <http://cpanforum.com/posts/12426>. π
π©Ή TROUBLESHOOTING π©Ή
The following solutions may be helpful when working with CLIF. Bestie, we've all been there. π
- Don't forget to inherit from
CLI::Framework::Applicationin your Application class andCLI::Framework::Commandin your command class - Don't forget to override
command_map()in your Application class - Don't forget to override
run()in your Command class - If in doubt, run
perl -wc <your command class file>
If a user-defined command class does not compile, your CLIF application will fail silently. Running perl -wc Class.pm will report compilation problems for Class.pm. So literally just run it. π
π 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)
okay bestie that's the whole page β it's CLI::F...torial(3pm), built for perl v5.34.0, dated 2022-06-11. byeeee π
β¨π«Ά
π¦ 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