PK ?VIxR_ _
composer.locknu W+A {
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "7345ae9c1a98de94c4d43629d7770d62",
"packages": [],
"packages-dev": [
{
"name": "phpunit/php-code-coverage",
"version": "2.0.11",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "53603b3c995f5aab6b59c8e08c3a663d2cc810b7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/53603b3c995f5aab6b59c8e08c3a663d2cc810b7",
"reference": "53603b3c995f5aab6b59c8e08c3a663d2cc810b7",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"phpunit/php-file-iterator": "~1.3",
"phpunit/php-text-template": "~1.2",
"phpunit/php-token-stream": "~1.3",
"sebastian/environment": "~1.0",
"sebastian/version": "~1.0"
},
"require-dev": {
"ext-xdebug": ">=2.1.4",
"phpunit/phpunit": "~4.1"
},
"suggest": {
"ext-dom": "*",
"ext-xdebug": ">=2.2.1",
"ext-xmlwriter": "*"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.",
"homepage": "https://github.com/sebastianbergmann/php-code-coverage",
"keywords": [
"coverage",
"testing",
"xunit"
],
"time": "2014-08-31 06:33:04"
},
{
"name": "phpunit/php-file-iterator",
"version": "1.3.4",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-file-iterator.git",
"reference": "acd690379117b042d1c8af1fafd61bde001bf6bb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/acd690379117b042d1c8af1fafd61bde001bf6bb",
"reference": "acd690379117b042d1c8af1fafd61bde001bf6bb",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"autoload": {
"classmap": [
"File/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "FilterIterator implementation that filters files based on a list of suffixes.",
"homepage": "https://github.com/sebastianbergmann/php-file-iterator/",
"keywords": [
"filesystem",
"iterator"
],
"time": "2013-10-10 15:34:57"
},
{
"name": "phpunit/php-text-template",
"version": "1.2.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-text-template.git",
"reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/206dfefc0ffe9cebf65c413e3d0e809c82fbf00a",
"reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"autoload": {
"classmap": [
"Text/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Simple template engine.",
"homepage": "https://github.com/sebastianbergmann/php-text-template/",
"keywords": [
"template"
],
"time": "2014-01-30 17:20:04"
},
{
"name": "phpunit/php-timer",
"version": "1.0.5",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-timer.git",
"reference": "19689d4354b295ee3d8c54b4f42c3efb69cbc17c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/19689d4354b295ee3d8c54b4f42c3efb69cbc17c",
"reference": "19689d4354b295ee3d8c54b4f42c3efb69cbc17c",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"autoload": {
"classmap": [
"PHP/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Utility class for timing",
"homepage": "https://github.com/sebastianbergmann/php-timer/",
"keywords": [
"timer"
],
"time": "2013-08-02 07:42:54"
},
{
"name": "phpunit/php-token-stream",
"version": "1.3.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-token-stream.git",
"reference": "f8d5d08c56de5cfd592b3340424a81733259a876"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/f8d5d08c56de5cfd592b3340424a81733259a876",
"reference": "f8d5d08c56de5cfd592b3340424a81733259a876",
"shasum": ""
},
"require": {
"ext-tokenizer": "*",
"php": ">=5.3.3"
},
"require-dev": {
"phpunit/phpunit": "~4.2"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.3-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de"
}
],
"description": "Wrapper around PHP's tokenizer extension.",
"homepage": "https://github.com/sebastianbergmann/php-token-stream/",
"keywords": [
"tokenizer"
],
"time": "2014-08-31 06:12:13"
},
{
"name": "phpunit/phpunit",
"version": "4.1.6",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "241116219bb7e3b8111a36ffd8f37546888738d6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/241116219bb7e3b8111a36ffd8f37546888738d6",
"reference": "241116219bb7e3b8111a36ffd8f37546888738d6",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-json": "*",
"ext-pcre": "*",
"ext-reflection": "*",
"ext-spl": "*",
"php": ">=5.3.3",
"phpunit/php-code-coverage": "~2.0",
"phpunit/php-file-iterator": "~1.3.1",
"phpunit/php-text-template": "~1.2",
"phpunit/php-timer": "~1.0.2",
"phpunit/phpunit-mock-objects": "2.1.5",
"sebastian/comparator": "~1.0",
"sebastian/diff": "~1.1",
"sebastian/environment": "~1.0",
"sebastian/exporter": "~1.0",
"sebastian/version": "~1.0",
"symfony/yaml": "~2.0"
},
"suggest": {
"phpunit/php-invoker": "~1.1"
},
"bin": [
"phpunit"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "4.1.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
"",
"../../symfony/yaml/"
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
}
],
"description": "The PHP Unit Testing framework.",
"homepage": "http://www.phpunit.de/",
"keywords": [
"phpunit",
"testing",
"xunit"
],
"time": "2014-08-17 08:07:02"
},
{
"name": "phpunit/phpunit-mock-objects",
"version": "2.1.5",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git",
"reference": "7878b9c41edb3afab92b85edf5f0981014a2713a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/7878b9c41edb3afab92b85edf5f0981014a2713a",
"reference": "7878b9c41edb3afab92b85edf5f0981014a2713a",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"phpunit/php-text-template": "~1.2"
},
"require-dev": {
"phpunit/phpunit": "~4.1"
},
"suggest": {
"ext-soap": "*"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.1.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Mock Object library for PHPUnit",
"homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/",
"keywords": [
"mock",
"xunit"
],
"time": "2014-06-12 07:22:15"
},
{
"name": "sebastian/comparator",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/comparator.git",
"reference": "f7069ee51fa9fb6c038e16a9d0e3439f5449dcf2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/f7069ee51fa9fb6c038e16a9d0e3439f5449dcf2",
"reference": "f7069ee51fa9fb6c038e16a9d0e3439f5449dcf2",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"sebastian/diff": "~1.1",
"sebastian/exporter": "~1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
},
{
"name": "Jeff Welch",
"email": "whatthejeff@gmail.com"
},
{
"name": "Volker Dusch",
"email": "github@wallbash.com"
},
{
"name": "Bernhard Schussek",
"email": "bschussek@2bepublished.at"
}
],
"description": "Provides the functionality to compare PHP values for equality",
"homepage": "http://www.github.com/sebastianbergmann/comparator",
"keywords": [
"comparator",
"compare",
"equality"
],
"time": "2014-05-02 07:05:58"
},
{
"name": "sebastian/diff",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/diff.git",
"reference": "1e091702a5a38e6b4c1ba9ca816e3dd343df2e2d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/1e091702a5a38e6b4c1ba9ca816e3dd343df2e2d",
"reference": "1e091702a5a38e6b4c1ba9ca816e3dd343df2e2d",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
},
{
"name": "Kore Nordmann",
"email": "mail@kore-nordmann.de"
}
],
"description": "Diff implementation",
"homepage": "http://www.github.com/sebastianbergmann/diff",
"keywords": [
"diff"
],
"time": "2013-08-03 16:46:33"
},
{
"name": "sebastian/environment",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/environment.git",
"reference": "79517609ec01139cd7e9fded0dd7ce08c952ef6a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/79517609ec01139cd7e9fded0dd7ce08c952ef6a",
"reference": "79517609ec01139cd7e9fded0dd7ce08c952ef6a",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phpunit/phpunit": "4.0.*@dev"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
}
],
"description": "Provides functionality to handle HHVM/PHP environments",
"homepage": "http://www.github.com/sebastianbergmann/environment",
"keywords": [
"Xdebug",
"environment",
"hhvm"
],
"time": "2014-02-18 16:17:19"
},
{
"name": "sebastian/exporter",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/exporter.git",
"reference": "1f9a98e6f5dfe0524cb8c6166f7c82f3e9ae1529"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/1f9a98e6f5dfe0524cb8c6166f7c82f3e9ae1529",
"reference": "1f9a98e6f5dfe0524cb8c6166f7c82f3e9ae1529",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phpunit/phpunit": "4.0.*@dev"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
},
{
"name": "Jeff Welch",
"email": "whatthejeff@gmail.com"
},
{
"name": "Volker Dusch",
"email": "github@wallbash.com"
},
{
"name": "Adam Harvey",
"email": "aharvey@php.net",
"role": "Lead"
},
{
"name": "Bernhard Schussek",
"email": "bschussek@2bepublished.at"
}
],
"description": "Provides the functionality to export PHP variables for visualization",
"homepage": "http://www.github.com/sebastianbergmann/exporter",
"keywords": [
"export",
"exporter"
],
"time": "2014-02-16 08:26:31"
},
{
"name": "sebastian/version",
"version": "1.0.3",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/version.git",
"reference": "b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/version/zipball/b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43",
"reference": "b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43",
"shasum": ""
},
"type": "library",
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
}
],
"description": "Library that helps with managing the version number of Git-hosted PHP projects",
"homepage": "https://github.com/sebastianbergmann/version",
"time": "2014-03-07 15:35:33"
},
{
"name": "symfony/yaml",
"version": "v2.5.4",
"target-dir": "Symfony/Component/Yaml",
"source": {
"type": "git",
"url": "https://github.com/symfony/Yaml.git",
"reference": "01a7695bcfb013d0a15c6757e15aae120342986f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/Yaml/zipball/01a7695bcfb013d0a15c6757e15aae120342986f",
"reference": "01a7695bcfb013d0a15c6757e15aae120342986f",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.5-dev"
}
},
"autoload": {
"psr-0": {
"Symfony\\Component\\Yaml\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
},
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
}
],
"description": "Symfony Yaml Component",
"homepage": "http://symfony.com",
"time": "2014-08-31 03:22:04"
}
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"platform": {
"php": ">=5.3.0"
},
"platform-dev": []
}
PK ?VYKF? ? dev-setupnu W+A #!/bin/bash
git submodule update --init
composer install --dev
PK ?VdGE E
README.rstnu W+A ``docopt`` creates *beautiful* command-line interfaces
======================================================================
.. image:: 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.0**. It is based on the Python version at
commit `3e0b80a32c8478c076171e0cffcf754141a9950d
`_
(labelled **0.6.1**).
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.
-----
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*:
.. code:: php
...
naval_fate.php ship move [--speed=]
naval_fate.php ship shoot
naval_fate.php mine (set|remove) [--moored | --drifting]
naval_fate.php (-h | --help)
naval_fate.php --version
Options:
-h --help Show this screen.
--version Show version.
--speed= 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
======================================================================
``docopt.php`` is available on `Packagist `_.
Create a ``composer.json`` file for your project
.. code-block:: javascript
{
"require": {
"docopt/docopt": "1.0.0"
}
}
Install using composer::
php composer.phar install
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 5.4 and PHP 5.3.
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
======================================================================
.. code:: php
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:
.. code:: php
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:
.. code:: php
false, 'mine'=>false,
'--help'=>false, 'move'=>true,
'--moored'=>false, 'new'=>true,
'--speed'=>'15', 'remove'=>true,
'--version'=>false, 'set'=>true,
''=>array('Guardian'), 'ship'=>true,
''=>'100', 'shoot'=>false,
''=>'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 are specified as either
upper-case words, e.g. ``my_program.php CONTENT-PATH`` or words
surrounded by angular brackets: ``my_program.php ``.
- **--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 ```` 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= ...`` is the same as ``my_program.php
(--path= ...)``. (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 --path=...
I.e. invoked with ``my_program.php file1 file2 --path=./here
--path=./there`` the returned dict will contain ``args[''] ==
['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 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 , --input # 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:
]``::
--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= --repeatable=]
[--another-repeatable=]...
[--not-repeatable=]
# will be ['./here', './there']
--repeatable= [default: ./here ./there]
# will be ['./here']
--another-repeatable= [default: ./here]
# will be './here ./there', because it is not repeatable
--not-repeatable= [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.
PK ?V? .travis.ymlnu W+A language: php
before_install:
- git submodule update --init
- composer install
php:
- "hhvm"
- "nightly"
- "5.6"
- "5.5"
- "5.4"
- "5.3"
branches:
only:
- master
- develop
script: php test.php
PK ?V\E LICENSE-MITnu W+A Copyright (c) 2012 Vladimir Keleshev,
Blake Williams,
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PK ?V]H H .gitmodulesnu W+A [submodule "py"]
path = py
url = https://github.com/docopt/docopt.git
PK ?VIJr r
composer.jsonnu W+A {
"name": "docopt/docopt",
"type": "library",
"description": "Port of Python's docopt for PHP 5.3",
"version": "1.0.0",
"keywords": ["cli","docs"],
"homepage": "http://github.com/docopt/docopt.php",
"license": "MIT",
"authors": [
{
"name": "Blake Williams",
"email": "code@shabbyrobe.org",
"homepage": "http://docopt.org/",
"role": "Developer"
}
],
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "4.1.*"
},
"autoload": {
"classmap": ["src/docopt.php"]
}
}
PK ?V,
! test/lib/LanguageAgnosticTest.phpnu W+A addTest(new static($tName, $doc, $prog, $argv, $expect));
$idx++;
}
}
return $suite;
}
public function __construct($name, $doc, $prog, $argv, $expect)
{
$this->doc = $doc;
$this->name = $name;
$this->prog = $prog;
$this->argv = $argv;
if ($expect == "user-error")
$expect = array('user-error');
$this->expect = $expect;
}
public function run(\PHPUnit_Framework_TestResult $result=null)
{
if (!$result)
$result = new \PHPUnit_Framework_TestResult();
$opt = null;
\PHP_Timer::start();
$result->startTest($this);
try {
$opt = \Docopt::handle($this->doc, array('argv'=>$this->argv, 'exit'=>false));
}
catch (\Exception $ex) {
// gulp
}
$found = null;
if ($opt) {
if (!$opt->success) {
$found = array('user-error');
}
elseif (empty($opt->args)) {
$found = array();
}
else {
$found = $opt->args;
}
}
$time = \PHP_Timer::stop();
try {
\PHPUnit_Framework_Assert::assertEquals($this->expect, $found);
}
catch (\PHPUnit_Framework_AssertionFailedError $e) {
$result->addFailure($this, $e, $time);
}
$result->endTest($this, $time);
return $result;
}
public function count()
{
return 1;
}
public function toString()
{
return __CLASS__.'::'.$this->name.' - "'.$this->prog.($this->argv ? ' '.$this->argv : '').'"';
}
}
PK ?VSgn n test/lib/TestCase.phpnu W+A false, 'help'=>false), $extra);
$handler = new \Docopt\Handler($extra);
return call_user_func(array($handler, 'handle'), $usage, $args);
}
}
PK ?VV test/lib/PythonPortedTest.phpnu W+A assertEquals($required->flat(),
array(new Argument('N'), new Option('-a'), new Argument('M'))
);
}
function testOption()
{
$this->assertEquals(Option::parse('-h'), new Option('-h'));
$this->assertEquals(Option::parse('--help'), new Option(null, '--help'));
$this->assertEquals(Option::parse('-h --help'), new Option('-h', '--help'));
$this->assertEquals(Option::parse('-h, --help'), new Option('-h', '--help'));
$this->assertEquals(Option::parse('-h TOPIC'), new Option('-h', null, 1));
$this->assertEquals(Option::parse('--help TOPIC'), new Option(null, '--help', 1));
$this->assertEquals(Option::parse('-h TOPIC --help TOPIC'), new Option('-h', '--help', 1));
$this->assertEquals(Option::parse('-h TOPIC, --help TOPIC'), new Option('-h', '--help', 1));
$this->assertEquals(Option::parse('-h TOPIC, --help=TOPIC'), new Option('-h', '--help', 1));
$this->assertEquals(Option::parse('-h Description...'), new Option('-h', null));
$this->assertEquals(Option::parse('-h --help Description...'), new Option('-h', '--help'));
$this->assertEquals(Option::parse('-h TOPIC Description...'), new Option('-h', null, 1));
$this->assertEquals(Option::parse(' -h'), new Option('-h', null));
$this->assertEquals(Option::parse('-h TOPIC Descripton... [default: 2]'), new Option('-h', null, 1, '2'));
$this->assertEquals(Option::parse('-h TOPIC Descripton... [default: topic-1]'), new Option('-h', null, 1, 'topic-1'));
$this->assertEquals(Option::parse('--help=TOPIC ... [default: 3.14]'), new Option(null, '--help', 1, '3.14'));
$this->assertEquals(Option::parse('-h, --help=DIR ... [default: ./]'), new Option('-h', '--help', 1, "./"));
$this->assertEquals(Option::parse('-h TOPIC Descripton... [dEfAuLt: 2]'), new Option('-h', null, 1, '2'));
}
public function testOptionName()
{
$option = new Option('-h', null);
$this->assertEquals($option->name, '-h');
$option = new Option('-h', '--help');
$this->assertEquals($option->name, '--help');
$option = new Option(null, '--help');
$this->assertEquals($option->name, '--help');
}
public function testCommands()
{
$this->assertEquals($this->docopt('Usage: prog add', 'add')->args, array('add' => true));
$this->assertEquals($this->docopt('Usage: prog [add]', '')->args, array('add' => false));
$this->assertEquals($this->docopt('Usage: prog [add]', 'add')->args, array('add' => true));
$this->assertEquals($this->docopt('Usage: prog (add|rm)', 'add')->args, array('add' => true, 'rm' => false));
$this->assertEquals($this->docopt('Usage: prog (add|rm)', 'rm')->args, array('add' => false, 'rm' => true));
$this->assertEquals($this->docopt('Usage: prog a b', 'a b')->args, array('a' => true, 'b' => true));
// invalid input exit test
$this->assertEquals($this->docopt('Usage: prog a b', 'b a')->status, 1);
}
public function testFormalUsage()
{
$doc =
"Usage: prog [-hv] ARG\n"
." prog N M\n"
."\n"
."prog is a program"
;
list ($usage, ) = \Docopt\parse_section('usage:', $doc);
$this->assertEquals($usage, "Usage: prog [-hv] ARG\n prog N M");
$this->assertEquals(\Docopt\formal_usage($usage), "( [-hv] ARG ) | ( N M )");
}
public function testParseArgv()
{
$o = new \ArrayIterator(array(new Option('-h'), new Option('-v', '--verbose'), new Option('-f', '--file', 1)));
$ts = function($s) { return new \Docopt\Tokens($s, 'ExitException'); };
$this->assertEquals(\Docopt\parse_argv($ts(''), $o), array());
$this->assertEquals(\Docopt\parse_argv($ts('-h'), $o), array(new Option('-h', null, 0, true)));
$this->assertEquals(\Docopt\parse_argv($ts('-h --verbose'), $o), array(new Option('-h', null, 0, true), new Option('-v', '--verbose', 0, true)));
$this->assertEquals(
\Docopt\parse_argv($ts('-h --file f.txt'), $o),
array(new Option('-h', null, 0, true), new Option('-f', '--file', 1, 'f.txt'))
);
$this->assertEquals(
\Docopt\parse_argv($ts('-h --file f.txt arg'), $o),
array(new Option('-h', null, 0, true),
new Option('-f', '--file', 1, 'f.txt'),
new Argument(null, 'arg')
)
);
$this->assertEquals(
\Docopt\parse_argv($ts('-h --file f.txt arg arg2'), $o),
array(new Option('-h', null, 0, true),
new Option('-f', '--file', 1, 'f.txt'),
new Argument(null, 'arg'),
new Argument(null, 'arg2')
)
);
$this->assertEquals(
\Docopt\parse_argv($ts('-h arg -- -v'), $o),
array(
new Option('-h', null, 0, true),
new Argument(null, 'arg'),
new Argument(null, '--'),
new Argument(null, '-v')
)
);
}
public function testParsePattern()
{
$o = new \ArrayIterator(array(new Option('-h'), new Option('-v', '--verbose'), new Option('-f', '--file', 1)));
$this->assertEquals(
\Docopt\parse_pattern('[ -h ]', $o),
new Required(new Optional(new Option('-h')))
);
$this->assertEquals(
\Docopt\parse_pattern('[ ARG ... ]', $o),
new Required(new Optional(new OneOrMore(new Argument('ARG'))))
);
$this->assertEquals(
\Docopt\parse_pattern('[ -h | -v ]', $o),
new Required(new Optional(
new Either(new Option('-h'), new Option('-v', '--verbose'))
))
);
$this->assertEquals(
\Docopt\parse_pattern('( -h | -v [ --file ] )', $o),
new Required(new Required(new Either(new Option('-h'), new Required(new Option('-v', '--verbose'), new Optional(new Option('-f', '--file', 1, null))))))
);
$this->assertEquals(
\Docopt\parse_pattern('(-h|-v[--file=]N...)', $o),
new Required(new Required(new Either(new Option('-h'),
new Required(new Option('-v', '--verbose'),
new Optional(new Option('-f', '--file', 1, null)),
new OneOrMore(new Argument('N'))))))
);
$this->assertEquals(
\Docopt\parse_pattern('(N [M | (K | L)] | O P)', new \ArrayIterator(array())),
new Required(new Required(new Either(new Required(new Argument('N'),
new Optional(new Either(new Argument('M'), new Required(
new Either(new Argument('K'), new Argument('L')))))),
new Required(new Argument('O'), new Argument('P')))))
);
$this->assertEquals(\Docopt\parse_pattern('[ -h ] [N]', $o),
new Required(
new Optional(new Option('-h')),
new Optional(new Argument('N')))
);
$this->assertEquals(
\Docopt\parse_pattern('[options]', $o),
new Required(new Optional(new OptionsShortcut()))
);
$this->assertEquals(\Docopt\parse_pattern('[options] A', $o),
new Required(
new Optional(new OptionsShortcut()),
new Argument('A'))
);
$this->assertEquals(\Docopt\parse_pattern('-v [options]', $o),
new Required(new Option('-v', '--verbose'),
new Optional(new OptionsShortcut()))
);
$this->assertEquals(\Docopt\parse_pattern('ADD', $o), new Required(new Argument('ADD')));
$this->assertEquals(\Docopt\parse_pattern('', $o), new Required(new Argument('')));
$this->assertEquals(\Docopt\parse_pattern('add', $o), new Required(new Command('add')));
}
public function testOptionMatch()
{
$option = new Option('-a');
$this->assertEquals(
$option->match(array(new Option('-a', null, 0, true))),
array(true, array(), array(new Option('-a', null, 0, true)))
);
$option = new Option('-a');
$this->assertEquals(
$option->match(array(new Option('-x'))),
array(false, array(new Option('-x')), array())
);
$option = new Option('-a');
$this->assertEquals(
$option->match(array(new Argument('N'))),
array(false, array(new Argument('N')), array())
);
$option = new Option('-a');
$this->assertEquals(
$option->match(array(new Option('-x'), new Option('-a'), new Argument('N'))),
array(true, array(new Option('-x'), new Argument('N')), array(new Option('-a')))
);
$option = new Option('-a');
$this->assertEquals(
$option->match(array(new Option('-a', null, 0, true), new Option('-a'))),
array(true, array(new Option('-a')), array(new Option('-a', null, 0, true)))
);
}
function testArgumentMatch()
{
$argument = new Argument('N');
$this->assertEquals($argument->match(array(new Argument(null, 9))),
array(true, array(), array(new Argument('N', 9))));
$argument = new Argument('N');
$this->assertEquals($argument->match(array(new Option('-x'))),
array(false, array(new Option('-x')), array()));
$argument = new Argument('N');
$this->assertEquals($argument->match(array(new Option('-x'),
new Option('-a'),
new Argument(null, 5))),
array(true, array(new Option('-x'), new Option('-a')), array(new Argument('N', 5))));
$argument = new Argument('N');
$this->assertEquals($argument->match(array(new Argument(null, 9), new Argument(null, 0))),
array(true, array(new Argument(null, 0)), array(new Argument('N', 9))));
}
function testCommandMatch()
{
$command = new Command('c');
$this->assertEquals(
$command->match(array(new Argument(null, 'c'))),
array(true, array(), array(new Command('c', true)))
);
$command = new Command('c');
$this->assertEquals(
$command->match(array(new Option('-x'))),
array(false, array(new Option('-x')), array())
);
$command = new Command('c');
$this->assertEquals($command->match(array(new Option('-x'),
new Option('-a'),
new Argument(null, 'c'))),
array(true, array(new Option('-x'), new Option('-a')), array(new Command('c', true)))
);
$either = new Either(new Command('add', false), new Command('rm', false));
$this->assertEquals(
$either->match(array(new Argument(null, 'rm'))),
array(true, array(), array(new Command('rm', true)))
);
}
function testOptionalMatch()
{
$optional = new Optional(new Option('-a'));
$this->assertEquals(
$optional->match(array(new Option('-a'))),
array(true, array(), array(new Option('-a')))
);
$optional = new Optional(new Option('-a'));
$this->assertEquals(
$optional->match(array()),
array(true, array(), array())
);
$optional = new Optional(new Option('-a'));
$this->assertEquals(
$optional->match(array(new Option('-x'))),
array(true, array(new Option('-x')), array())
);
$optional = new Optional(new Option('-a'), new Option('-b'));
$this->assertEquals(
$optional->match(array(new Option('-a'))),
array(true, array(), array(new Option('-a')))
);
$optional = new Optional(new Option('-a'), new Option('-b'));
$this->assertEquals(
$optional->match(array(new Option('-b'))),
array(true, array(), array(new Option('-b')))
);
$optional = new Optional(new Option('-a'), new Option('-b'));
$this->assertEquals(
$optional->match(array(new Option('-x'))),
array(true, array(new Option('-x')), array())
);
$optional = new Optional(new Argument('N'));
$this->assertEquals(
$optional->match(array(new Argument(null, 9))),
array(true, array(), array(new Argument('N', 9)))
);
$optional = new Optional(new Option('-a'), new Option('-b'));
$this->assertEquals(
$optional->match(array(new Option('-b'), new Option('-x'), new Option('-a'))),
array(true, array(new Option('-x')), array(new Option('-a'), new Option('-b')))
);
}
function testRequiredMatch()
{
$required = new Required(new Option('-a'));
$this->assertEquals($required->match(array(new Option('-a'))),
array(true, array(), array(new Option('-a')))
);
$required = new Required(new Option('-a'));
$this->assertEquals(
$required->match(array()),
array(false, array(), array())
);
$required = new Required(new Option('-a'));
$this->assertEquals(
$required->match(array(new Option('-x'))),
array(false, array(new Option('-x')), array())
);
$required = new Required(new Option('-a'), new Option('-b'));
$this->assertEquals(
$required->match(array(new Option('-a'))),
array(false, array(new Option('-a')), array())
);
}
function testEitherMatch()
{
$either = new Either(new Option('-a'), new Option('-b'));
$this->assertEquals(
$either->match(array(new Option('-a'))),
array(true, array(), array(new Option('-a')))
);
$either = new Either(new Option('-a'), new Option('-b'));
$this->assertEquals(
$either->match(array(new Option('-a'), new Option('-b'))),
array(true, array(new Option('-b')), array(new Option('-a')))
);
$either = new Either(new Option('-a'), new Option('-b'));
$this->assertEquals(
$either->match(array(new Option('-x'))),
array(false, array(new Option('-x')), array())
);
$either = new Either(new Option('-a'), new Option('-b'), new Option('-c'));
$this->assertEquals(
$either->match(array(new Option('-x'), new Option('-b'))),
array(true, array(new Option('-x')), array(new Option('-b')))
);
$either = new Either(new Argument('M'),
new Required(new Argument('N'), new Argument('M')));
$this->assertEquals(
$either->match(array(new Argument(null, 1), new Argument(null, 2))),
array(true, array(), array(new Argument('N', 1), new Argument('M', 2)))
);
}
function testOneOrMoreMatch()
{
$oneOrMore = new OneOrMore(new Argument('N'));
$this->assertEquals($oneOrMore->match(array(new Argument(null, 9))),
array(true, array(), array(new Argument('N', 9)))
);
$oneOrMore = new OneOrMore(new Argument('N'));
$this->assertEquals(
$oneOrMore->match(array()),
array(false, array(), array())
);
$oneOrMore = new OneOrMore(new Argument('N'));
$this->assertEquals(
$oneOrMore->match(array(new Option('-x'))),
array(false, array(new Option('-x')), array())
);
$oneOrMore = new OneOrMore(new Argument('N'));
$this->assertEquals(
$oneOrMore->match(array(new Argument(null, 9), new Argument(null, 8))),
array(true, array(), array(new Argument('N', 9), new Argument('N', 8)))
);
$oneOrMore = new OneOrMore(new Argument('N'));
$this->assertEquals(
$oneOrMore->match(array(new Argument(null, 9), new Option('-x'), new Argument(null, 8))),
array(true, array(new Option('-x')), array(new Argument('N', 9), new Argument('N', 8)))
);
$oneOrMore = new OneOrMore(new Option('-a'));
$this->assertEquals(
$oneOrMore->match(array(new Option('-a'), new Argument(null, 8), new Option('-a'))),
array(true, array(new Argument(null, 8)), array(new Option('-a'), new Option('-a')))
);
$oneOrMore = new OneOrMore(new Option('-a'));
$this->assertEquals(
$oneOrMore->match(array(new Argument(null, 8), new Option('-x'))),
array(false, array(new Argument(null, 8), new Option('-x')), array())
);
$oneOrMore = new OneOrMore(new Required(new Option('-a'), new Argument('N')));
$this->assertEquals(
$oneOrMore->match(array(new Option('-a'), new Argument(null, 1), new Option('-x'),
new Option('-a'), new Argument(null, 2))),
array(true, array(new Option('-x')),
array(new Option('-a'), new Argument('N', 1), new Option('-a'), new Argument('N', 2)))
);
$oneOrMore = new OneOrMore(new Optional(new Argument('N')));
$this->assertEquals(
$oneOrMore->match(array(new Argument(null, 9))),
array(true, array(), array(new Argument('N', 9)))
);
}
function testListArgumentMatch()
{
$input = new Required(new Argument('N'), new Argument('N'));
$this->assertEquals(
$input->fix()->match(
array(new Argument(null, '1'), new Argument(null, '2'))),
array(true, array(), array(new Argument('N', array('1', '2'))))
);
$input = new OneOrMore(new Argument('N'));
$this->assertEquals(
$input->fix()->match(
array(new Argument(null, '1'), new Argument(null, '2'), new Argument(null, '3'))),
array(true, array(), array(new Argument('N', array('1', '2', '3'))))
);
$input = new Required(new Argument('N'), new OneOrMore(new Argument('N')));
$this->assertEquals(
$input->fix()->match(
array(new Argument(null, '1'), new Argument(null, '2'), new Argument(null, '3'))),
array(true, array(), array(new Argument('N', array('1', '2', '3'))))
);
$input = new Required(new Argument('N'), new Required(new Argument('N')));
$this->assertEquals(
$input->fix()->match(
array(new Argument(null, '1'), new Argument(null, '2'))),
array(true, array(), array(new Argument('N', array('1', '2'))))
);
}
function testBasicPatternMatching()
{
# ( -a N [ -x Z ] )
$pattern = new Required(new Option('-a'), new Argument('N'),
new Optional(new Option('-x'), new Argument('Z')))
;
# -a N
$this->assertEquals($pattern->match(array(new Option('-a'), new Argument(null, 9))),
array(true, array(), array(new Option('-a'), new Argument('N', 9)))
);
# -a -x N Z
$this->assertEquals($pattern->match(array(new Option('-a'), new Option('-x'),
new Argument(null, 9), new Argument(null, 5))),
array(true, array(), array(new Option('-a'), new Argument('N', 9),
new Option('-x'), new Argument('Z', 5)))
);
# -x N Z # BZZ!
$this->assertEquals($pattern->match(array(new Option('-x'),
new Argument(null, 9),
new Argument(null, 5))),
array(false, array(new Option('-x'), new Argument(null, 9), new Argument(null, 5)), array())
);
}
function testPatternEither()
{
$input = new Option('-a');
$this->assertEquals(
\Docopt\transform($input),
new Either(new Required(new Option('-a')))
);
$input = new Argument('A');
$this->assertEquals(
\Docopt\transform($input),
new Either(new Required(new Argument('A')))
);
$input = new Required(new Either(new Option('-a'), new Option('-b')),
new Option('-c'));
$this->assertEquals(
\Docopt\transform($input),
new Either(new Required(new Option('-a'), new Option('-c')),
new Required(new Option('-b'), new Option('-c')))
);
$input = new Optional(new Option('-a'),
new Either(new Option('-b'),
new Option('-c')));
$this->assertEquals(
\Docopt\transform($input),
new Either(new Required(new Option('-b'), new Option('-a')),
new Required(new Option('-c'), new Option('-a')))
);
$input = new Either(new Option('-x'), new Either(new Option('-y'), new Option('-z')));
$this->assertEquals(
\Docopt\transform($input),
new Either(new Required(new Option('-x')),
new Required(new Option('-y')),
new Required(new Option('-z')))
);
$input = new OneOrMore(new Argument('N'), new Argument('M'));
$this->assertEquals(
\Docopt\transform($input),
new Either(new Required(new Argument('N'), new Argument('M'),
new Argument('N'), new Argument('M')))
);
}
function testPatternFixRepeatingArguments()
{
$input = new Option('-a');
$this->assertEquals($input->fixRepeatingArguments(), new Option('-a'));
$input = new Argument('N', null);
$this->assertEquals($input->fixRepeatingArguments(), new Argument('N', null));
$input = new Required(new Argument('N'), new Argument('N'));
$this->assertEquals(
$input->fixRepeatingArguments(),
new Required(new Argument('N', array()), new Argument('N', array()))
);
$input = new Either(new Argument('N'), new OneOrMore(new Argument('N')));
$this->assertEquals(
$input->fix(),
new Either(new Argument('N', array()), new OneOrMore(new Argument('N', array())))
);
}
function testSet()
{
$this->assertEquals(new Argument('N'), new Argument('N'));
$this->assertEquals(
array_unique(array(new Argument('N'), new Argument('N'))),
array(new Argument('N'))
);
}
function testPatternFixIdentities1()
{
$pattern = new Required(new Argument('N'), new Argument('N'));
$this->assertEquals($pattern->children[0], $pattern->children[1]);
$this->assertNotSame($pattern->children[0], $pattern->children[1]);
$pattern->fixIdentities();
$this->assertSame($pattern->children[0], $pattern->children[1]);
}
function testPatternFixIdentities2()
{
$pattern = new Required(new Optional(new Argument('X'), new Argument('N')), new Argument('N'));
$this->assertEquals($pattern->children[0]->children[1], $pattern->children[1]);
$this->assertNotSame($pattern->children[0]->children[1], $pattern->children[1]);
$pattern->fixIdentities();
$this->assertSame($pattern->children[0]->children[1], $pattern->children[1]);
}
function testLongOptionsErrorHandling()
{
# $this->setExpectedException('Docopt\LanguageError');
# $this->docopt('Usage: prog --non-existent', '--non-existent')
# $this->setExpectedException('Docopt\LanguageError');
# $this->docopt('Usage: prog --non-existent')
$result = $this->docopt('Usage: prog', '--non-existent');
$this->assertFalse($result->success);
$result = $this->docopt("Usage: prog [--version --verbose]\n".
"Options: --version\n --verbose", '--ver');
$this->assertFalse($result->success);
}
function testLongOptionsErrorHandlingPart2()
{
$this->setExpectedException('Docopt\LanguageError');
$result = $this->docopt("Usage: prog --long\nOptions: --long ARG");
}
function testLongOptionsErrorHandlingPart3()
{
$result = $this->docopt("Usage: prog --long ARG\nOptions: --long ARG", '--long');
$this->assertFalse($result->success);
}
function testLongOptionsErrorHandlingPart4()
{
$this->setExpectedException('Docopt\LanguageError');
$result = $this->docopt("Usage: prog --long=ARG\nOptions: --long");
}
function testLongOptionsErrorHandlingPart5()
{
$result = $this->docopt("Usage: prog --long\nOptions: --long", '--long=ARG');
$this->assertFalse($result->success);
}
function testShortOptionsErrorHandlingPart1()
{
$this->setExpectedException('Docopt\LanguageError');
$this->docopt("Usage: prog -x\nOptions: -x this\n -x that");
}
function testShortOptionsErrorHandlingPart2()
{
$result = $this->docopt('Usage: prog', '-x');
$this->assertFalse($result->success);
}
function testShortOptionsErrorHandlingPart3()
{
$this->setExpectedException('Docopt\LanguageError');
$this->docopt("Usage: prog -o\nOptions: -o ARG");
}
function testShortOptionsErrorHandlingPart4()
{
$result = $this->docopt("Usage: prog -o ARG\n\n-o ARG", '-o');
$this->assertFalse($result->success);
}
function testMatchingParenPart1()
{
$this->setExpectedException('Docopt\LanguageError');
$this->docopt('Usage: prog [a [b]');
}
function testMatchingParenPart2()
{
$this->setExpectedException('Docopt\LanguageError');
$this->docopt('Usage: prog [a [b] ] c )');
}
function testAllowDoubleDash()
{
$this->assertEquals($this->docopt("usage: prog [-o] [--] \nOptions: -o",
'-- -o')->args, array('-o'=> false, ''=>'-o', '--'=>true)
);
$this->assertEquals($this->docopt("usage: prog [-o] [--] \nOptions: -o",
'-o 1')->args, array('-o'=>true, ''=>'1', '--'=>false)
);
$result = $this->docopt("usage: prog [-o] \nOptions: -o", '-- -o'); # "--" is not allowed; FIXME?
$this->assertFalse($result->success);
}
function testDocopt()
{
$doc = "Usage: prog [-v] A\n\n Options: -v Be verbose.";
$this->assertEquals($this->docopt($doc, 'arg')->args, array('-v'=>false, 'A'=>'arg'));
$this->assertEquals($this->docopt($doc, '-v arg')->args, array('-v'=>true, 'A'=>'arg'));
$doc = "Usage: prog [-vqr] [FILE]
prog INPUT OUTPUT
prog --help
Options:
-v print status messages
-q report only file names
-r show all occurrences of the same error
--help
";
$a = $this->docopt($doc, '-v file.py');
$this->assertEquals($a->args, array('-v'=>true, '-q'=>false, '-r'=>false, '--help'=>false,
'FILE'=>'file.py', 'INPUT'=>null, 'OUTPUT'=>null));
$a = $this->docopt($doc, '-v');
$this->assertEquals($a->args, array('-v'=>true, '-q'=>false, '-r'=>false, '--help'=>false,
'FILE'=>null, 'INPUT'=>null, 'OUTPUT'=>null));
$result = $this->docopt($doc, '-v input.py output.py');
$this->assertFalse($result->success);
$result = $this->docopt($doc, '--fake');
$this->assertFalse($result->success);
$result = $this->docopt($doc, '--hel');
$this->assertTrue($result['--help']);
}
function testLanguageErrors()
{
$this->setExpectedException('Docopt\LanguageError');
$this->docopt('no usage with colon here');
}
function testLanguageErrorsPart2()
{
$this->setExpectedException('Docopt\LanguageError');
$this->docopt("usage: here \n\n and again usage: here");
}
function testIssue40()
{
$result = $this->docopt('usage: prog --help-commands | --help', '--help');
$this->assertTrue($result['--help']);
$this->assertEquals($this->docopt('usage: prog --aabb | --aa', '--aa')->args, array('--aabb'=>false,
'--aa'=>true));
}
function testCountMultipleFlags()
{
$this->assertEquals($this->docopt('usage: prog [-v]', '-v')->args, array('-v'=>true));
$this->assertEquals($this->docopt('usage: prog [-vv]', '')->args, array('-v'=>0));
$this->assertEquals($this->docopt('usage: prog [-vv]', '-v')->args, array('-v'=>1));
$this->assertEquals($this->docopt('usage: prog [-vv]', '-vv')->args, array('-v'=>2));
$this->assertEquals($this->docopt('usage: prog [-vv]', '-v -v')->args, array('-v'=>2));
$this->assertFalse($this->docopt('usage: prog [-vv]', '-vvv')->success);
$this->assertEquals($this->docopt('usage: prog [-v | -vv | -vvv]', '-vvv')->args, array('-v'=>3));
$this->assertEquals($this->docopt('usage: prog -v...', '-vvvvvv')->args, array('-v'=>6));
$this->assertEquals($this->docopt('usage: prog [--ver --ver]', '--ver --ver')->args, array('--ver'=>2));
}
function testOptionsShortcutParameter()
{
$result = $this->docopt('usage: prog [options]', '-foo --bar --spam=eggs');
$this->assertFalse($result->success);
# $this->assertEquals($this->docopt('usage: prog [options]', '-foo --bar --spam=eggs',
# any_options=true), array('-f'=>true, '-o'=>2,
# '--bar'=>true, '--spam'=>'eggs'}
$result = $this->docopt('usage: prog [options]', '--foo --bar --bar');
$this->assertFalse($result->success);
# $this->assertEquals($this->docopt('usage: prog [options]', '--foo --bar --bar',
# any_options=true), array('--foo'=>true, '--bar'=>2}
$result = $this->docopt('usage: prog [options]', '--bar --bar --bar -ffff');
$this->assertFalse($result->success);
# $this->assertEquals($this->docopt('usage: prog [options]', '--bar --bar --bar -ffff',
# any_options=true), array('--bar'=>3, '-f'=>4}
$result = $this->docopt('usage: prog [options]', '--long=arg --long=another');
$this->assertFalse($result->success);
# $this->assertEquals($this->docopt('usage: prog [options]', '--long=arg --long=another',
# any_options=true), array('--long'=>['arg', 'another']}
}
#def test_options_shortcut_multiple_commands():
# # any_options is disabled
# $this->assertEquals($this->docopt('usage: prog c1 [options] prog c2 [options]',
# 'c2 -o', any_options=true), array('-o'=>true, 'c1'=>false, 'c2'=>true}
# $this->assertEquals($this->docopt('usage: prog c1 [options] prog c2 [options]',
# 'c1 -o', any_options=true), array('-o'=>true, 'c1'=>true, 'c2'=>false}
// removed in the python version for some reason
public function testOptionsShortcutDoesNotAddOptionsToPatternSecondTime()
{
$this->assertEquals($this->docopt("usage: prog [options] [-a]\nOptions: -a -b", '-a')->args,
array('-a'=>true, '-b'=>false));
$result = $this->docopt("usage: prog [options] [-a]\nOptions: -a -b", '-aa');
$this->assertFalse($result->success);
}
function testDefaultValueForPositionalArguments()
{
$doc = "Usage: prog [--data=...]\n".
"Options:\n\t-d --data= Input data [default: x]";
$a = $this->docopt($doc, '')->args;
$this->assertEquals($a, array('--data'=>array('x')));
$doc = "Usage: prog [--data=...]\n".
"Options:\n\t-d --data= Input data [default: x y]";
$a = $this->docopt($doc, '')->args;
$this->assertEquals($a, array('--data'=>array('x', 'y')));
$doc = "Usage: prog [--data=...]\n".
"Options:\n\t-d --data= Input data [default: x y]";
$a = $this->docopt($doc, '--data=this')->args;
$this->assertEquals($a, array('--data'=>array('this')));
/* Doesn't work.
$doc = "Usage: prog [--data=...]\n".
"Options:\n\t-d --data= Input data [default: \"hello world\"]";
$a = $this->docopt($doc, '')->args;
$this->assertEquals($a, ['--data'=>['hello world']]);
*/
}
#def test_parse_defaults():
# $this->assertEquals(parse_defaults("""usage: prog
#
# -o, --option
# --another description
# [default: x]
#
# description [default: y]"""),
# ([new Option('-o', '--option', 1, null),
# new Option(null, '--another', 1, 'x')],
# [new Argument('', null),
# new Argument('', 'y')])
#
# doc = '''
# -h, --help Print help message.
# -o FILE Output file.
# --verbose Verbose mode.'''
# $this->assertEquals(parse_defaults(doc)[0], [new Option('-h', '--help'),
# new Option('-o', null, 1),
# new Option(null, '--verbose')]
public function testIssue59()
{
$this->assertEquals($this->docopt("usage: prog --long=", '--long=')->args, array('--long'=>''));
$this->assertEquals($this->docopt("usage: prog -l \noptions: -l ", array('-l', ''))->args, array('-l'=>''));
}
public function testOptionsFirst()
{
$this->assertEquals(
$this->docopt('usage: prog [--opt] [...]', '--opt this that')->args,
array('--opt'=>true, ''=>array('this', 'that'))
);
$this->assertEquals(
$this->docopt('usage: prog [--opt] [...]', 'this that --opt')->args,
array('--opt'=>true, ''=>array('this', 'that'))
);
$this->assertEquals(
$this->docopt('usage: prog [--opt] [...]', 'this that --opt', array('optionsFirst'=>true))->args,
array('--opt'=>false, ''=>array('this', 'that', '--opt'))
);
// found issue with PHP version in this situation
$this->assertEquals(
$this->docopt('usage: prog [--opt=] [...]', ' --opt=foo this that --opt', array('optionsFirst'=>true))->args,
array('--opt'=>'foo', ''=>array('this', 'that', '--opt'))
);
}
public function testIssue68OptionsShortcutDoesNotIncludeOptionsInUsagePattern()
{
$args = $this->docopt("usage: prog [-ab] [options]\noptions: -x\n -y", '-ax');
$this->assertTrue($args['-a']);
$this->assertFalse($args['-b']);
$this->assertTrue($args['-x']);
$this->assertFalse($args['-y']);
}
public function testIssue71DoubleDashIsNotAValidOptionArgument()
{
$result = $this->docopt("usage: prog [--log=LEVEL] [--] ...", "--log -- 1 2");
$this->assertFalse($result->success);
$result = $this->docopt("usage: prog [-l LEVEL] [--] ...\noptions: -l LEVEL", "-l -- 1 2");
$this->assertFalse($result->success);
}
public function testParseSection()
{
$this->assertEquals(\Docopt\parse_section('usage:', 'foo bar fizz buzz'), array());
$this->assertEquals(\Docopt\parse_section('usage:', 'usage: prog'), array('usage: prog'));
$this->assertEquals(\Docopt\parse_section('usage:', "usage: -x\n -y"), array("usage: -x\n -y"));
$usage = <<assertEquals(\Docopt\parse_section("usage:", $usage), array(
"usage: this",
"usage:hai",
"usage: this that",
"usage: foo\n bar",
"PROGRAM USAGE:\n foo\n bar",
"usage:\n\ttoo\n\ttar",
"Usage: eggs spam",
"usage: pit stop",
));
}
public function testIssue126DefaultsNotParsedCorrectlyWhenTabs()
{
$section = "Options:\n\t--foo= [default: bar]";
$this->assertEquals(\Docopt\parse_defaults($section)->getArrayCopy(), array(new Option(null, '--foo', 1, 'bar')));
}
}
PK ?VFC C test.phpnu W+A null,
);
$options = array_merge(
$options,
getopt('', array('filter:'))
);
$pyTestFile = $basePath.'/py/testcases.docopt';
if (!file_exists($pyTestFile)) {
die("Please ensure you have loaded the git submodules\n");
}
$suite = new PHPUnit_Framework_TestSuite();
$suite->addTest(new PHPUnit_Framework_TestSuite('Docopt\Test\PythonPortedTest'));
$suite->addTest(Docopt\Test\LanguageAgnosticTest::createSuite($pyTestFile));
$runner = new PHPUnit_TextUI_TestRunner();
$runner->doRun($suite, array(
'filter'=>$options['filter'],
'strict'=>true,
));
PK ?V~I examples/arguments.phpnu W+A '1.0.0rc2'));
foreach ($result as $k=>$v)
echo $k.': '.json_encode($v).PHP_EOL;
PK ?VZco o examples/any-options.phpnu W+A
Options:
-h --help show this help message and exit
--version show version and exit
-n, --number N use N as a number
-t, --timeout TIMEOUT set timeout TIMEOUT seconds
--apply apply changes to database
-q operate in quiet mode
";
$result = Docopt\docopt($doc, array('version'=>'1.0.0rc2'));
foreach ($result as $k=>$v)
echo $k.': '.json_encode($v).PHP_EOL;
PK ?V&N
.gitignorenu W+A vendor/
PK ?VI@c src/docopt.phpnu W+A
*/
namespace
{
class Docopt
{
/**
* API compatibility with python docopt
*/
static function handle($doc, $params=array())
{
$argv = null;
if (isset($params['argv'])) {
$argv = $params['argv'];
unset($params['argv']);
}
elseif (is_string($params)) {
$argv = $params;
$params = array();
}
$h = new \Docopt\Handler($params);
return $h->handle($doc, $argv);
}
}
}
namespace Docopt
{
/**
* Return true if all cased characters in the string are uppercase and there is
* at least one cased character, false otherwise.
* Python method with no knowrn equivalent in PHP.
*/
function is_upper($string)
{
return preg_match('/[A-Z]/', $string) && !preg_match('/[a-z]/', $string);
}
/**
* Return True if any element of the iterable is true. If the iterable is empty, return False.
* Python method with no known equivalent in PHP.
*/
function any($iterable)
{
foreach ($iterable as $element) {
if ($element)
return true;
}
return false;
}
/**
* The PHP version of this doesn't support array iterators
*/
function array_filter($input, $callback, $reKey=false)
{
if ($input instanceof \ArrayIterator)
$input = $input->getArrayCopy();
$filtered = \array_filter($input, $callback);
if ($reKey) $filtered = array_values($filtered);
return $filtered;
}
/**
* The PHP version of this doesn't support array iterators
*/
function array_merge()
{
$values = func_get_args();
$resolved = array();
foreach ($values as $v) {
if ($v instanceof \ArrayIterator)
$resolved[] = $v->getArrayCopy();
else
$resolved[] = $v;
}
return call_user_func_array('array_merge', $resolved);
}
function ends_with($str, $test)
{
$len = strlen($test);
return substr_compare($str, $test, -$len, $len) === 0;
}
function get_class_name($obj)
{
$cls = get_class($obj);
return substr($cls, strpos($cls, '\\')+1);
}
function dumpw($val)
{
echo dump($val);
echo PHP_EOL;
}
function dump($val)
{
$out = "";
if (is_array($val) || $val instanceof \Traversable) {
$out = '[';
$cur = array();
foreach ($val as $i) {
if (is_object($i))
$cur[] = $i->dump();
elseif (is_array($i))
$cur[] = dump($i);
else
$cur[] = dump_scalar($i);
}
$out .= implode(', ', $cur);
$out .= ']';
}
else
$out .=$val->dump();
return $out;
}
function dump_scalar($scalar)
{
if ($scalar === null)
return 'None';
elseif ($scalar === false)
return 'False';
elseif ($scalar === true)
return 'True';
elseif (is_int($scalar) || is_float($scalar))
return $scalar;
else
return "'$scalar'";
}
/**
* Error in construction of usage-message by developer
*/
class LanguageError extends \Exception
{
}
/**
* Exit in case user invoked program with incorrect arguments.
* DocoptExit equivalent.
*/
class ExitException extends \RuntimeException
{
public static $usage;
public $status;
public function __construct($message=null, $status=1)
{
parent::__construct(trim($message.PHP_EOL.static::$usage));
$this->status = $status;
}
}
class Pattern
{
public function __toString()
{
return serialize($this);
}
public function hash()
{
return crc32((string)$this);
}
public function fix()
{
$this->fixIdentities();
$this->fixRepeatingArguments();
return $this;
}
/**
* Make pattern-tree tips point to same object if they are equal.
*/
public function fixIdentities($uniq=null)
{
if (!isset($this->children) || !$this->children)
return $this;
if (!$uniq) {
$uniq = array_unique($this->flat());
}
foreach ($this->children as $i=>$child) {
if (!$child instanceof BranchPattern) {
if (!in_array($child, $uniq)) {
// Not sure if this is a true substitute for 'assert c in uniq'
throw new \UnexpectedValueException();
}
$this->children[$i] = $uniq[array_search($child, $uniq)];
}
else {
$child->fixIdentities($uniq);
}
}
}
/**
* Fix elements that should accumulate/increment values.
*/
public function fixRepeatingArguments()
{
$either = array();
foreach (transform($this)->children as $child) {
$either[] = $child->children;
}
foreach ($either as $case) {
$counts = array();
foreach ($case as $child) {
$ser = serialize($child);
if (!isset($counts[$ser]))
$counts[$ser] = array('cnt'=>0, 'items'=>array());
$counts[$ser]['cnt']++;
$counts[$ser]['items'][] = $child;
}
$repeatedCases = array();
foreach ($counts as $child) {
if ($child['cnt'] > 1)
$repeatedCases = array_merge($repeatedCases, $child['items']);
}
foreach ($repeatedCases as $e) {
if ($e instanceof Argument || ($e instanceof Option && $e->argcount)) {
if (!$e->value)
$e->value = array();
elseif (!is_array($e->value) && !$e->value instanceof \Traversable)
$e->value = preg_split('/\s+/', $e->value);
}
if ($e instanceof Command || ($e instanceof Option && $e->argcount == 0))
$e->value = 0;
}
}
return $this;
}
public function name()
{}
public function __get($name)
{
if ($name == 'name')
return $this->name();
else
throw new \BadMethodCallException("Unknown property $name");
}
}
/**
* Expand pattern into an (almost) equivalent one, but with single Either.
*
* Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)
* Quirks: [-a] => (-a), (-a...) => (-a -a)
*/
function transform($pattern)
{
$result = array();
$groups = array(array($pattern));
$parents = array('Required', 'Optional', 'OptionsShortcut', 'Either', 'OneOrMore');
while ($groups) {
$children = array_shift($groups);
$types = array();
foreach ($children as $c) {
if (is_object($c)) {
$types[get_class_name($c)] = true;
}
}
if (array_intersect(array_keys($types), $parents)) {
$child = null;
foreach ($children as $currentChild) {
if (in_array(get_class_name($currentChild), $parents)) {
$child = $currentChild;
break;
}
}
unset($children[array_search($child, $children)]);
$childClass = get_class_name($child);
if ($childClass == 'Either') {
foreach ($child->children as $c) {
$groups[] = array_merge(array($c), $children);
}
}
elseif ($childClass == 'OneOrMore') {
$groups[] = array_merge($child->children, $child->children, $children);
}
else {
$groups[] = array_merge($child->children, $children);
}
}
else {
$result[] = $children;
}
}
$rs = array();
foreach ($result as $e) {
$rs[] = new Required($e);
}
return new Either($rs);
}
class LeafPattern extends Pattern
{
public function flat($types=array())
{
$types = is_array($types) ? $types : array($types);
if (!$types || in_array(get_class_name($this), $types))
return array($this);
else
return array();
}
public function match($left, $collected=null)
{
if (!$collected) $collected = array();
list ($pos, $match) = $this->singleMatch($left);
if (!$match)
return array(false, $left, $collected);
$left_ = $left;
unset($left_[$pos]);
$left_ = array_values($left_);
$name = $this->name;
$sameName = array_filter($collected, function ($a) use ($name) { return $name == $a->name; }, true);
if (is_int($this->value) || is_array($this->value) || $this->value instanceof \Traversable) {
if (is_int($this->value))
$increment = 1;
else
$increment = is_string($match->value) ? array($match->value) : $match->value;
if (!$sameName) {
$match->value = $increment;
return array(true, $left_, array_merge($collected, array($match)));
}
if (is_array($increment) || $increment instanceof \Traversable)
$sameName[0]->value = array_merge($sameName[0]->value, $increment);
else
$sameName[0]->value += $increment;
return array(true, $left_, $collected);
}
return array(true, $left_, array_merge($collected, array($match)));
}
}
class BranchPattern extends Pattern
{
public $children = array();
public function __construct($children=null)
{
if (!$children)
$children = array();
elseif ($children instanceof Pattern)
$children = func_get_args();
foreach ($children as $child) {
$this->children[] = $child;
}
}
public function flat($types=array())
{
$types = is_array($types) ? $types : array($types);
if (in_array(get_class_name($this), $types))
return array($this);
$flat = array();
foreach ($this->children as $c) {
$flat = array_merge($flat, $c->flat($types));
}
return $flat;
}
public function dump()
{
$out = get_class_name($this).'(';
$cd = array();
foreach ($this->children as $c) {
$cd[] = $c->dump();
}
$out .= implode(', ', $cd).')';
return $out;
}
}
class Argument extends LeafPattern
{
/* {{{ this stuff is against LeafPattern in the python version but it interferes with name() */
public $name;
public $value;
public function __construct($name, $value=null)
{
$this->name = $name;
$this->value = $value;
}
/* }}} */
public function singleMatch($left)
{
foreach ($left as $n=>$pattern) {
if ($pattern instanceof Argument) {
return array($n, new Argument($this->name, $pattern->value));
}
}
return array(null, null);
}
public static function parse($source)
{
$name = null;
$value = null;
if (preg_match_all('@(<\S*?'.'>)@', $source, $matches)) {
$name = $matches[0][0];
}
if (preg_match_all('@\[default: (.*)\]@i', $source, $matches)) {
$value = $matches[0][1];
}
return new static($name, $value);
}
public function dump()
{
return get_class_name($this)."(".dump_scalar($this->name).", ".dump_scalar($this->value).")";
}
}
class Command extends Argument
{
public $name;
public $value;
public function __construct($name, $value=false)
{
$this->name = $name;
$this->value = $value;
}
function singleMatch($left)
{
foreach ($left as $n=>$pattern) {
if ($pattern instanceof Argument) {
if ($pattern->value == $this->name)
return array($n, new Command($this->name, true));
else
break;
}
}
return array(null, null);
}
}
class Option extends LeafPattern
{
public $short;
public $long;
public function __construct($short=null, $long=null, $argcount=0, $value=false)
{
if ($argcount != 0 && $argcount != 1)
throw new \InvalidArgumentException();
$this->short = $short;
$this->long = $long;
$this->argcount = $argcount;
$this->value = $value;
// Python checks "value is False". maybe we should check "$value === false"
if (!$value && $argcount)
$this->value = null;
}
public static function parse($optionDescription)
{
$short = null;
$long = null;
$argcount = 0;
$value = false;
$exp = explode(' ', trim($optionDescription), 2);
$options = $exp[0];
$description = isset($exp[1]) ? $exp[1] : '';
$options = str_replace(',', ' ', str_replace('=', ' ', $options));
foreach (preg_split('/\s+/', $options) as $s) {
if (strpos($s, '--')===0)
$long = $s;
elseif ($s && $s[0] == '-')
$short = $s;
else
$argcount = 1;
}
if ($argcount) {
$value = null;
if (preg_match('@\[default: (.*)\]@i', $description, $match)) {
$value = $match[1];
}
}
return new static($short, $long, $argcount, $value);
}
public function singleMatch($left)
{
foreach ($left as $n=>$pattern) {
if ($this->name == $pattern->name) {
return array($n, $pattern);
}
}
return array(null, null);
}
public function name()
{
return $this->long ?: $this->short;
}
public function dump()
{
return "Option(".dump_scalar($this->short).", ".dump_scalar($this->long).", ".dump_scalar($this->argcount).", ".dump_scalar($this->value).")";
}
}
class Required extends BranchPattern
{
public function match($left, $collected=null)
{
if (!$collected)
$collected = array();
$l = $left;
$c = $collected;
foreach ($this->children as $pattern) {
list ($matched, $l, $c) = $pattern->match($l, $c);
if (!$matched)
return array(false, $left, $collected);
}
return array(true, $l, $c);
}
}
class Optional extends BranchPattern
{
public function match($left, $collected=null)
{
if (!$collected)
$collected = array();
foreach ($this->children as $pattern) {
list($m, $left, $collected) = $pattern->match($left, $collected);
}
return array(true, $left, $collected);
}
}
/**
* Marker/placeholder for [options] shortcut.
*/
class OptionsShortcut extends Optional
{
}
class OneOrMore extends BranchPattern
{
public function match($left, $collected=null)
{
if (count($this->children) != 1)
throw new \UnexpectedValueException();
if (!$collected)
$collected = array();
$l = $left;
$c = $collected;
$lnew = array();
$matched = true;
$times = 0;
while ($matched) {
# could it be that something didn't match but changed l or c?
list ($matched, $l, $c) = $this->children[0]->match($l, $c);
if ($matched) $times += 1;
if ($lnew == $l)
break;
$lnew = $l;
}
if ($times >= 1)
return array(true, $l, $c);
else
return array(false, $left, $collected);
}
}
class Either extends BranchPattern
{
public function match($left, $collected=null)
{
if (!$collected)
$collected = array();
$outcomes = array();
foreach ($this->children as $pattern) {
list ($matched, $dump1, $dump2) = $outcome = $pattern->match($left, $collected);
if ($matched)
$outcomes[] = $outcome;
}
if ($outcomes) {
// return min(outcomes, key=lambda outcome: len(outcome[1]))
$min = null;
$ret = null;
foreach ($outcomes as $o) {
$cnt = count($o[1]);
if ($min === null || $cnt < $min) {
$min = $cnt;
$ret = $o;
}
}
return $ret;
}
else
return array(false, $left, $collected);
}
}
class Tokens extends \ArrayIterator
{
public $error;
public function __construct($source, $error='ExitException')
{
if (!is_array($source)) {
$source = trim($source);
if ($source)
$source = preg_split('/\s+/', $source);
else
$source = array();
}
parent::__construct($source);
$this->error = $error;
}
public static function fromPattern($source)
{
$source = preg_replace('@([\[\]\(\)\|]|\.\.\.)@', ' $1 ', $source);
$source = preg_split('@\s+|(\S*<.*?>)@', $source, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
return new static($source, 'LanguageError');
}
function move()
{
$item = $this->current();
$this->next();
return $item;
}
function left()
{
$left = array();
while (($token = $this->move()) !== null) {
$left[] = $token;
}
return $left;
}
function raiseException($message)
{
$class = __NAMESPACE__.'\\'.$this->error;
throw new $class($message);
}
}
/**
* long ::= '--' chars [ ( ' ' | '=' ) chars ] ;
*/
function parse_long($tokens, \ArrayIterator $options)
{
$token = $tokens->move();
$exploded = explode('=', $token, 2);
if (count($exploded) == 2) {
$long = $exploded[0];
$eq = '=';
$value = $exploded[1];
}
else {
$long = $token;
$eq = null;
$value = null;
}
if (strpos($long, '--') !== 0)
throw new \UnexpectedValueExeption();
$value = (!$eq && !$value) ? null : $value;
$similar = array_filter($options, function($o) use ($long) { return $o->long && $o->long == $long; }, true);
if ('ExitException' == $tokens->error && !$similar)
$similar = array_filter($options, function($o) use ($long) { return $o->long && strpos($o->long, $long)===0; }, true);
if (count($similar) > 1) {
// might be simply specified ambiguously 2+ times?
$tokens->raiseException("$long is not a unique prefix: ".implode(', ', array_map(function($o) { return $o->long; }, $similar)));
}
elseif (count($similar) < 1) {
$argcount = $eq == '=' ? 1 : 0;
$o = new Option(null, $long, $argcount);
$options[] = $o;
if ($tokens->error == 'ExitException') {
$o = new Option(null, $long, $argcount, $argcount ? $value : true);
}
}
else {
$o = new Option($similar[0]->short, $similar[0]->long, $similar[0]->argcount, $similar[0]->value);
if ($o->argcount == 0) {
if ($value !== null) {
$tokens->raiseException("{$o->long} must not have an argument");
}
}
else {
if ($value === null) {
if ($tokens->current() === null || $tokens->current() == "--") {
$tokens->raiseException("{$o->long} requires argument");
}
$value = $tokens->move();
}
}
if ($tokens->error == 'ExitException') {
$o->value = $value !== null ? $value : true;
}
}
return array($o);
}
/**
* shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;
*/
function parse_shorts($tokens, \ArrayIterator $options)
{
$token = $tokens->move();
if (strpos($token, '-') !== 0 || strpos($token, '--') === 0)
throw new \UnexpectedValueExeption();
$left = ltrim($token, '-');
$parsed = array();
while ($left != '') {
$short = '-'.$left[0];
$left = substr($left, 1);
$similar = array();
foreach ($options as $o) {
if ($o->short == $short)
$similar[] = $o;
}
$similarCnt = count($similar);
if ($similarCnt > 1) {
$tokens->raiseException("$short is specified ambiguously $similarCnt times");
}
elseif ($similarCnt < 1) {
$o = new Option($short, null, 0);
$options[] = $o;
if ($tokens->error == 'ExitException')
$o = new Option($short, null, 0, true);
}
else {
$o = new Option($short, $similar[0]->long, $similar[0]->argcount, $similar[0]->value);
$value = null;
if ($o->argcount != 0) {
if ($left == '') {
if ($tokens->current() === null || $tokens->current() == '--')
$tokens->raiseException("$short requires argument");
$value = $tokens->move();
}
else {
$value = $left;
$left = '';
}
}
if ($tokens->error == 'ExitException') {
$o->value = $value !== null ? $value : true;
}
}
$parsed[] = $o;
}
return $parsed;
}
function parse_pattern($source, \ArrayIterator $options)
{
$tokens = Tokens::fromPattern($source);
$result = parse_expr($tokens, $options);
if ($tokens->current() != null) {
$tokens->raiseException('unexpected ending: '.implode(' ', $tokens->left()));
}
return new Required($result);
}
/**
* expr ::= seq ( '|' seq )* ;
*/
function parse_expr($tokens, \ArrayIterator $options)
{
$seq = parse_seq($tokens, $options);
if ($tokens->current() != '|')
return $seq;
$result = null;
if (count($seq) > 1)
$result = array(new Required($seq));
else
$result = $seq;
while ($tokens->current() == '|') {
$tokens->move();
$seq = parse_seq($tokens, $options);
if (count($seq) > 1)
$result[] = new Required($seq);
else
$result = array_merge($result, $seq);
}
if (count($result) > 1)
return new Either($result);
else
return $result;
}
/**
* seq ::= ( atom [ '...' ] )* ;
*/
function parse_seq($tokens, \ArrayIterator $options)
{
$result = array();
$not = array(null, '', ']', ')', '|');
while (!in_array($tokens->current(), $not, true)) {
$atom = parse_atom($tokens, $options);
if ($tokens->current() == '...') {
$atom = array(new OneOrMore($atom));
$tokens->move();
}
if ($atom instanceof \ArrayIterator)
$atom = $atom->getArrayCopy();
if ($atom) {
$result = array_merge($result, $atom);
}
}
return $result;
}
/**
* atom ::= '(' expr ')' | '[' expr ']' | 'options'
* | long | shorts | argument | command ;
*/
function parse_atom($tokens, \ArrayIterator $options)
{
$token = $tokens->current();
$result = array();
if ($token == '(' || $token == '[') {
$tokens->move();
static $index;
if (!$index) $index = array('('=>array(')', __NAMESPACE__.'\Required'), '['=>array(']', __NAMESPACE__.'\Optional'));
list ($matching, $pattern) = $index[$token];
$result = new $pattern(parse_expr($tokens, $options));
if ($tokens->move() != $matching)
$tokens->raiseException("Unmatched '$token'");
return array($result);
}
elseif ($token == 'options') {
$tokens->move();
return array(new OptionsShortcut);
}
elseif (strpos($token, '--') === 0 && $token != '--') {
return parse_long($tokens, $options);
}
elseif (strpos($token, '-') === 0 && $token != '-' && $token != '--') {
return parse_shorts($tokens, $options);
}
elseif (strpos($token, '<') === 0 && ends_with($token, '>') || is_upper($token)) {
return array(new Argument($tokens->move()));
}
else {
return array(new Command($tokens->move()));
}
}
/**
* Parse command-line argument vector.
*
* If options_first:
* argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
* else:
* argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
*/
function parse_argv($tokens, \ArrayIterator $options, $optionsFirst=false)
{
$parsed = array();
while ($tokens->current() !== null) {
if ($tokens->current() == '--') {
while ($tokens->current() !== null) {
$parsed[] = new Argument(null, $tokens->move());
}
return $parsed;
}
elseif (strpos($tokens->current(), '--')===0) {
$parsed = array_merge($parsed, parse_long($tokens, $options));
}
elseif (strpos($tokens->current(), '-')===0 && $tokens->current() != '-') {
$parsed = array_merge($parsed, parse_shorts($tokens, $options));
}
elseif ($optionsFirst) {
return array_merge($parsed, array_map(function($v) { return new Argument(null, $v); }, $tokens->left()));
}
else {
$parsed[] = new Argument(null, $tokens->move());
}
}
return $parsed;
}
function parse_defaults($doc)
{
$defaults = array();
foreach (parse_section('options:', $doc) as $s) {
# FIXME corner case "bla: options: --foo"
list (, $s) = explode(':', $s, 2);
$splitTmp = array_slice(preg_split("@\n[ \t]*(-\S+?)@", "\n".$s, null, PREG_SPLIT_DELIM_CAPTURE), 1);
$split = array();
for ($cnt = count($splitTmp), $i=0; $i < $cnt; $i+=2) {
$split[] = $splitTmp[$i] . (isset($splitTmp[$i+1]) ? $splitTmp[$i+1] : '');
}
$options = array();
foreach ($split as $s) {
if (strpos($s, '-') === 0)
$options[] = Option::parse($s);
}
$defaults = array_merge($defaults, $options);
}
return new \ArrayIterator($defaults);
}
function parse_section($name, $source)
{
$ret = array();
if (preg_match_all('@^([^\n]*'.$name.'[^\n]*\n?(?:[ \t].*?(?:\n|$))*)@im', $source, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$ret[] = trim($match[0]);
}
}
return $ret;
}
function formal_usage($section)
{
list (, $section) = explode(':', $section, 2); # drop "usage:"
$pu = preg_split('/\s+/', trim($section));
$ret = array();
foreach (array_slice($pu, 1) as $s) {
if ($s == $pu[0])
$ret[] = ') | (';
else
$ret[] = $s;
}
return '( '.implode(' ', $ret).' )';
}
function extras($help, $version, $options, $doc)
{
$ofound = false;
$vfound = false;
foreach ($options as $o) {
if ($o->value && ($o->name == '-h' || $o->name == '--help'))
$ofound = true;
if ($o->value && $o->name == '--version')
$vfound = true;
}
if ($help && $ofound) {
ExitException::$usage = null;
throw new ExitException($doc, 0);
}
if ($version && $vfound) {
ExitException::$usage = null;
throw new ExitException($version, 0);
}
}
class Handler
{
public $exit = true;
public $help = true;
public $optionsFirst = false;
public $version;
public function __construct($options=array())
{
foreach ($options as $k=>$v)
$this->$k = $v;
}
function handle($doc, $argv=null)
{
try {
if ($argv === null && isset($_SERVER['argv']))
$argv = array_slice($_SERVER['argv'], 1);
$usageSections = parse_section('usage:', $doc);
if (count($usageSections) == 0)
throw new LanguageError('"usage:" (case-insensitive) not found.');
elseif (count($usageSections) > 1)
throw new LanguageError('More than one "usage:" (case-insensitive).');
$usage = $usageSections[0];
// temp fix until python port provides solution
ExitException::$usage = $usage;
$options = parse_defaults($doc);
$formalUse = formal_usage($usage);
$pattern = parse_pattern($formalUse, $options);
$argv = parse_argv(new Tokens($argv), $options, $this->optionsFirst);
$patternOptions = $pattern->flat('Option');
foreach ($pattern->flat('OptionsShortcut') as $optionsShortcut) {
$docOptions = parse_defaults($doc);
$optionsShortcut->children = array_diff((array)$docOptions, $patternOptions);
}
extras($this->help, $this->version, $argv, $doc);
list($matched, $left, $collected) = $pattern->fix()->match($argv);
if ($matched && !$left) {
$return = array();
foreach (array_merge($pattern->flat(), $collected) as $a) {
$name = $a->name;
if ($name)
$return[$name] = $a->value;
}
return new Response($return);
}
throw new ExitException();
}
catch (ExitException $ex) {
$this->handleExit($ex);
return new Response(null, $ex->status, $ex->getMessage());
}
}
function handleExit(ExitException $ex)
{
if ($this->exit) {
echo $ex->getMessage().PHP_EOL;
exit($ex->status);
}
}
}
class Response implements \ArrayAccess, \IteratorAggregate
{
public $status;
public $output;
public $args;
public function __construct($args, $status=0, $output='')
{
$this->args = $args ?: array();
$this->status = $status;
$this->output = $output;
}
public function __get($name)
{
if ($name == 'success')
return $this->status === 0;
else
throw new \BadMethodCallException("Unknown property $name");
}
public function offsetExists($offset)
{
return isset($this->args[$offset]);
}
public function offsetGet($offset)
{
return $this->args[$offset];
}
public function offsetSet($offset, $value)
{
$this->args[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->args[$offset]);
}
public function getIterator()
{
return new \ArrayIterator($this->args);
}
}
}
PK ?V py/nu PK ?VIxR_ _
composer.locknu W+A PK ?VYKF? ? .` dev-setupnu W+A PK ?VdGE E
` README.rstnu W+A PK ?V? .travis.ymlnu W+A PK ?V\E LICENSE-MITnu W+A PK ?V]H H z .gitmodulesnu W+A PK ?VIJr r
composer.jsonnu W+A PK ?V,
! test/lib/LanguageAgnosticTest.phpnu W+A PK ?VSgn n test/lib/TestCase.phpnu W+A PK ?VV test/lib/PythonPortedTest.phpnu W+A PK ?VFC C Q test.phpnu W+A PK ?V~I #U examples/arguments.phpnu W+A PK ?VZco o X examples/any-options.phpnu W+A PK ?V&N
Z .gitignorenu W+A PK ?VI@c Z src/docopt.phpnu W+A PK ?V py/nu PK