2017 © Pedro Peláez
 

library cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

image

aura/cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  • Thursday, February 9, 2017
  • by pmjones
  • Repository
  • 14 Watchers
  • 99 Stars
  • 167,327 Installations
  • PHP
  • 32 Dependents
  • 0 Suggesters
  • 19 Forks
  • 3 Open issues
  • 17 Versions
  • 7 % Grown

The README.md

Aura.Cli

Provides the equivalent of request ( Context ) and response ( Stdio ) objects for the command line interface, including Getopt support, and an independent Help object for describing commands., (*1)

Foreword

Installation

This library requires PHP 7.2 or later; we recommend using the latest available version of PHP as a matter of principle., (*2)

It has no userland dependencies., (*3)

It is installable and autoloadable via Composer as aura/cli., (*4)

Alternatively, download a release or clone this repository, then require or include its autoload.php file., (*5)

Quality

Continuous Integration, (*6)

To run the unit tests at the command line, issue composer install and then composer test at the package root. This requires Composer to be available as composer., (*7)

This library attempts to comply with PSR-1, PSR-2, and PSR-4. If you notice compliance oversights, please send a patch via pull request., (*8)

Community

To ask questions, provide feedback, or otherwise communicate with the Aura community, please join our Google Group, follow @auraphp on Twitter, or chat with us on #auraphp on Freenode., (*9)

Getting Started

Context Discovery

The Context object provides information about the command line environment, including any option flags passed via the command line. (This is the command line equivalent of a web request object.), (*10)

Instantiate a Context object using the CliFactory; pass it a copy of $GLOBALS., (*11)

newContext($GLOBALS);
?>

You can access the $_ENV, $_SERVER, and $argv values with the $env, $server, and $argv property objects, respectively. (Note that these properties are copies of those superglobals as they were at the time of Context instantiation.) You can pass an alternative default value if the related key is missing., (*12)

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');
?>

Getopt Support

The Context object provides support for retrieving command-line options and params, along with positional arguments., (*13)

To retrieve options and arguments parsed from the command-line $argv values, use the getopt() method on the Context object. This will return a GetoptValues object for you to use as as you wish., (*14)

Defining Options and Params

To tell getopt() how to recognize command line options, pass an array of option definitions. The definitions array format is similar to, but not exactly the same as, the one used by the getopt() function in PHP. Instead of defining short flags in a string and long options in 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., (*15)

getopt($options);
?>

N.b.: When we say "required" here, it means "the option, when present, must have a parameter." It does not mean "the option must be present." These are options, after all. If a particular value must be passed, consider using positional arguments instead., (*16)

Use the get() method on the returned GetoptValues object to retrieve the option values. You can provide an alternative default value for when the option is missing., (*17)

<?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;, (*18)

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 end of the option name., (*19)

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, the GetoptValues object retains various errors related to the parsing failures. In these cases, hasErrors() will return true, and you can then review the errors. (The errors are actually Aura\Cli\Exception objects, but they don't get thrown as they occur; this is so that you can deal with or ignore the different kinds of errors as you like.), (*20)

<?php
$getopt = $context->getopt($options);
if ($getopt->hasErrors()) {
    $errors = $getopt->getErrors();
    foreach ($errors as $error) {
        // print error messages to stderr using a Stdio object
        $stdio->errln($error->getMessage());
    }
};
?>

Positional Arguments

To get the positional arguments passed to the command line, use the get() method and the argument position number:, (*21)

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., (*22)

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 immediately after it will be treated as the option value, not as an argument., (*23)

Standard Input/Output Streams

The Stdio object allows you to work with standard input/output streams. (This is the command line equivalent of a web response object.), (*24)

Instantiate a Stdio object using the CliFactory., (*25)

newStdio();
?>

It defaults to using php://stdin, php://stdout, and php://stderr, but you can pass whatever stream names you like as parameters to the newStdio() method., (*26)

The Stdio object methods are ..., (*27)

  • getStdin(), getStdout(), and getStderr() to return the respective Handle objects;, (*28)

  • outln() and out() to print to stdout, with or without a line ending;, (*29)

  • errln() and err() to print to stderr, with or without a line ending;, (*30)

  • inln() and in() to read from stdin until the user hits enter; inln() leaves the trailing line ending in place, whereas in() strips it., (*31)

You can use special formatting markup in the output and error strings to set text color, text weight, background color, and other display characteristics. See the formatter cheat sheet below., (*32)

outln('This is normal text.');

// print to stderr
$stdio->errln('>This is an error in red.');
$stdio->errln('Output will stay red until a formatting change.>');
?>

Exit Codes

This library comes with a Status class that defines constants for exit status codes. You should use these whenever possible. For example, if a command is used with the wrong number of arguments or improper option flags, exit() with Status::USAGE. The exit status codes are the same as those found in sysexits.h., (*33)

Writing Commands

The Aura.Cli library does not come with an abstract or base command class to extend from, but writing commands for yourself is straightforward. The following is a standalone command script, but similar logic can be used in a class. Save it in a file named hello and invoke it with php hello [-v,--verbose] [name]., (*34)

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 hello
if ($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);
?>

Writing Command Help

Sometimes it will be useful to provide help output for your commands. With Aura.Cli, the Help object is separate from any command you may write. It may be manipulated externally or extended., (*35)

For example, extend the Help object and override the init() method., (*36)

setSummary('A single-line summary.');
        $this->setUsage(' []');
        $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 its getHelp() output through Stdio:, (*37)

newStdio();

$help = new MyCommandHelp(new OptionFactory);
$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., (*38)

  • We pass a GetoptParser to the Help object so it can parse the option definitions., (*39)

  • We can get the option definitions out of the Help object using getOptions(); this allows us to pass a Help object into a hypothetical command object and reuse the definitions., (*40)

The output will look something like this:, (*41)

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 to setOptions() 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 a Getopt definition array is ignored, but the Help object will read them and generate output for them automatically., (*42)

For example, the following code (notice the lack of a setUsage() call)..., (*43)

newStdio();

$help = new Help(new OptionFactory);
$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:, (*44)

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.

Formatter Cheat Sheet

On POSIX terminals, <<markup>> strings will change the display characteristics. Note that these are not HTML tags; they will be converted into terminal control codes, and do not get "closed". You can place as many space-separated markup codes between the double angle-brackets as you like., (*45)

reset       reset display to defaults

black       black text
red         red text
green       green text
yellow      yellow text
blue        blue text
magenta     magenta (purple) text
cyan        cyan (light blue) text
white       white text

blackbg     black background
redbg       red background
greenbg     green background
yellowbg    yellow background
bluebg      blue background
magentabg   magenta (purple) background
cyanbg      cyan (light blue) background
whitebg     white background

bold        bold in the current text and background colors
dim         dim in the current text and background colors
ul          underline in the current text and background colors
blink       blinking in the current text and background colors
reverse     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>>., (*46)

The Versions

09/02 2017

2.x-dev

2.9999999.9999999.9999999-dev https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

The Development Requires

command cli command line options getopt stdio

09/02 2017

2.2.0

2.2.0.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

The Development Requires

command cli command line options getopt stdio

03/10 2016

2.1.2

2.1.2.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

The Development Requires

command cli command line options getopt stdio

04/04 2015

1.x-dev

1.9999999.9999999.9999999-dev http://auraphp.github.com/Aura.Cli

The Aura CLI package provides a system for creating and executing CLI command objects. It includes facilities for parsing command-line options and handling standard input/output.

  Sources   Download

BSD-2-Clause

The Requires

 

command cli command line options getopt

27/03 2015

2.1.1

2.1.1.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

The Development Requires

command cli command line options getopt stdio

26/03 2015

2.1.0

2.1.0.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

command cli command line options getopt stdio

16/03 2015

2.0.4

2.0.4.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

command cli command line options getopt stdio

19/01 2015

2.0.3

2.0.3.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

command cli command line options getopt stdio

19/01 2015

2.0.2

2.0.2.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

command cli command line options getopt stdio

07/11 2014

2.0.1

2.0.1.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

command cli command line options getopt stdio

30/08 2014

2.0.0

2.0.0.0 https://github.com/auraphp/Aura.Cli

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

command cli command line options getopt stdio

31/05 2014

1.1.2

1.1.2.0 http://auraphp.com/Aura.Cli

The Aura CLI package provides a system for creating and executing CLI command objects. It includes facilities for parsing command-line(console) options and handling standard input/output.

  Sources   Download

BSD-2-Clause

The Requires

 

command console cli command line options getopt

13/01 2014

2.0.0-beta1

2.0.0.0-beta1 https://github.com/auraphp/Aura.Cli/releases

Provides the equivalent of request (Context) and response (Stdio) classes for a command line environment, including Getopt support.

  Sources   Download

BSD-2-Clause

The Requires

  • php >=5.3.0

 

command cli command line options getopt stdio

09/09 2013

1.1.1

1.1.1.0 http://auraphp.com/Aura.Cli

The Aura CLI package provides a system for creating and executing CLI command objects. It includes facilities for parsing command-line(console) options and handling standard input/output.

  Sources   Download

BSD-2-Clause

The Requires

 

command console cli command line options getopt

12/04 2013

1.1.0

1.1.0.0 http://auraphp.github.com/Aura.Cli

The Aura CLI package provides a system for creating and executing CLI command objects. It includes facilities for parsing command-line(console) options and handling standard input/output.

  Sources   Download

BSD-2-Clause

The Requires

 

command console cli command line options getopt

28/11 2012

1.0.1

1.0.1.0 http://auraphp.github.com/Aura.Cli

The Aura CLI package provides a system for creating and executing CLI command objects. It includes facilities for parsing command-line(console) options and handling standard input/output.

  Sources   Download

BSD

The Requires

 

command console cli command line options getopt

27/11 2012

1.0.0

1.0.0.0 http://auraphp.github.com/Aura.Cli

The Aura CLI package provides a system for creating and executing CLI command objects. It includes facilities for parsing command-line(console) options and handling standard input/output.

  Sources   Download

BSD

The Requires

 

command console cli command line options getopt