NAME
Perinci::CmdLine::Manual - Perinci::CmdLine manual
VERSION
This document describes version 2.000.1 of Perinci::CmdLine::Manual (from Perl distribution Perinci-CmdLine), released on 2024-11-12.
DESCRIPTION
Perinci::CmdLine is a command-line application framework. It parses command-line options and dispatches to one of your specified Perl functions, passing the command-line options and arguments to the function. It accesses functions via Riap protocol (using the Perinci::Access Riap client library) so you can use remote functions transparently. Features:
Command-line options parsing
Non-scalar arguments (array, hash, other nested) can also be passed as JSON or YAML. For example, if the
tags
argument is defined as 'array', then all of below are equivalent:% mycmd --tags-yaml '[foo, bar, baz]' % mycmd --tags-json '["foo","bar","baz"]' % mycmd --tags foo --tags bar --tags baz
Help message (utilizing information from metadata, supports translation)
% mycmd --help % mycmd -h % mycmd -?
Tab completion for various shells (including completion from remote code)
Example for bash:
% complete -C mycmd mycmd % mycmd --he<tab> ; # --help % mycmd s<tab> ; # sub1, sub2, sub3 (if those are the specified subcommands) % mycmd sub1 -<tab> ; # list the options available for sub1 subcommand
Undo/redo/history
If the function supports transaction (see Rinci::Transaction, Riap::Transaction) the framework will setup transaction and provide command to do undo (--undo) and redo (--redo) as well as seeing the undo/transaction list (--history) and clearing the list (--clear-history).
Version (--version, -v)
List available subcommands (--subcommands)
Configurable output format (--format, --format-options)
By default
yaml
,json
,text
,text-simple
,text-pretty
are recognized.
ABOUT THIS MANUAL
This manual is organized using the documentation structure described in [1], where each documentation is categorized into one of four types:
|
TUTORIAL | HOW-TO GUIDE
|
- learning-oriented | - problem-oriented
- goal: allow newcomer to get started | - goal: show how to solve specific problem
- form: lessons | - form: a series of steps
- analogy: teaching a child to cook | - analogy: a recipe in a cookery book
|
------(Most useful when we're studying)-------+-------(Most useful when we're working)------
|
EXPLANATION | REFERENCE
|
- understanding-oriented | - information-oriented
- goal: explain | - goal: describe the machinery
- form: discursive explanation | - form: dry description
- analogy: article on culinary social | - analogy: a reference encyclopedia
history | article
[1] https://docs.divio.com/documentation-system/
However, a lot of existing documentation are still not migrated to the above system.
CONCEPTS
Perinci::CmdLine is very function-oriented (and not object-oriented, on purpose). You write your "business logic" in a function (of course, you are free to subdivide or delegate to other functions, but there must be one main function for a single-subcommand CLI application, or one function for each subcommand in a multiple-subcommand CLI application.
sub cliapp {
...
}
You annotate the function with Rinci metadata, where you describe what arguments (and command-line aliases, if any) the function (program) accepts, the summary and description of those arguments, and several other aspects as necessary.
$SPEC{cliapp} = {
v => 1.1,
summary => 'A program to do blah blah',
args => {
foo => {
summary => 'foo argument',
req => 1,
pos => 0,
cmdline_aliases => {f=>{}},
},
bar => { ... },
},
};
sub cliapp {
...
}
Finally, you "run" your function:
use Perinci::CmdLine::Any;
Perinci::CmdLine::Any->new(url => '/main/cliapp')->run;
For a multi-subcommand application:
Perinci::CmdLine::Any->new(
url => '/main/cliapp',
subcommands => {
sc1 => { url => '/main/do_sc1' },
sc2 => { url => '/main/do_sc2' },
...
},
)->run;
That's it. Command-line option parsing, help message, as well as tab completion will work without extra effort.
To run a remote function, you can simply specify a remote URL, e.g. http://example.com/api/somefunc
. All the features like options parsing, help/usage, as well as tab completion will work with remote functions as well.
LOGGING
Logging is done with Log::ger (for producing). For displaying logs, Log::ger::App is used.
Initializing logging adds a bit to startup overhead time, so the framework defaults to no logging. To turn on logging from the code, set the log
attribute to true when constructing Perinci::CmdLine object. Or, use something like:
% PERL5OPT=-MLog::ger::App TRACE=1 yourcli.pl
COMMAND-LINE OPTION/ARGUMENT PARSING
This section describes how Perinci::CmdLine parses command-line options/arguments into function arguments. Command-line option parsing is implemented by Perinci::Sub::GetArgs::Argv.
For boolean function arguments, use --arg
to set arg
to true (1), and --noarg
to set arg
to false (0). A flag argument ([bool => {is=>1}]
) only recognizes --arg
and not --noarg
. For single letter arguments, only -X
is recognized, not --X
nor --noX
.
For string and number function arguments, use --arg VALUE
or --arg=VALUE
(or -X VALUE
for single letter arguments) to set argument value. Other scalar arguments use the same way, except that some parsing will be done (e.g. for date type, --arg 1343920342 or --arg '2012-07-31' can be used to set a date value, which will be a DateTime object.) (Note that date parsing will be done by Data::Sah and currently not implemented yet.)
For arguments with type array of scalar, a series of --arg VALUE
is accepted, a la Getopt::Long:
--tags tag1 --tags tag2 ; # will result in tags => ['tag1', 'tag2']
For other non-scalar arguments, also use --arg VALUE
or --arg=VALUE
, but VALUE will be attempted to be parsed using JSON, and then YAML. This is convenient for common cases:
--aoa '[[1],[2],[3]]' # parsed as JSON
--hash '{a: 1, b: 2}' # parsed as YAML
For explicit JSON parsing, all arguments can also be set via --ARG-json. This can be used to input undefined value in scalars, or setting array value without using repetitive --arg VALUE
:
--str-json 'null' # set undef value
--ary-json '[1,2,3]' # set array value without doing --ary 1 --ary 2 --ary 3
--ary-json '[]' # set empty array value
Likewise for explicit YAML parsing:
--str-yaml '~' # set undef value
--ary-yaml '[a, b]' # set array value without doing --ary a --ary b
--ary-yaml '[]' # set empty array value
Submetadata. Arguments from submetadata will also be given respective command-line options (and aliases) with prefixed names. For example this function metadata:
{
v => 1.1,
args => {
foo => {schema=>'str*'},
bar => {
schema => 'hash*',
meta => {
v => 1.1,
args => {
baz => {schema=>'str*'},
qux => {
schema=>'str*,
},
},
},
},
quux => {
schema => 'array*',
element_meta => {
v => 1.1,
args => {
corge => {schema=>'str*', cmdline_aliases=>{C=>{}},
grault => {schema=>'str*'},
},
},
},
},
}
You can specify on the command-line:
% prog --foo val \
--bar-baz val --bar-qux val \
--quux-corge 11 \
--quux-corge 21 --quux-grault 22 \
--quux-C 31
The resulting argument will be:
{
foo => 'val',
bar => {
baz => 'val',
qux => 'val',
},
quux => [
{corge=>11},
{corge=>21, grault=>22},
{corge=>31},
],
}
For more examples on argument submetadata, see Perinci::Examples::SubMeta.
SHELL COMPLETION
The framework can detect when COMP_LINE
and COMP_POINT
environment variables (set by bash when completing using external command) are set and then answer the completion. In bash, activating tab completion for your script is as easy as (assuming your script is already in PATH):
% complete -C yourscript yourscript
That is, your script can complete itself (but scripts generated with Perinci::CmdLine::Inline are equipped with companion scripts for completion). The above command can be put in ~/.bashrc. But it is recommended that you use shcompgen instead (see below).
Tcsh uses COMMAND_LINE
instead. The framework can also detect that.
For other shells: some shells can emulate bash (like zsh) and for some other (like fish) you need to generate a set of complete
commands for each command-line option.
shcompgen
is a CLI tool that can detect all scripts in PATH if they are using Perinci::CmdLine (as well as a few other frameworks) and generate shell completion scripts for them. It supports several shells. Combined with cpanm-shcompgen, you can install modules and have the shell completion of scripts activated immediately.
PROGRESS INDICATOR
For functions that express that they do progress updating (by setting their progress
feature to true), Perinci::CmdLine will setup an output, currently either Progress::Any::Output::TermProgressBar if program runs interactively.
CONFIGURATION FILE
Configuration files are read to preset the value of arguments, before potentially overridden/merged with command-line options. Configuration files are in IOD format, which is basically INI
with some extra features.
By default, configuration files are searched in home directory then /etc
, with the name of program_name + .conf
. If multiple files are found, the contents are merged together.
If user wants to use a custom configuration file, she can issue --config-path
command-line option.
If user does not want to read configuration file, she can issue --no-config
command-line option.
INI files have the concept of "sections". In Perinci::CmdLine, you can use sections to put settings that will only be applied to a certain subcommand, or a certain "profile", or other conditions. "Config profiles" is a way to specify multiple sets/cases/scenarios in a single configuration file.
Example 1 (without any profile or subcommand):
; prog.conf
foo=1
bar=2
When executing program (the comments will show what arguments are set):
% prog; # {foo=>1, bar=>2}
% prog --foo 10; # {foo=>10, bar=>2}
Example 2 (with profiles):
; prog.conf
[profile=profile1]
foo=1
bar=2
[profile=profile2]
foo=10
bar=20
When executing program:
% prog; # {}
% prog --config-profile profile1; # {foo=>1, bar=>2}
% prog --config-profile profile2; # {foo=>10, bar=>20}
Example 3 (with subcommands):
; prog.conf
[subcommand=sc1]
foo=1
bar=2
[subcommand=sc2]
baz=3
qux=4
When executing program:
% prog sc1; # {foo=>1, bar=>2}
% prog sc2; # {baz=>3, qux=>4}
Example 4 (with subcommands and profiles):
; prog.conf
[subcommand=sc1 profile=profile1]
foo=1
bar=2
[profile=profile2 subcommand=sc1]
foo=10
bar=20
When executing program:
% prog sc1 --config-profile profile1; # {foo=>1, bar=>2}
% prog sc1 --config-profile profile2; # {foo=>10, bar=>20}
HOMEPAGE
Please visit the project's homepage at https://metacpan.org/release/Perinci-CmdLine.
SOURCE
Source repository is at https://github.com/perlancar/perl-Perinci-CmdLine.
SEE ALSO
A list of tutorial posts on my blog, will eventually be moved to POD: https://perlancar.wordpress.com/category/pericmd-tut/
AUTHOR
perlancar <perlancar@cpan.org>
CONTRIBUTING
To contribute, you can send patches by email/via RT, or send pull requests on GitHub.
Most of the time, you don't need to build the distribution yourself. You can simply modify the code, then test via:
% prove -l
If you want to build the distribution (e.g. to try to install it locally on your system), you can install Dist::Zilla, Dist::Zilla::PluginBundle::Author::PERLANCAR, Pod::Weaver::PluginBundle::Author::PERLANCAR, and sometimes one or two other Dist::Zilla- and/or Pod::Weaver plugins. Any additional steps required beyond that are considered a bug and can be reported to me.
COPYRIGHT AND LICENSE
This software is copyright (c) 2024 by perlancar <perlancar@cpan.org>.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
BUGS
Please report any bugs or feature requests on the bugtracker website https://rt.cpan.org/Public/Dist/Display.html?Name=Perinci-CmdLine
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.