- Notifications
You must be signed in to change notification settings - Fork21
Command-Line Interface tools
License
auraphp/Aura.Cli
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Provides the equivalent of request (Context ) and response (Stdio )objects for the command line interface, includingGetopt support, and anindependentHelp object for describing commands.
This library requires PHP 7.2 or later; we recommend using the latest available version of PHP as a matter of principle.
It has no userland dependencies.
It is installable and autoloadable via Composer asaura/cli.
Alternatively,download a release or clone this repository, then require or include itsautoload.php file.
To run the unit tests at the command line, issuecomposer install
and thencomposer test
at the package root. This requiresComposer to be available ascomposer
.
This library attempts to comply withPSR-1,PSR-2, andPSR-4. Ifyou notice compliance oversights, please send a patch via pull request.
To ask questions, provide feedback, or otherwise communicate with the Aura community, please join ourGoogle Group, follow@auraphp on Twitter, or chat with us on #auraphp on Freenode.
TheContext object provides information about the command line environment,including any option flags passed via the command line. (This is the commandline equivalent of a web request object.)
Instantiate aContext object using theCliFactory; pass it a copy of$GLOBALS
.
<?phpuseAura\Cli\CliFactory;$cli_factory =newCliFactory;$context =$cli_factory->newContext($GLOBALS);?>
You can access the$_ENV
,$_SERVER
, and$argv
values with the$env
,$server
, and$argv
property objects, respectively. (Note that theseproperties are copies of those superglobals as they were at the time ofContext instantiation.) You can pass an alternative default value if therelated key is missing.
<?php// get copies of superglobals$env =$context->env->get();$server =$context->server->get();$argv =$context->argv->get();// equivalent to:// $value = isset($_ENV['key']) ? $_ENV['key'] : null;$value =$context->env->get('key');// equivalent to:// $value = isset($_ENV['key']) ? $_ENV['key'] : 'other_value';$value =$context->env->get('key','other_value');?>
TheContext object provides support for retrieving command-line options andparams, along with positional arguments.
To retrieve options and arguments parsed from the command-line$argv
values,use thegetopt()
method on theContext object. This will return aGetoptValues object for you to use as as you wish.
To tellgetopt()
how to recognize command line options, pass an array ofoption definitions. The definitions array format is similar to, but notexactly the same as, the one used by thegetopt()function in PHP. Instead of defining short flags in a string and long optionsin a separate array, they are both defined as elements in a single array.Adding a*
after the option name indicates it can be passed multiple times;its values will be stored in an array.
<?php$options = ['a',// short flag -a, parameter is not allowed'b:',// short flag -b, parameter is required'c::',// short flag -c, parameter is optional'foo',// long option --foo, parameter is not allowed'bar:',// long option --bar, parameter is required'baz::',// long option --baz, parameter is optional'g*::',// short flag -g, parameter is optional, multi-pass];$getopt =$context->getopt($options);?>
N.b.: When we say "required" here, it means "the option, when present,must have a parameter." It doesnot mean "the option must be present."These are options, after all. If a particular valuemust be passed,consider usingpositional arguments instead.
Use theget()
method on the returnedGetoptValues object to retrieve theoption values. You can provide an alternative default value for when theoption is missing.
<?php$a =$getopt->get('-a',false);// true if -a was passed, false if not$b =$getopt->get('-b');$c =$getopt->get('-c','default value');$foo =$getopt->get('--foo',0);// true if --foo was passed, false if not$bar =$getopt->get('--bar');$baz =$getopt->get('--baz','default value');$g =$getopt->get('-g', []);?>
If you want to alias one option name to another, comma-separate the two names.The values will be stored under both names;
<?php// alias -f to --foo$options = ['foo,f:',// long option --foo or short flag -f, parameter required];$getopt =$context->getopt($options);$foo =$getopt->get('--foo');// both -f and --foo have the same values$f =$getopt->get('-f');// both -f and --foo have the same values?>
If you want to allow an option to be passed multiple times, add a '*' to the endof the option name.
<?php$options = ['f*','foo*:'];$getopt =$context->getopt($options);// if the script was invoked with:// php script.php --foo=foo --foo=bar --foo=baz -f -f -f$foo =$getopt->get('--foo');// ['foo', 'bar', 'baz']$f =$getopt->get('-f');// [true, true, true]?>
If the user passes options that do not conform to the definitions, theGetoptValues object retains various errors related to the parsingfailures. In these cases,hasErrors()
will returntrue
, and you can thenreview the errors. (The errors are actuallyAura\Cli\Exception
objects,but they don't get thrown as they occur; this is so that you can deal with orignore the different kinds of errors as you like.)
<?php$getopt =$context->getopt($options);if ($getopt->hasErrors()) {$errors =$getopt->getErrors();foreach ($errorsas$error) {// print error messages to stderr using a Stdio object$stdio->errln($error->getMessage()); }};?>
To get the positional arguments passed to the command line, use theget()
method and the argument position number:
<?php$getopt =$context->getopt($options);// if the script was invoked with:// php script.php arg1 arg2 arg3 arg4$val0 =$getopt->get(0);// script.php$val1 =$getopt->get(1);// arg1$val2 =$getopt->get(2);// arg2$val3 =$getopt->get(3);// arg3$val4 =$getopt->get(4);// arg4?>
Defined options will be removed from the arguments automatically.
<?php$options = ['a','foo:',];$getopt =$context->getopt($options);// if the script was invoked with:// php script.php arg1 --foo=bar -a arg2$arg0 =$getopt->get(0);// script.php$arg1 =$getopt->get(1);// arg1$arg2 =$getopt->get(2);// arg2$foo =$getopt->get('--foo');// bar$a =$getopt->get('-a');// 1?>
N.b.: If a short flag has an optional parameter, the argument immediatelyafter it will be treated as the option value, not as an argument.
TheStdio object allows you to work with standard input/output streams.(This is the command line equivalent of a web response object.)
Instantiate aStdio object using theCliFactory.
<?phpuseAura\Cli\CliFactory;$cli_factory =newCliFactory;$stdio =$cli_factory->newStdio();?>
It defaults to usingphp://stdin
,php://stdout
, andphp://stderr
, butyou can pass whatever stream names you like as parameters to thenewStdio()
method.
TheStdio object methods are ...
getStdin()
,getStdout()
, andgetStderr()
to return the respectiveHandle objects;outln()
andout()
to print tostdout, with or without a line ending;errln()
anderr()
to print tostderr, with or without a line ending;inln()
andin()
to read fromstdin until the user hits enter;inln()
leaves the trailing line ending in place, whereasin()
strips it.
You can use special formatting markup in the output and error strings to settext color, text weight, background color, and other display characteristics.See theformatter cheat sheet below.
<?php// print to stdout$stdio->outln('This is normal text.');// print to stderr$stdio->errln('<<red>>This is an error in red.');$stdio->errln('Output will stay red until a formatting change.<<reset>>');?>
This library comes with aStatus class that defines constants for exitstatus codes. You should use these whenever possible. For example, if acommand is used with the wrong number of arguments or improper option flags,exit()
withStatus::USAGE
. The exit status codes are the same as thosefound insysexits.h.
The Aura.Cli library does not come with an abstract or base command class toextend from, but writing commands for yourself is straightforward. Thefollowing is a standalone command script, but similar logic can be used in aclass. Save it in a file namedhello
and invoke it withphp hello [-v,--verbose] [name]
.
<?phpuseAura\Cli\CliFactory;useAura\Cli\Status;require'/path/to/Aura.Cli/autoload.php';// get the context and stdio objects$cli_factory =newCliFactory;$context =$cli_factory->newContext($GLOBALS);$stdio =$cli_factory->newStdio();// define options and named arguments through getopt$options = ['verbose,v'];$getopt =$context->getopt($options);// do we have a name to say hello to?$name =$getopt->get(1);if (!$name) {// print an error$stdio->errln("Please give a name to say hello to.");exit(Status::USAGE);}// say helloif ($getopt->get('--verbose')) {// verbose output$stdio->outln("Hello{$name}, it's nice to see you!");}else {// plain output$stdio->outln("Hello{$name}!");}// done!exit(Status::SUCCESS);?>
Sometimes it will be useful to provide help output for your commands. With Aura.Cli, theHelp object is separate from any command you may write. It may be manipulated externally or extended.
For example, extend theHelp object and override theinit()
method.
<?phpuseAura\Cli\Help;class MyCommandHelpextends Help{protectedfunctioninit() {$this->setSummary('A single-line summary.');$this->setUsage('<arg1> [<arg2>]');$this->setOptions(['f,foo' =>"The -f/--foo option description.",'bar::' =>"The --bar option description.", ]);$this->setDescr("A multi-line description of the command."); }}?>
Then instantiate the new class and pass itsgetHelp()
output throughStdio:
<?phpuseAura\Cli\CliFactory;useAura\Cli\Context\OptionFactory;$cli_factory =newCliFactory;$stdio =$cli_factory->newStdio();$help =newMyCommandHelp(newOptionFactory);$stdio->outln($help->getHelp('my-command'));?>
We keep the command name itself outside of the help class, because the command name may be mapped differently in different projects.
We pass aGetoptParser to theHelp object so it can parse the option definitions.
We can get the option definitions out of theHelp object using
getOptions()
; this allows us to pass aHelp object into a hypothetical command object and reuse the definitions.
The output will look something like this:
SUMMARY my-command -- A single-line summary.USAGE my-command <arg1> [<arg2>]DESCRIPTION A multi-line description of the command.OPTIONS -f --foo The -f/--foo option description. --bar[=<value>] The --bar option description.
As a side note, the array of options passed tosetOptions()
may contain argument descriptions as well. These are in the format#argname
(to indicate a required argument) and#argname?
(to indicate an optional argument). They may additionally be used as keys, with corresponding description values. Their presence in aGetopt definition array is ignored, but theHelp object will read them and generate output for them automatically.
For example, the following code (notice the lack of asetUsage()
call)...
<?phpuseAura\Cli\CliFactory;useAura\Cli\Context\OptionFactory;useAura\Cli\Help;$cli_factory =newCliFactory;$stdio =$cli_factory->newStdio();$help =newHelp(newOptionFactory);$this->setSummary('A single-line summary.');$help->setOptions(['f,foo' =>"The -f/--foo option description.",'bar::' =>"The --bar option description.",'#arg1' =>"The description for argument 1.",'#arg2?' =>"The description for argument 2.",]);$this->setDescr("A multi-line description of the command.");$stdio->outln($help->getHelp('my-command'));?>
... will generate the following output:
SUMMARY my-command -- A single-line summary.USAGE my-command <arg1> [<arg2>]DESCRIPTION A multi-line description of the command.ARGUMENTS <foo> The description for argument 1. <bar> The description for argument 2.OPTIONS -f --foo The -f/--foo option description. --bar[=<value>] The --bar option description.
On POSIX terminals,<<markup>>
strings will change the displaycharacteristics. Note that these are not HTML tags; they will be convertedinto terminal control codes, and do not get "closed". You can place as manyspace-separated markup codes between the double angle-brackets as you like.
reset reset display to defaultsblack black textred red textgreen green textyellow yellow textblue blue textmagenta magenta (purple) textcyan cyan (light blue) textwhite white textblackbg black backgroundredbg red backgroundgreenbg green backgroundyellowbg yellow backgroundbluebg blue backgroundmagentabg magenta (purple) backgroundcyanbg cyan (light blue) backgroundwhitebg white backgroundbold bold in the current text and background colorsdim dim in the current text and background colorsul underline in the current text and background colorsblink blinking in the current text and background colorsreverse reverse the current text and background colors
For example, to set bold white text on a red background, add<<bold white redbg>>
into your output or error string. Reset back to normal with<<reset>>
.
About
Command-Line Interface tools