Git Product home page Git Product logo

docopt.php's Introduction

docopt creates beautiful command-line interfaces

https://travis-ci.org/docopt/docopt.php.svg?branch=master

This is a straight PHP transliteration of Vladimir Keleshev's brilliant docopt Python library. There are a few artefacts in the code as a result that may seem inefficient and non-idiomatic to PHP, this has been done to make integrating changes more efficient.

As a result, unless a bug is present only in the PHP version, pull requests are unlikely to be accepted unless they are themselves direct transliterations of bugfixes in the Python version.

This port has been marked version 1.0. It is based on the Python version at commit a093f938b7f26564434f3c15a1dcc39e017ad638 (labelled 0.6.2).

It has been quite stable for a long time and has barely been changed. The Python version receives only occasional bugfixes and keeping the version numbers pinned has been more trouble than it has been worth.

There are also some major backward compatibility breaks. Rather than dwell in 0.x semver hell, the PHP port will liberally bump major numbers henceforth when BC breaks regardless of the reason.

  • The PHP API has changed slightly. Docopt\docopt() has been renamed to Docopt::handle() to fix autoloader support. See issue #3.
  • Docopt.py also has a significant BC break. Existing users should read the information below about Usage and Option sections. See issue 102 for more info.

Please see the Python version's README for details of any new and breaking changes that are not specific to the PHP version.

There is also at least one significant known issue with the upstream Python version. Due to the porting strategy used for the PHP version, it inherits the bug surface of the Python version (and if it doesn't, that's actually a bug!):


Isn't it awesome how optparse and argparse generate help messages based on your code?!

Hell no! You know what's awesome? It's when the option parser is generated based on the beautiful help message that you write yourself! This way you don't need to write this stupid repeatable parser-code, and instead can write only the help message--the way you want it.

docopt helps you create most beautiful command-line interfaces easily:

<?php
$doc = <<<DOC
Naval Fate.

Usage:
  naval_fate.php ship new <name>...
  naval_fate.php ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.php ship shoot <x> <y>
  naval_fate.php mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.php (-h | --help)
  naval_fate.php --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

DOC;

require('path/to/src/docopt.php');
$args = Docopt::handle($doc, array('version'=>'Naval Fate 2.0'));
foreach ($args as $k=>$v)
    echo $k.': '.json_encode($v).PHP_EOL;

Beat that! The option parser is generated based on the docstring above that is passed to docopt function. docopt parses the usage pattern ("Usage: ...") and option descriptions (lines starting with dash "-") and ensures that the program invocation matches the usage pattern; it parses options, arguments and commands based on that. The basic idea is that a good help message has all necessary information in it to make a parser.

Installation

Install docopt.php using Composer:

composer require docopt/docopt

Alternatively, you can just drop docopt.php file into your project--it is self-contained. Get source on github.

docopt.php is tested with PHP 7; it should still work with PHP 5.3+ but this support will become increasingly fragile and will at some point cease to be supported at all. You should update to 7 as soon as you can.

Testing

Configure your repo for running tests:

./dev-setup

You can run unit tests with the following command:

php test.php

This will run the Python language agnostic tests as well as the PHP docopt tests.

API

<?php
require('/path/to/src/docopt.php');

// short form, simple API
$args = Docopt::handle($doc);

// short form (5.4 or better)
$args = (new \Docopt\Handler)->handle($sdoc);

// long form, simple API (equivalent to short)
$params = array(
    'argv'=>array_slice($_SERVER['argv'], 1),
    'help'=>true,
    'version'=>null,
    'optionsFirst'=>false,
);
$args = Docopt::handle($doc, $params);

// long form, full API
$handler = new \Docopt\Handler(array(
    'help'=>true,
    'optionsFirst'=>false,
));
$handler->handle($doc, $argv);

Docopt::handle() takes 1 required and 1 optional argument:

  • doc is a string that contains a help message that will be parsed to create the option parser. The simple rules of how to write such a help message are given in next sections. Here is a quick example of such a string:
<?php
$doc = <<<DOC
Usage: my_program.php [-hso FILE] [--quiet | --verbose] [INPUT ...]

Options:
  -h --help    show this
  -s --sorted  sorted output
  -o FILE      specify output file [default: ./test.txt]
  --quiet      print less text
  --verbose    print more text

DOC;
  • params is an optional array of additional data to influence docopt. The following keys are supported:

    • argv is an optional argument vector; by default docopt uses the argument vector passed to your program ($_SERVER['argv']). Alternatively you can supply a list of strings like array('--verbose', '-o', 'hai.txt').

    • help, by default true, specifies whether the parser should

      automatically print the help message (supplied as doc) and terminate, in case -h or --help option is encountered (options should exist in usage pattern, more on that below). If you want to handle -h or --help options manually (as other options), set help to false.

    • version, by default null, is an optional argument that specifies the version of your program. If supplied, then, (assuming --version option is mentioned in usage pattern) when parser encounters the --version option, it will print the supplied version and terminate. version could be any printable object, but most likely a string, e.g. "2.1.0rc1".

      Note, when docopt is set to automatically handle -h, --help and --version options, you still need to mention them in usage pattern for this to work. Also, for your users to know about them.

    • optionsFirst, by default false. If set to true will disallow mixing options and positional argument. I.e. after first positional argument, all arguments will be interpreted as positional even if the look like options. This can be used for strict compatibility with POSIX, or if you want to dispatch your arguments to other programs.

Docopt\Handler->handle() takes one required argument:

  • doc is a string that contains a help message that will be parsed to create the option parser. The simple rules of how to write such a help message are given in next sections. Here is a quick example of such a string:
<?php
$doc = <<<DOC
Usage: my_program.php [-hso FILE] [--quiet | --verbose] [INPUT ...]

-h --help    show this
-s --sorted  sorted output
-o FILE      specify output file [default: ./test.txt]
--quiet      print less text
--verbose    print more text

DOC;

The return value of handle() is a simple associative array with options, arguments and commands as keys, spelled exactly like in your help message. Long versions of options are given priority. For example, if you invoke the top example as:

naval_fate.php ship Guardian move 100 150 --speed=15

the return dictionary will be:

<?php
array(
  '--drifting'=>false,         'mine'=>false,
  '--help'=>false,             'move'=>true,
  '--moored'=>false,           'new'=>false,
  '--speed'=>'15',             'remove'=>false,
  '--version'=>false,          'set'=>false,
  '<name>'=>array('Guardian'), 'ship'=>true,
  '<x>'=>'100',                'shoot'=>false,
  '<y>'=>'150'
);

Help message format

Help message consists of 2 sections:

  • Usage section, starting with Usage: e.g.:

    Usage: my_program.php [-hso FILE] [--quiet | --verbose] [INPUT ...]
    
  • Option section, starting with Options: e.g.:

    Options:
      -h --help    show this
      -s --sorted  sorted output
      -o FILE      specify output file [default: ./test.txt]
      --quiet      print less text
      --verbose    print more text
    

Sections consist of a header and a body. The section body can begin on the same line as the header, but if it spans multiple lines, it must be indented. A section is terminated by an empty line or a string with no indentation:

Section header: Section body

Section header:
  Section body, which is indented at least
  one space or tab from the section header

Section header: Section body, which is indented at least
  one space or tab from the section header

Usage section format

Minimum example:

Usage: my_program.php

The first word after usage: is interpreted as your program's name. You can specify your program's name several times to signify several exclusive patterns:

Usage: my_program.php FILE
       my_program.php COUNT FILE

Each pattern can consist of the following elements:

  • <arguments>, ARGUMENTS. Arguments are specified as either upper-case words, e.g. my_program.php CONTENT-PATH or words surrounded by angular brackets: my_program.php <content-path>.
  • --options. Options are words started with dash (-), e.g. --output, -o. You can "stack" several of one-letter options, e.g. -oiv which will be the same as -o -i -v. The options can have arguments, e.g. --input=FILE or -i FILE or even -iFILE. However it is important that you specify option descriptions if you want your option to have an argument, a default value, or specify synonymous short/long versions of option (see next section on option descriptions).
  • commands are words that do not follow the described above conventions of --options or <arguments> or ARGUMENTS, plus two special commands: dash "-" and double dash "--" (see below).

Use the following constructs to specify patterns:

  • [ ] (brackets) optional elements. e.g.: my_program.php [-hvqo FILE]
  • ( ) (parens) required elements. All elements that are not put in [ ] are also required, e.g.: my_program.php --path=<path> <file>... is the same as my_program.php (--path=<path> <file>...). (Note, "required options" might be not a good idea for your users).
  • | (pipe) mutually exclusive elements. Group them using ( ) if one of the mutually exclusive elements is required: my_program.php (--clockwise | --counter-clockwise) TIME. Group them using [ ] if none of the mutually-exclusive elements are required: my_program.php [--left | --right].
  • ... (ellipsis) one or more elements. To specify that arbitrary number of repeating elements could be accepted, use ellipsis (...), e.g. my_program.php FILE ... means one or more FILE-s are accepted. If you want to accept zero or more elements, use brackets, e.g.: my_program.php [FILE ...]. Ellipsis works as a unary operator on the expression to the left.
  • [options] (case sensitive) shortcut for any options. You can use it if you want to specify that the usage pattern could be provided with any options defined below in the option-descriptions and do not want to enumerate them all in usage-pattern. "[--]". Double dash "--" is used by convention to separate positional arguments that can be mistaken for options. In order to support this convention add "[--]" to you usage patterns. "[-]". Single dash "-" is used by convention to signify that stdin is used instead of a file. To support this add "[-]" to you usage patterns. "-" act as a normal command.

If your pattern allows to match argument-less option (a flag) several times:

Usage: my_program.php [-v | -vv | -vvv]

then number of occurrences of the option will be counted. I.e. args['-v'] will be 2 if program was invoked as my_program -vv. Same works for commands.

If your usage patterns allows to match same-named option with argument or positional argument several times, the matched arguments will be collected into a list:

Usage: my_program.php <file> <file> --path=<path>...

I.e. invoked with my_program.php file1 file2 --path=./here --path=./there the returned dict will contain args['<file>'] == ['file1', 'file2'] and args['--path'] == ['./here', './there'].

Options section format

The Option section is an optional section that contains a list of options that can document or supplement your usage pattern.

It is necessary to list option descriptions in order to specify:

  • synonymous short and long options,
  • if an option has an argument,
  • if option's argument has a default value.

The rules are as follows:

  • Every line in the options section body that starts with one or more horizontal whitespace characters, followed by - or -- is treated as an option description, e.g.:

    Options:
      --verbose   # GOOD
      -o FILE     # GOOD
    Other: --bad  # BAD, line does not start with dash "-"
    
  • To specify that option has an argument, put a word describing that argument after space (or equals "=" sign) as shown below. Follow either <angular-brackets> or UPPER-CASE convention for options' arguments. You can use comma if you want to separate options. In the example below, both lines are valid, however you are recommended to stick to a single style.:

    -o FILE --output=FILE       # without comma, with "=" sign
    -i <file>, --input <file>   # with comma, wihtout "=" sign
    
  • Use two spaces to separate options with their informal description:

    --verbose More text.   # BAD, will be treated as if verbose option had
                           # an argument "More", so use 2 spaces instead
    -q        Quit.        # GOOD
    -o FILE   Output file. # GOOD
    --stdout  Use stdout.  # GOOD, 2 spaces
    
  • If you want to set a default value for an option with an argument, put it into the option-description, in form [default: <my-default-value>]:

    --coefficient=K  The K coefficient [default: 2.95]
    --output=FILE    Output file [default: test.txt]
    --directory=DIR  Some directory [default: ./]
    
  • If the option is not repeatable, the value inside [default: ...] will be interpreted as string. If it is repeatable, it will be splited into a list on whitespace:

    Usage: my_program.php [--repeatable=<arg> --repeatable=<arg>]
                          [--another-repeatable=<arg>]...
                          [--not-repeatable=<arg>]
    
    # will be ['./here', './there']
    --repeatable=<arg>          [default: ./here ./there]
    
    # will be ['./here']
    --another-repeatable=<arg>  [default: ./here]
    
    # will be './here ./there', because it is not repeatable
    --not-repeatable=<arg>      [default: ./here ./there]
    

Examples

We have an extensive list of examples which cover every aspect of functionality of docopt. Try them out, read the source if in doubt.

Subparsers, multi-level help and huge applications (like git)

If you want to split your usage-pattern into several, implement multi-level help (with separate help-screen for each subcommand), want to interface with existing scripts that don't use docopt, or you're building the next "git", you will need the new options_first parameter (described in API section above). To get you started quickly we implemented a subset of git command-line interface as an example: examples/git

Data validation

docopt does one thing and does it well: it implements your command-line interface. However it does not validate the input data. You should supplement docopt with a validation library when your validation requirements extend beyond whether input is optional or required.

Development

See the Python version's page for more info on developing.

docopt.php's People

Contributors

jkingweb avatar johnstevenson avatar maltsev avatar marcioalmada avatar sctice-ifixit avatar shabbyrobe avatar svenrtbg avatar yriveiro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docopt.php's Issues

Options section is more rigidly defined than other docopt implementations

Here is a test program that works:

<?php
require 'vendor/autoload.php';

$doc = <<<DOC
Usage:
    test [-t <ttt>]... [-x <xxx>] [<yyy>]...

Options:
    -t <arg>   Y
    -x <xxx>   X

DOC;

$args = (new \Docopt\Handler)->handle($doc);
print_r($args);

Here's the output:

$ php test.php -t a -t b -x xxx 1 2 3 4
Docopt\Response Object
(
    [status] => 0
    [output] =>
    [args] => Array
        (
            [-t] => Array
                (
                    [0] => a
                    [1] => b
                )

            [-x] => xxx
            [<yyy>] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => 4
                )
        )
)

But if I add a blank line in the options list then it doesn't work:

Options:
    -t <arg>   Y

    -x <xxx>   X

The output becomes this: (note the -x has reverted to a flag option and its parameter goes into <xxx> instead)

$ php test.php -t a -t b -x xxx 1 2 3 4
Docopt\Response Object
(
    [status] => 0
    [output] =>
    [args] => Array
        (
            [-t] => Array
                (
                    [0] => a
                    [1] => b
                )
            [-x] => 1
            [<xxx>] => xxx
            [<yyy>] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => 4
                )
        )
)

This also doesn't work:

Options in common:
    -t <arg>   Y
    -x <xxx>   X

The output for this case: (neither option acts like it's declared)

php test.php -t a -t b -x xxx 1 2 3 4
Docopt\Response Object
(
    [status] => 0
    [output] =>
    [args] => Array
        (
            [-t] => 2
            [<ttt>] => Array
                (
                    [0] => a
                    [1] => b
                    [2] => xxx
                    [3] => 1
                    [4] => 2
                    [5] => 3
                    [6] => 4
                )

            [-x] => 1
            [<xxx>] =>
            [<yyy>] => Array
                (
                )
        )
)

Both of those cases work correctly in the reference implementation

PHP API issues with ExitExceptions

When docopt.php encounters a problem with input, it raises an ExitException. This is necessary to maintain parity with the python version, upon which this will remain as derived as possible.

Unfortunately, there is no analog for the python SystemExit exception, as demonstrated here:

# this will show a full traceback
php -r "throw new Exception('traceback');"

# as will this
python -c "raise RuntimeError('traceback')"

# this one shows no traceback. there is no equivalent in PHP
python -c "raise SystemExit('no traceback')"

Currently, docopt.php catches the ExitException in the docopt method, echoes the message and returns false.

This has the following similarities to the python version:

  • It allows the code calling docopt to take responsibility for exiting
  • It does not print a full traceback when the calling code does not explicitly catch the ExitException

It has the following differences:

  • docopt.php will not exit when the calling code does not check the return condition
  • In order to suppress, capture or otherwise modify the error message output, output buffering must be used. In python, you can just use a catch block.

And the following problems:

  • The proper exit status cannot be determined - if you pass --help or --version, the program should exit with status 0, but input errors should exit with status 1.

Unfortunately, I can't see a simple way to enure the behaviour is the same as the python version without slightly changing the API.

While I mull this over, the API will be a slightly moving target.

Handle quoted multi-word argument & option values

Not sure if I'm "doing it wrong", but I am having the same issue as reported in other languages, where Docopt does not treat quote delimited strings as one parameter.

As demonstrated here

Also reported in:

docopt/docopt#207
docopt/try.docopt.org#3
docopt/docopt.R#4

Until this is fixed I suggest putting a warning or removing examples like git commit where it's typical for a command like git commit -m "To have multiple words inside a quote".

In the mean time I have created a workaround that isn't perfect but has so far worked okay for me. I pre-process and post-process the input/output.

The pre-process function replaces any quoted strings with a variable so that git commit -m "To have multiple words inside a quote" becomes git commit -m $_v12345abcdef.

function pre_processor(string $string) {
	$variables = [];

	$new_string = preg_replace_callback('/["\'](.*?(?<!\\\\))["\']/m', function($match) use (&$variables) {
		// Results in a var name like 'v12345abcdef'
		$varName = 'v' . hash('fnv164', $match[0]);
		$variables[$varName] = $match[1];
		// Results in a placeholder like $_v12345abcdef
		return '$_' . $varName;
	},$string);

	return ['string' => $new_string, 'variables' => $variables];
}

The $new_string is the passed to Docopt handler in place of the normal CLI input args. The result of which is then sent to a post processing function to fill the variables back in

function post_processor(array $args, array $variables) {
	foreach ($args as &$arg){
		// find any thing that matches like $_v12345abcdef and replace it with the actual value
		$arg = preg_replace_callback('/\$_(v[a-f0-9]{16})\b/', function($match) use ($variables) {
			return str_replace($match[0], isset($variables[$match[1]]) ? $variables[$match[1]] : $match[0], $match[0]);
		}, $arg);
	}
	
	return $args;
}

For example, you might have something that looks like this:

function handle($string) {
	list('string' => $processed_string, 'variables' => $variables) = pre_processor($string);
	$result = $DOCOPT->handle($doc, $processed_string);	
	$real_args = post_processor($result->args, $variables);
	return $real_args;
}

I haven't looked through the Docopt.php code, but this might be something that could be done as part of the existing handle() function.

How can I represent yes or no value?

I just wondering ...

If I have an option with yes or no value or say enum values, how can I represent it?

[--option=(yes|no)] or [--option=(yes|no|maybe)] , is it a right representation based on docopt spec?

Mark

No installable candidates for 3 years - how so?

So I cannot install the latest 1.0.3 version because of some HHVM.

I'm a PHP developer with 15+ years of exp and honeslty - I don't know what is HHVM and don't have any desire to know. Don't take me wrong, usually I have a decent setup on my machines and they've been running Linx Debian and then Ubuntu for 20 years. But now I cannot install some PHP package because of some HHVM which I never used. I just don't get what can be so wrong about PHP that one has to install some virtual machine to run it?

From what I see the version 1.0.3 was released back in 2017-03-28 08:43 UTC, i.e. almost 3 years ago. The funny thing - I've been using DocOpt for about a year and haven't got any problems with it. This is because I was and am still using its dev version. It's just that now I decieded to realease my product and discovered that I CANNOT do this: I have to use stable versions but you do not provide any working one.

Please give us something. DocOpt rocks. And doesn't need some weird HHVMs to run.

Hangs forever with HHVM

I tried to run docopt with HHVM and it simply hangs forever. All runs fine with Zend PHP.

Allow args beginning with "-"

It would be great if you could allow ambiguous arguments after a --. For example:

bin/count-up-to --debug -- -1

Here the -1 is not interpreted as an option, but instead is an argument.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.