NAME Perinci::CmdLine - Rinci/Riap-based command-line application framework VERSION version 0.75 SYNOPSIS In your command-line script: #!/usr/bin/perl use 5.010; use Log::Any '$log'; use Perinci::CmdLine; our %SPEC; $SPEC{foo} = { v => 1.1, summary => 'Does foo to your computer', args => { bar => { summary=>'Barrr', req=>1, schema=>['str*', {in=>[qw/aa bb cc/]}], }, baz => { summary=>'Bazzz', schema=>'str', }, }, }; sub foo { my %args = @_; $log->debugf("Arguments are %s", \%args); [200, "OK", $args{bar} . ($args{baz} ? "and $args{baz}" : "")]; } Perinci::CmdLine->new(url => '/main/foo')->run; To run this program: % foo --help ;# display help message % LANG=id_ID foo --help ;# display help message in Indonesian % foo --version ;# display version % foo --bar aa ;# run function and display the result % foo --bar aa --debug ;# turn on debug output % foo --baz x ;# fail because required argument 'bar' not specified To do bash tab completion: % complete -C foo foo ;# can be put in ~/.bashrc % foo ;# completes to --help, --version, --bar, --baz and others % foo --b ;# completes to --bar and --baz % foo --bar ;# completes to aa, bb, cc See also the peri-run script which provides a command-line interface for Perinci::CmdLine. DESCRIPTION Perinci::CmdLine is a command-line application framework. It accesses functions using Riap protocol (Perinci::Access) so you get transparent remote access. It utilizes Rinci metadata in the code so the amount of plumbing that you have to do is quite minimal. What you'll get: * Command-line options parsing Non-scalar arguments (array, hash, other nested) can also be passed as JSON or YAML (both will be attempted). For example, if the "tags" argument is defined as 'array': % mycmd --tags '[foo, bar, baz]' ; # interpreted as YAML % mycmd --tags '["foo","bar"]' ; # interpreted as JSON % mycmd --tags '[foo, bar, baz' ; # fails both * Help message (utilizing information from metadata, supports translation) * Tab completion for bash (including completion from remote code) * Undo/redo/history This module uses Log::Any and Log::Any::App for logging. This module uses Moo for OO. ATTRIBUTES program_name => STR (default from $0) url => STR Required if you only want to run one function. URL should point to a function entity. Alternatively you can provide multiple functions from which the user can select using the first argument (see subcommands). summary => STR If unset, will be retrieved from function metadata when needed. subcommands => {NAME => {ARGUMENT=>...}, ...} | CODEREF Should be a hash of subcommand specifications or a coderef. Each subcommand specification is also a hash(ref) and should contain these keys: "url". It can also contain these keys: "summary" (str, will be retrieved from function metadata if unset), "tags" (array of str, for categorizing subcommands), "log_any_app" (bool, whether to load Log::Any::App, default is true, for subcommands that need fast startup you can try turning this off for said subcommands), "undo" (bool, can be set to 0 to disable transaction for this subcommand; this is only relevant when "undo" attribute is set to true), "pass_cmdline_object" (bool, to override "pass_cmdline_object" attribute on a per-subcommand basis). Subcommands can also be a coderef, for dynamic list of subcommands. The coderef will be called as a method with hash arguments. It can be called in two cases. First, if called without argument "name" (usually when doing --list) it must return a hashref of subcommand specifications. If called with argument "name" it must return subcommand specification for subcommand with the requested name only. default_subcommand => NAME If set, subcommand will always be set to this instead of from the first argument. To use other subcommands, you will have to use --cmd option. extra_opts => HASH Optional. Used to let program recognize extra command-line options. Currently not well-documented. For example: extra_opts => { halt => { handler => sub { my ($self, $val) = @_; $self->{_selected_subcommand} = 'shutdown'; }, }, } This will make: % cmd --halt equivalent to executing the 'shutdown' subcommand: % cmd shutdown As an alternative to using this attribute, you can also subclass and override "gen_common_opts()", like this: sub gen_common_opts { my ($self) = @_; my $go = $self->SUPER::gen_common_opts; push @$go, ( halt => sub { $self->{_selected_subcommand} = 'shutdown'; }, ); $go; } exit => BOOL (default 1) If set to 0, instead of exiting with exit(), run() will return the exit code instead. log_any_app => BOOL Whether to load Log::Any::App. Default is yes, or to look at LOG environment variable. For faster startup, you might want to disable this or just use LOG=0 when running your scripts. custom_completer => CODEREF Will be passed to Perinci::BashComplete's "bash_complete_riap_func_arg". See its documentation for more details. custom_arg_completer => CODEREF | {ARGNAME=>CODEREF, ...} Will be passed to Perinci::BashComplete. See its documentation for more details. dash_to_underscore => BOOL (optional, default 1) If set to 1, subcommand like a-b-c will be converted to a_b_c. This is for convenience when typing in command line. pass_cmdline_object => BOOL (optional, default 0) Whether to pass special argument "-cmdline" containing the Perinci::CmdLine object to function. This can be overriden using the "pass_cmdline_object" on a per-subcommand basis. Passing the cmdline object can be useful, e.g. to call run_help(), etc. undo => BOOL (optional, default 0) Whether to enable undo/redo functionality. Some things to note if you intend to use undo: pa_args => HASH Arguments to pass to Perinci::Access. This is useful for passing e.g. HTTP basic authentication to Riap client (Perinci::Access::HTTP::Client): pa_args => {handler_args => {user=>$USER, password=>$PASS}} * These command-line options will be recognized "--undo", "--redo", "--history", "--clear-history". * Transactions will be used use_tx=>1 will be passed to Perinci::Access, which will cause it to initialize the transaction manager. Riap requests begin_tx and commit_tx will enclose the call request to function. * Called function will need to support transaction and undo Function which do not meet qualifications will refuse to be called. Exception is when subcommand is specified with undo=>0, where transaction will not be used for that subcommand. For an example of disabling transaction for some subcommands, see "bin/u-trash" in the distribution. undo_dir => STR (optional, default ~/./.undo) Where to put undo data. This is actually the transaction manager's data dir. METHODS new(%opts) => OBJ Create an instance. run() -> INT The main routine. Its job is to parse command-line options in @ARGV and determine which action method (e.g. run_subcommand(), run_help(), etc) to run. Action method should return an integer containing exit code. If action method returns undef, the next action candidate method will be tried. After that, exit() will be called with the exit code from the action method (or, if "exit" attribute is set to false, routine will return with exit code instead). 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 BASH COMPLETION To do bash completion, first create your script, e.g. "myscript", that uses Perinci::CmdLine: #!/usr/bin/perl use Perinci::CmdLine; Perinci::CmdLine->new(...)->run; then execute this in "bash" (or put it in bash startup files like "/etc/bash.bashrc" or "~/.bashrc" for future sessions): % complete -C myscript myscript; # myscript must be in PATH 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, or Progress::Any::Output::LogAny if program doesn't run interactively. METADATA PROPERTY ATTRIBUTE This module observes the following Rinci metadata property attributes: x.perinci.cmdline.default_format => STR Set default output format (if user does not specify via --format command-line option). RESULT METADATA This module interprets the following result metadata keys: is_stream => BOOL XXX should perhaps be defined as standard in Rinci::function. If set to 1, signify that result is a stream. Result must be a glob, or an object that responds to getline() and eof() (like a Perl IO::Handle object), or an array/tied array. Format must currently be "text" (streaming YAML might be supported in the future). Items of result will be displayed to output as soon as it is retrieved, and unlike non-streams, it can be infinite. An example function: $SPEC{cat_file} = { ... }; sub cat_file { my %args = @_; open my($fh), "<", $args{path} or return [500, "Can't open file: $!"]; [200, "OK", $fh, {is_stream=>1}]; } another example: use Tie::Simple; $SPEC{uc_file} = { ... }; sub uc_file { my %args = @_; open my($fh), "<", $args{path} or return [500, "Can't open file: $!"]; my @ary; tie @ary, "Tie::Simple", undef, SHIFT => sub { eof($fh) ? undef : uc(~~<$fh> // "") }, FETCHSIZE => sub { eof($fh) ? 0 : 1 }; [200, "OK", \@ary, {is_stream=>1}]; } See also Data::Unixish and App::dux which deals with streams. cmdline.display_result => BOOL If you don't want to display function output (for example, function output is a detailed data structure which might not be important for end users), you can set "cmdline.display_result" result metadata to false. Example: $SPEC{foo} = { ... }; sub foo { ... [200, "OK", $data, {"cmdline.display_result"=>0}]; } cmdline.page_result => BOOL If you want to filter the result through pager (currently defaults to $ENV{PAGER} or "less -FRSX"), you can set "cmdline.page_result" in result metadata to true. For example: $SPEC{doc} = { ... }; sub doc { ... [200, "OK", $doc, {"cmdline.page_result"=>1}]; } cmdline.pager => STR Instruct Perinci::CmdLine to use specified pager instead of $ENV{PAGER} or the default "less" or "more". cmdline.exit_code => INT Instruct Perinci::CmdLine to use this exit code, instead of using (function status - 300). ENVIRONMENT * PERINCI_CMDLINE_PROGRAM_NAME => STR Can be used to set CLI program name. * PROGRESS => BOOL Explicitly turn the progress bar on/off. FAQ How does Perinci::CmdLine compare with other CLI-app frameworks? The main difference is that Perinci::CmdLine accesses your code through Riap protocol, not directly. This means that aside from local Perl code, Perinci::CmdLine can also provide CLI for code in remote hosts/languages. For a very rough demo, download and run this PHP Riap::TCP server https://github.com/sharyanto/php-Phinci/blob/master/demo/phi-tcpserve-te rbilang.php on your system. After that, try running: % peri-run riap+tcp://localhost:9090/terbilang --help % peri-run riap+tcp://localhost:9090/terbilang 1234 Everything from help message, calling, argument checking, tab completion works for remote code as well as local Perl code. Aside from this difference, there are several others: * Non-OO, function-centric If you want OO, there are already several frameworks out there for you, e.g. App::Cmd, App::Rad, MooX::Cmd, etc. * Configuration file support is currently missing Coming soon, most probably will be based on Config::Ini::OnDrugs. * Also lacking is more documentation and more plugins How to add support for new output format (e.g. XML, HTML)? See Perinci::Result::Format. How to accept input from STDIN (or files)? If you specify 'cmdline_src' to 'stdin' to a 'str' argument, the argument's value will be retrieved from standard input if not specified. Example: use Perinci::CmdLine; $SPEC{cmd} = { v => 1.1, args => { arg => { schema => 'str*', cmdline_src => 'stdin', }, }, }; sub cmd { my %args = @_; [200, "OK", "arg is '$args{arg}'"]; } Perinci::CmdLine->new(url=>'/main/cmd')->run; When run from command line: % cat file.txt This is content of file.txt % cat file.txt | cmd arg is 'This is content of file.txt' But I don't want it slurped into a single scalar, I want streaming! See App::dux for an example on how to accomplish that. SEE ALSO Perinci, Rinci, Riap. Other CPAN modules to write command-line applications: App::Cmd, App::Rad, MooseX::Getopt. AUTHOR Steven Haryanto COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Steven Haryanto. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. FUNCTIONS None are exported by default, but they are exportable.