Permalink
Browse files

initial import of Console_CommandLine PEAR2 port

  • Loading branch information...
1 parent 5bf3f93 commit 18ea84b7b5cfe0a26f8afa896f1a628c2cb98f75 @izimobil izimobil committed Jun 9, 2008
Showing with 5,501 additions and 0 deletions.
  1. +3 −0 CREDITS
  2. +12 −0 README
  3. +1 −0 RELEASE-0.1.0
  4. +153 −0 data/xmlschema.rng
  5. +77 −0 examples/ex1.php
  6. +49 −0 examples/ex2.php
  7. +34 −0 examples/ex2.xml
  8. +51 −0 makepackage.php
  9. +136 −0 package.xml
  10. +1,029 −0 src/Console/CommandLine.php
  11. +135 −0 src/Console/CommandLine/Action.php
  12. +79 −0 src/Console/CommandLine/Action/Callback.php
  13. +85 −0 src/Console/CommandLine/Action/Counter.php
  14. +59 −0 src/Console/CommandLine/Action/Help.php
  15. +89 −0 src/Console/CommandLine/Action/Password.php
  16. +66 −0 src/Console/CommandLine/Action/StoreArray.php
  17. +62 −0 src/Console/CommandLine/Action/StoreFalse.php
  18. +74 −0 src/Console/CommandLine/Action/StoreFloat.php
  19. +74 −0 src/Console/CommandLine/Action/StoreInt.php
  20. +61 −0 src/Console/CommandLine/Action/StoreString.php
  21. +62 −0 src/Console/CommandLine/Action/StoreTrue.php
  22. +59 −0 src/Console/CommandLine/Action/Version.php
  23. +76 −0 src/Console/CommandLine/Argument.php
  24. +46 −0 src/Console/CommandLine/Command.php
  25. +119 −0 src/Console/CommandLine/Element.php
  26. +78 −0 src/Console/CommandLine/Exception.php
  27. +55 −0 src/Console/CommandLine/MessageProvider.php
  28. +99 −0 src/Console/CommandLine/MessageProvider/Default.php
  29. +334 −0 src/Console/CommandLine/Option.php
  30. +66 −0 src/Console/CommandLine/Outputter.php
  31. +74 −0 src/Console/CommandLine/Outputter/Default.php
  32. +75 −0 src/Console/CommandLine/Renderer.php
  33. +383 −0 src/Console/CommandLine/Renderer/Default.php
  34. +76 −0 src/Console/CommandLine/Result.php
  35. +257 −0 src/Console/CommandLine/XmlParser.php
  36. +78 −0 tests/AllTests.php
  37. +28 −0 tests/console_commandline_accept.phpt
  38. +63 −0 tests/console_commandline_addargument.phpt
  39. +34 −0 tests/console_commandline_addcommand.phpt
  40. +119 −0 tests/console_commandline_addoption.phpt
  41. +14 −0 tests/console_commandline_addoption_errors_1.phpt
  42. +14 −0 tests/console_commandline_addoption_errors_2.phpt
  43. +14 −0 tests/console_commandline_addoption_errors_3.phpt
  44. +14 −0 tests/console_commandline_addoption_errors_4.phpt
  45. +14 −0 tests/console_commandline_addoption_errors_5.phpt
  46. +14 −0 tests/console_commandline_addoption_errors_6.phpt
  47. +14 −0 tests/console_commandline_addoption_errors_7.phpt
  48. +31 −0 tests/console_commandline_fromxmlfile.phpt
  49. +19 −0 tests/console_commandline_fromxmlfile_error.phpt
  50. +32 −0 tests/console_commandline_fromxmlstring.phpt
  51. +17 −0 tests/console_commandline_parse_1.phpt
  52. +36 −0 tests/console_commandline_parse_10.phpt
  53. +31 −0 tests/console_commandline_parse_11.phpt
  54. +27 −0 tests/console_commandline_parse_12.phpt
  55. +21 −0 tests/console_commandline_parse_13.phpt
  56. +21 −0 tests/console_commandline_parse_14.phpt
  57. +23 −0 tests/console_commandline_parse_15.phpt
  58. +21 −0 tests/console_commandline_parse_16.phpt
  59. +37 −0 tests/console_commandline_parse_2.phpt
  60. +58 −0 tests/console_commandline_parse_3.phpt
  61. +23 −0 tests/console_commandline_parse_4.phpt
  62. +23 −0 tests/console_commandline_parse_5.phpt
  63. +23 −0 tests/console_commandline_parse_6.phpt
  64. +67 −0 tests/console_commandline_parse_7.phpt
  65. +66 −0 tests/console_commandline_parse_8.phpt
  66. +55 −0 tests/console_commandline_parse_9.phpt
  67. +44 −0 tests/test.xml
  68. +218 −0 tests/tests.inc.php
View
3 CREDITS
@@ -0,0 +1,3 @@
+; Maintainers of Console_CommandLine
+David JEAN LOUIS [izi] <izi@php.net> (lead)
+
View
12 README
@@ -0,0 +1,12 @@
+PEAR2_Console_CommandLine is a full featured package for managing command-line
+options and arguments highly inspired from python optparse module, it allows
+the developer to easily build complex command line interfaces.
+
+Main features:
+* handles sub commands (ie. $ myscript.php -q subcommand -f file),
+* can be completely built from an xml definition file,
+* generate --help and --version options automatically,
+* can be completely customized,
+* builtin support for i18n,
+* and much more...
+
View
1 RELEASE-0.1.0
@@ -0,0 +1 @@
+Initial port of PEAR Console_CommandLine to PEAR2.
View
153 data/xmlschema.rng
@@ -0,0 +1,153 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ This is the RNG file for validating PEAR2_Console_CommandLine xml definitions.
+
+ Author : David JEAN LOUIS
+ Licence : MIT License
+ Version : SVN: $Id$
+-->
+
+<grammar xmlns="http://relaxng.org/ns/structure/1.0"
+ datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
+
+ <!-- structure -->
+ <start>
+ <ref name="ref_command"/>
+ </start>
+
+ <!-- Command node -->
+ <define name="ref_command">
+ <element name="command">
+ <interleave>
+ <optional>
+ <element name="name">
+ <text/>
+ </element>
+ </optional>
+ <optional>
+ <element name="description">
+ <text/>
+ </element>
+ </optional>
+ <optional>
+ <element name="version">
+ <text/>
+ </element>
+ </optional>
+ <optional>
+ <element name="add_help_option">
+ <ref name="ref_bool_choices"/>
+ </element>
+ </optional>
+ <optional>
+ <element name="add_version_option">
+ <ref name="ref_bool_choices"/>
+ </element>
+ </optional>
+ <optional>
+ <element name="force_posix">
+ <ref name="ref_bool_choices"/>
+ </element>
+ </optional>
+ <zeroOrMore>
+ <ref name="ref_option"/>
+ </zeroOrMore>
+ <zeroOrMore>
+ <ref name="ref_argument"/>
+ </zeroOrMore>
+ <zeroOrMore>
+ <ref name="ref_command"/>
+ </zeroOrMore>
+ </interleave>
+ </element>
+ </define>
+
+ <!-- options and arguments common elements -->
+
+ <define name="ref_option_argument_common">
+ <optional>
+ <element name="description">
+ <text/>
+ </element>
+ </optional>
+ <optional>
+ <element name="help_name">
+ <text/>
+ </element>
+ </optional>
+ <optional>
+ <element name="default">
+ <text/>
+ </element>
+ </optional>
+ </define>
+
+ <!-- Option node -->
+ <define name="ref_option">
+ <element name="option">
+ <attribute name="name">
+ <data type="string"/>
+ </attribute>
+ <interleave>
+ <optional>
+ <element name="short_name">
+ <text/>
+ </element>
+ </optional>
+ <optional>
+ <element name="long_name">
+ <text/>
+ </element>
+ </optional>
+ <ref name="ref_option_argument_common"/>
+ <optional>
+ <element name="action">
+ <text/>
+ </element>
+ </optional>
+ <optional>
+ <element name="choices">
+ <zeroOrMore>
+ <element name="choice">
+ <text/>
+ </element>
+ </zeroOrMore>
+ </element>
+ </optional>
+ </interleave>
+ </element>
+ </define>
+
+ <!-- Argument node -->
+ <define name="ref_argument">
+ <element name="argument">
+ <attribute name="name">
+ <data type="string"/>
+ </attribute>
+ <interleave>
+ <ref name="ref_option_argument_common"/>
+ <optional>
+ <element name="multiple">
+ <ref name="ref_bool_choices"/>
+ </element>
+ </optional>
+ </interleave>
+ </element>
+ </define>
+
+ <!-- boolean choices -->
+ <define name="ref_bool_choices">
+ <choice>
+ <value>true</value>
+ <value>1</value>
+ <value>on</value>
+ <value>yes</value>
+ <value>false</value>
+ <value>0</value>
+ <value>off</value>
+ <value>no</value>
+ </choice>
+ </define>
+
+</grammar>
View
77 examples/ex1.php
@@ -0,0 +1,77 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * A simple example demonstrating the basic features of the PEAR2_Console_CommandLine
+ * package.
+ * In this example we create a program that simply zip a set of files.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+// uncomment this when package won't be in the SandBox anymore
+// $basedir = __DIR__ . '/..';
+$basedir = __DIR__ . '/../..';
+
+// Include PEAR2 autoload
+require_once $basedir . '/autoload.php';
+
+// create the parser
+$parser = new PEAR2_Console_CommandLine(array(
+ 'description' => 'zip given files using the php zip module.',
+ 'version' => '1.0.0'
+));
+
+// add an option to make the program verbose
+$parser->addOption('verbose', array(
+ 'short_name' => '-v',
+ 'long_name' => '--verbose',
+ 'action' => 'StoreTrue',
+ 'description' => 'turn on verbose output'
+));
+
+// add an option to delete original files after zipping
+$parser->addOption('delete', array(
+ 'short_name' => '-d',
+ 'long_name' => '--delete',
+ 'action' => 'StoreString',
+ 'description' => 'delete original files after zip operation',
+ 'choices' => array('foo', 'bar')
+));
+
+// add the files argument, the user can specify one or several files
+$parser->addArgument('files', array(
+ 'multiple' => true,
+ 'description' => 'list of files to zip separated by spaces'
+));
+
+// add the zip file name argument
+$parser->addArgument('zipfile', array('description' => 'zip file name'));
+
+// run the parser
+try {
+ $result = $parser->parse();
+ // write your program here...
+ print_r($result->options);
+ print_r($result->args);
+} catch (Exception $exc) {
+ $parser->displayError($exc->getMessage());
+}
+
+?>
View
49 examples/ex2.php
@@ -0,0 +1,49 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * This example demonstrate the use of xml definitions files with
+ * PEAR2_Console_CommandLine, the result is the same as for the ex1.php file.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+// uncomment this when package won't be in the SandBox anymore
+// $basedir = __DIR__ . '/..';
+$basedir = __DIR__ . '/../..';
+
+// Include PEAR2 autoload
+require_once $basedir . '/autoload.php';
+
+// create the parser from xml file
+$xmlfile = __DIR__ . DIRECTORY_SEPARATOR . 'ex2.xml';
+$parser = PEAR2_Console_CommandLine::fromXmlFile($xmlfile);
+
+
+// run the parser
+try {
+ $result = $parser->parse();
+ // write your program here...
+ print_r($result->options);
+ print_r($result->args);
+} catch (Exception $exc) {
+ $parser->displayError($exc->getMessage());
+}
+
+?>
View
34 examples/ex2.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes"?>
+<command>
+ <description>zip given files using the php zip module.</description>
+ <version>1.0.0</version>
+ <option name="choice">
+ <short_name>-c</short_name>
+ <long_name>--choice</long_name>
+ <description>choice option</description>
+ <action>StoreString</action>
+ <choices>
+ <choice>ham</choice>
+ <choice>spam</choice>
+ </choices>
+ </option>
+ <option name="verbose">
+ <short_name>-v</short_name>
+ <long_name>--verbose</long_name>
+ <description>turn on verbose output</description>
+ <action>StoreTrue</action>
+ </option>
+ <option name="delete">
+ <short_name>-d</short_name>
+ <long_name>--delete</long_name>
+ <description>delete original files after zip operation</description>
+ <action>StoreTrue</action>
+ </option>
+ <argument name="files">
+ <description>a list of files to zip together</description>
+ <multiple>true</multiple>
+ </argument>
+ <argument name="zipfile">
+ <description>path to the zip file to generate</description>
+ </argument>
+</command>
View
51 makepackage.php
@@ -0,0 +1,51 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * A full featured package for managing command-line options and arguments
+ * hightly inspired from python optparse module, it allows the developper to
+ * easily build complex command line interfaces.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ */
+
+// ensure that errors will be printed
+error_reporting(E_ALL);
+ini_set('display_errors',true);
+
+// uncomment this when package won't be in the SandBox anymore
+// $basedir = __DIR__ . '/..';
+$basedir = __DIR__ . '/../..';
+
+require_once $basedir . '/autoload.php';
+
+new PEAR2_Pyrus_Developer_PackageFile_PEAR2SVN(
+ __DIR__,
+ 'PEAR2_Console_CommandLine'
+);
+
+$package = new PEAR2_Pyrus_Package('package.xml');
+$outfile = $package->name . '-' . $package->version['release'];
+$creator = new PEAR2_Pyrus_Package_Creator(
+ new PEAR2_Pyrus_Developer_Creator_Phar($outfile . '.tgz', false, Phar::TAR, Phar::GZ),
+ $basedir . '/Exception/src',
+ $basedir . '/Autoload/src',
+ $basedir . '/MultiErrors/src'
+);
+$creator->render($package);
View
136 package.xml
@@ -0,0 +1,136 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<package version="2.1" xmlns="http://pear.php.net/dtd/package-2.1" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.1 http://pear.php.net/dtd/package-2.1.xsd">
+ <name>PEAR2_Console_CommandLine</name>
+ <channel>pear2.php.net</channel>
+ <summary>PEAR2_Console_CommandLine is a full featured package for managing command-line
+</summary>
+ <description>options and arguments highly inspired from python optparse module, it allows
+the developer to easily build complex command line interfaces.
+
+Main features:
+* handles sub commands (ie. $ myscript.php -q subcommand -f file),
+* can be completely built from an xml definition file,
+* generate --help and --version options automatically,
+* can be completely customized,
+* builtin support for i18n,
+* and much more...
+
+</description>
+ <lead>
+ <name>David JEAN LOUIS</name>
+ <user>izi</user>
+ <email>izi@php.net</email>
+ <active>yes</active>
+ </lead>
+ <date>2008-06-08</date>
+ <time>21:20:56</time>
+ <version>
+ <release>0.1.0</release>
+ <api>0.1.0</api>
+ </version>
+ <stability>
+ <release>devel</release>
+ <api>alpha</api>
+ </stability>
+ <license uri="http://www.opensource.org/licenses/bsd-license.php">New BSD License</license>
+ <notes>Initial port of PEAR Console_CommandLine to PEAR2.
+</notes>
+ <contents>
+ <dir name="/">
+ <dir name="data" baseinstalldir="/">
+ <file role="data" name="xmlschema.rng"/>
+ </dir>
+ <dir name="examples">
+ <file role="doc" name="ex1.php"/>
+ <file role="doc" name="ex2.php"/>
+ <file role="doc" name="ex2.xml"/>
+ </dir>
+ <dir name="src" baseinstalldir="PEAR2">
+ <dir name="Console">
+ <dir name="CommandLine">
+ <dir name="Action">
+ <file role="php" name="Callback.php"/>
+ <file role="php" name="Counter.php"/>
+ <file role="php" name="Help.php"/>
+ <file role="php" name="Password.php"/>
+ <file role="php" name="StoreArray.php"/>
+ <file role="php" name="StoreFalse.php"/>
+ <file role="php" name="StoreFloat.php"/>
+ <file role="php" name="StoreInt.php"/>
+ <file role="php" name="StoreString.php"/>
+ <file role="php" name="StoreTrue.php"/>
+ <file role="php" name="Version.php"/>
+ </dir>
+ <dir name="MessageProvider">
+ <file role="php" name="Default.php"/>
+ </dir>
+ <dir name="Outputter">
+ <file role="php" name="Default.php"/>
+ </dir>
+ <dir name="Renderer">
+ <file role="php" name="Default.php"/>
+ </dir>
+ <file role="php" name="Action.php"/>
+ <file role="php" name="Argument.php"/>
+ <file role="php" name="Command.php"/>
+ <file role="php" name="Element.php"/>
+ <file role="php" name="Exception.php"/>
+ <file role="php" name="MessageProvider.php"/>
+ <file role="php" name="Option.php"/>
+ <file role="php" name="Outputter.php"/>
+ <file role="php" name="Renderer.php"/>
+ <file role="php" name="Result.php"/>
+ <file role="php" name="XmlParser.php"/>
+ </dir>
+ <file role="php" name="CommandLine.php"/>
+ </dir>
+ </dir>
+ <dir name="tests" baseinstalldir="/">
+ <file role="test" name="AllTests.php"/>
+ <file role="test" name="console_commandline_accept.phpt"/>
+ <file role="test" name="console_commandline_addargument.phpt"/>
+ <file role="test" name="console_commandline_addcommand.phpt"/>
+ <file role="test" name="console_commandline_addoption.phpt"/>
+ <file role="test" name="console_commandline_addoption_errors_1.phpt"/>
+ <file role="test" name="console_commandline_addoption_errors_2.phpt"/>
+ <file role="test" name="console_commandline_addoption_errors_3.phpt"/>
+ <file role="test" name="console_commandline_addoption_errors_4.phpt"/>
+ <file role="test" name="console_commandline_addoption_errors_5.phpt"/>
+ <file role="test" name="console_commandline_addoption_errors_6.phpt"/>
+ <file role="test" name="console_commandline_addoption_errors_7.phpt"/>
+ <file role="test" name="console_commandline_fromxmlfile.phpt"/>
+ <file role="test" name="console_commandline_fromxmlfile_error.phpt"/>
+ <file role="test" name="console_commandline_fromxmlstring.phpt"/>
+ <file role="test" name="console_commandline_parse_1.phpt"/>
+ <file role="test" name="console_commandline_parse_2.phpt"/>
+ <file role="test" name="console_commandline_parse_3.phpt"/>
+ <file role="test" name="console_commandline_parse_4.phpt"/>
+ <file role="test" name="console_commandline_parse_5.phpt"/>
+ <file role="test" name="console_commandline_parse_6.phpt"/>
+ <file role="test" name="console_commandline_parse_7.phpt"/>
+ <file role="test" name="console_commandline_parse_8.phpt"/>
+ <file role="test" name="console_commandline_parse_9.phpt"/>
+ <file role="test" name="console_commandline_parse_10.phpt"/>
+ <file role="test" name="console_commandline_parse_11.phpt"/>
+ <file role="test" name="console_commandline_parse_12.phpt"/>
+ <file role="test" name="console_commandline_parse_13.phpt"/>
+ <file role="test" name="console_commandline_parse_14.phpt"/>
+ <file role="test" name="console_commandline_parse_15.phpt"/>
+ <file role="test" name="console_commandline_parse_16.phpt"/>
+ <file role="test" name="test.xml"/>
+ <file role="test" name="tests.inc.php"/>
+ </dir>
+ </dir>
+ </contents>
+ <dependencies>
+ <required>
+ <php>
+ <min>5.2.0</min>
+ </php>
+ <pearinstaller>
+ <min>2.0.0a1</min>
+ </pearinstaller>
+ </required>
+ </dependencies>
+ <phprelease/>
+</package>
View
1,029 src/Console/CommandLine.php
@@ -0,0 +1,1029 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * A full featured package for managing command-line options and arguments
+ * hightly inspired from python optparse module, it allows the developper to
+ * easily build complex command line interfaces.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ */
+
+/**
+ * Main class for parsing command line options and arguments.
+ *
+ * There are three ways to create parsers with this class:
+ * <code>
+ * // direct usage
+ * $parser = new PEAR2_Console_CommandLine();
+ *
+ * // with an xml definition file
+ * $parser = PEAR2_Console_CommandLine::fromXmlFile('path/to/file.xml');
+ *
+ * // with an xml definition string
+ * $validXmlString = '..your xml string...';
+ * $parser = PEAR2_Console_CommandLine::fromXmlString($validXmlString);
+ * </code>
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ * @example docs/examples/ex1.php
+ * @example docs/examples/ex2.php
+ */
+class PEAR2_Console_CommandLine
+{
+ // Public properties {{{
+
+ /**
+ * Error messages.
+ *
+ * @var array $errors
+ * @access public
+ */
+ public static $errors = array(
+ 'option_bad_name' => 'option name must be a valid php variable name (got: {$name})',
+ 'argument_bad_name' => 'argument name must be a valid php variable name (got: {$name})',
+ 'option_long_and_short_name_missing' => 'you must provide at least an option short name or long name for option "{$name}"',
+ 'option_bad_short_name' => 'option "{$name}" short name must be a dash followed by a letter (got: "{$short_name}")',
+ 'option_bad_long_name' => 'option "{$name}" long name must be 2 dashes followed by a word (got: "{$long_name}")',
+ 'option_unregistered_action' => 'unregistered action "{$action}" for option "{$name}".',
+ 'option_bad_action' => 'invalid action for option "{$name}".',
+ 'option_invalid_callback' => 'you must provide a valid callback for option "{$name}"',
+ 'action_class_does_not_exists' => 'action "{$name}" class "{$class}" not found, make sure that your class is available before calling PEAR2_Console_CommandLine::registerAction()',
+ 'invalid_xml_file' => 'XML definition file "{$file}" does not exists or is not readable',
+ 'invalid_rng_file' => 'RNG file "{$file}" does not exists or is not readable'
+ );
+
+ /**
+ * The name of the program, if not given it defaults to argv[0].
+ *
+ * @var string $name
+ * @access public
+ */
+ public $name;
+
+ /**
+ * A description text that will be displayed in the help message.
+ *
+ * @var string $description
+ * @access public
+ */
+ public $description = '';
+
+ /**
+ * A string that represents the version of the program, if this property is
+ * not empty and property add_version_option is not set to false, the
+ * command line parser will add a --version option, that will display the
+ * property content.
+ *
+ * @var string $version
+ * @access public
+ */
+ public $version = '';
+
+ /**
+ * Boolean that determine if the command line parser should add the help
+ * (-h, --help) option automatically.
+ *
+ * @var bool $add_help_option
+ * @access public
+ */
+ public $add_help_option = true;
+
+ /**
+ * Boolean that determine if the command line parser should add the version
+ * (-v, --version) option automatically.
+ * Note that the version option is also generated only if the version
+ * property is not empty, it's up to you to provide a version string of
+ * course.
+ *
+ * @var bool $add_version_option
+ * @access public
+ */
+ public $add_version_option = true;
+
+ /**
+ * The command line parser renderer instance.
+ *
+ * @var object that implements PEAR2_Console_CommandLine_Renderer interface
+ * @access protected
+ */
+ public $renderer = false;
+
+ /**
+ * The command line parser outputter instance.
+ *
+ * @var object that implements PEAR2_Console_CommandLine::Outputter interface
+ * @access protected
+ */
+ public $outputter = false;
+
+ /**
+ * The command line message provider instance.
+ *
+ * @var object an instance of PEAR2_Console_CommandLine::Message
+ * @access protected
+ */
+ public $message_provider = false;
+
+ /**
+ * Boolean that tells the parser to be POSIX compliant, POSIX demands the
+ * following behavior: the first non-option stops option processing.
+ *
+ * @var bool $force_posix
+ * @access public
+ */
+ public $force_posix = false;
+
+ /**
+ * An array of PEAR2_Console_CommandLine_Option objects.
+ *
+ * @var array $options
+ * @access public
+ */
+ public $options = array();
+
+ /**
+ * An array of PEAR2_Console_CommandLine_Argument objects.
+ *
+ * @var array $args
+ * @access public
+ */
+ public $args = array();
+
+ /**
+ * An array of PEAR2_Console_CommandLine_Command objects (sub commands).
+ *
+ * @var array $commands
+ * @access public
+ */
+ public $commands = array();
+
+ /**
+ * Parent, only relevant in Command objects but left here for interface
+ * convenience.
+ *
+ * @var object PEAR2_Console_CommandLine
+ * @access public
+ */
+ public $parent = false;
+
+ /**
+ * Array of valid actions for an option, this array will also store user
+ * registered actions.
+ * The array format is:
+ * <pre>
+ * array(
+ * <ActionName:string> => array(<ActionClass:string>, <builtin:bool>)
+ * )
+ *
+ * @var array $actions
+ * @static
+ * @access public
+ */
+ public static $actions = array(
+ 'StoreTrue' => array('PEAR2_Console_CommandLine_Action_StoreTrue', true),
+ 'StoreFalse' => array('PEAR2_Console_CommandLine_Action_StoreFalse', true),
+ 'StoreString' => array('PEAR2_Console_CommandLine_Action_StoreString', true),
+ 'StoreInt' => array('PEAR2_Console_CommandLine_Action_StoreInt', true),
+ 'StoreFloat' => array('PEAR2_Console_CommandLine_Action_StoreFloat', true),
+ 'StoreArray' => array('PEAR2_Console_CommandLine_Action_StoreArray', true),
+ 'Callback' => array('PEAR2_Console_CommandLine_Action_Callback', true),
+ 'Counter' => array('PEAR2_Console_CommandLine_Action_Counter', true),
+ 'Help' => array('PEAR2_Console_CommandLine_Action_Help', true),
+ 'Version' => array('PEAR2_Console_CommandLine_Action_Version', true),
+ 'Password' => array('PEAR2_Console_CommandLine_Action_Password', true)
+ );
+
+ /**
+ * Array of options that must be dispatched at the end.
+ *
+ * @var array $_dispatchLater
+ * @access private
+ */
+ private $_dispatchLater = array();
+
+ // }}}
+ // __construct() {{{
+
+ /**
+ * Constructor.
+ * Example:
+ *
+ * <code>
+ * $parser = new PEAR2_Console_CommandLine(array(
+ * 'name' => 'yourprogram', // defaults to argv[0]
+ * 'description' => 'Description of your program',
+ * 'version' => '0.0.1', // your program version
+ * 'add_help_option' => true, // or false to disable --version option
+ * 'add_version_option' => true, // or false to disable --help option
+ * 'force_posix' => false // or true to force posix compliance
+ * ));
+ * </code>
+ *
+ * @param array $params an optional array of parameters
+ *
+ * @access public
+ */
+ public function __construct(array $params=array())
+ {
+ if (isset($params['name'])) {
+ $this->name = $params['name'];
+ } else {
+ $this->name = $_SERVER['argv'][0];
+ }
+ if (isset($params['description'])) {
+ $this->description = $params['description'];
+ }
+ if (isset($params['version'])) {
+ $this->version = $params['version'];
+ }
+ if (isset($params['add_version_option'])) {
+ $this->add_version_option = $params['add_version_option'];
+ }
+ if (isset($params['add_help_option'])) {
+ $this->add_help_option = $params['add_help_option'];
+ }
+ if (isset($params['force_posix'])) {
+ $this->force_posix = $params['force_posix'];
+ } else if (getenv('POSIXLY_CORRECT')) {
+ $this->force_posix = true;
+ }
+ // set default instances
+ $this->renderer = new PEAR2_Console_CommandLine_Renderer_Default($this);
+ $this->outputter = new PEAR2_Console_CommandLine_Outputter_Default();
+ $this->message_provider = new PEAR2_Console_CommandLine_MessageProvider_Default();
+ }
+
+ // }}}
+ // accept() {{{
+
+ /**
+ * Method to allow PEAR2_Console_CommandLine to accept either:
+ * + a custom renderer,
+ * + a custom outputter,
+ * + or a custom message provider
+ *
+ * @param mixed $instance the custom instance
+ *
+ * @access public
+ * @return void
+ * @throws PEAR2_Console_CommandLine_Exception if wrong argument passed
+ */
+ public function accept($instance)
+ {
+ if ($instance instanceof PEAR2_Console_CommandLine_Renderer) {
+ if (property_exists($instance, 'parser') && !$instance->parser) {
+ $instance->parser = $this;
+ }
+ $this->renderer = $instance;
+ } else if ($instance instanceof PEAR2_Console_CommandLine_Outputter) {
+ $this->outputter = $instance;
+ } else if ($instance instanceof PEAR2_Console_CommandLine_MessageProvider) {
+ $this->message_provider = $instance;
+ } else {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'INVALID_CUSTOM_INSTANCE',
+ array(),
+ $this
+ );
+ }
+ }
+
+ // }}}
+ // fromXmlFile() {{{
+
+ /**
+ * Return a command line parser instance built from an xml file.
+ *
+ * Example:
+ * <code>
+ * require_once 'Console/CommandLine.php';
+ * $parser = PEAR2_Console_CommandLine::fromXmlFile('path/to/file.xml');
+ * $result = $parser->parse();
+ * </code>
+ *
+ * @param string $file path to the xml file
+ *
+ * @return object a PEAR2_Console_CommandLine instance
+ * @access public
+ * @static
+ */
+ public static function fromXmlFile($file)
+ {
+ return PEAR2_Console_CommandLine_XmlParser::parse($file);
+ }
+
+ // }}}
+ // fromXmlString() {{{
+
+ /**
+ * Return a command line parser instance built from an xml string.
+ *
+ * Example:
+ * <code>
+ * require_once 'Console/CommandLine.php';
+ * $xmldata = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
+ * <command>
+ * <description>Compress files</description>
+ * <option name="quiet">
+ * <short_name>-q</short_name>
+ * <long_name>--quiet</long_name>
+ * <description>be quiet when run</description>
+ * <action>StoreTrue/action>
+ * </option>
+ * <argument name="files">
+ * <description>a list of files</description>
+ * <multiple>true</multiple>
+ * </argument>
+ * </command>';
+ * $parser = PEAR2_Console_CommandLine::fromXmlString($xmldata);
+ * $result = $parser->parse();
+ * </code>
+ *
+ * @param string $string the xml data
+ *
+ * @return object a PEAR2_Console_CommandLine instance
+ * @access public
+ * @static
+ */
+ public static function fromXmlString($string)
+ {
+ return PEAR2_Console_CommandLine_XmlParser::parseString($string);
+ }
+
+ // }}}
+ // addArgument() {{{
+
+ /**
+ * Add an argument with the given $name to the command line parser.
+ *
+ * Example:
+ * <code>
+ * $parser = new PEAR2_Console_CommandLine();
+ * // add an array argument
+ * $parser->addArgument('input_files', array('multiple'=>true));
+ * // add a simple argument
+ * $parser->addArgument('output_file');
+ * $result = $parser->parse();
+ * print_r($result->args['input_files']);
+ * print_r($result->args['output_file']);
+ * // will print:
+ * // array('file1', 'file2')
+ * // 'file3'
+ * // if the command line was:
+ * // myscript.php file1 file2 file3
+ * </code>
+ *
+ * In a terminal, the help will be displayed like this:
+ * <code>
+ * $ myscript.php install -h
+ * Usage: myscript.php <input_files...> <output_file>
+ * </code>
+ *
+ * @param mixed $name a string containing the argument name or an
+ * instance of PEAR2_Console_CommandLine_Argument
+ * @param array $params an array containing the argument attributes
+ *
+ * @return object PEAR2_Console_CommandLine_Argument
+ * @access public
+ * @see PEAR2_Console_CommandLine_Command
+ */
+ public function addArgument($name, $params=array())
+ {
+ if ($name instanceof PEAR2_Console_CommandLine_Argument) {
+ $argument = $name;
+ } else {
+ $argument = new PEAR2_Console_CommandLine_Argument($name, $params);
+ }
+ $argument->validate();
+ $this->args[$argument->name] = $argument;
+ return $argument;
+ }
+
+ // }}}
+ // addCommand() {{{
+
+ /**
+ * Add a sub-command to the command line parser.
+ *
+ * Add a command with the given $name to the parser and return the
+ * PEAR2_Console_CommandLine_Command instance, you can then populate the command
+ * with options, configure it, etc... like you would do for the main parser
+ * because the class PEAR2_Console_CommandLine_Command inherits from
+ * PEAR2_Console_CommandLine.
+ *
+ * An example:
+ * <code>
+ * $parser = new PEAR2_Console_CommandLine();
+ * $install_cmd = $parser->addCommand('install');
+ * $install_cmd->addOption(
+ * 'verbose',
+ * array(
+ * 'short_name' => '-v',
+ * 'long_name' => '--verbose',
+ * 'description' => 'be noisy when installing stuff',
+ * 'action' => 'StoreTrue'
+ * )
+ * );
+ * $parser->parse();
+ * </code>
+ * Then in a terminal:
+ * <code>
+ * $ myscript.php install -h
+ * Usage: myscript.php install [options]
+ *
+ * Options:
+ * -h, --help display this help message and exit
+ * -v, --verbose be noisy when installing stuff
+ *
+ * $ myscript.php install --verbose
+ * Installing whatever...
+ * $
+ * </code>
+ *
+ * @param mixed $name a string containing the command name or an
+ * instance of PEAR2_Console_CommandLine_Command
+ * @param array $params an array containing the command attributes
+ *
+ * @return object PEAR2_Console_CommandLine_Command
+ * @access public
+ * @see PEAR2_Console_CommandLine_Command
+ */
+ public function addCommand($name, $params=array())
+ {
+ if ($name instanceof PEAR2_Console_CommandLine_Command) {
+ $command = $name;
+ } else {
+ $params['name'] = $name;
+ $command = new PEAR2_Console_CommandLine_Command($params);
+ }
+ $command->parent = $this;
+ $this->commands[$command->name] = $command;
+ return $command;
+ }
+
+ // }}}
+ // addOption() {{{
+
+ /**
+ * Add an option to the command line parser.
+ *
+ * Add an option with the name (variable name) $optname and set its
+ * attributes with the array $params, then return the
+ * PEAR2_Console_CommandLine_Option instance created.
+ * The method accepts another form: you can directly pass a
+ * PEAR2_Console_CommandLine_Option object as the sole argument, this allows to
+ * contruct the option separately, in order to reuse an option in
+ * different command line parsers or commands for example.
+ *
+ * Example:
+ * <code>
+ * $parser = new PEAR2_Console_CommandLine();
+ * $parser->addOption('path', array(
+ * 'short_name' => '-p', // a short name
+ * 'long_name' => '--path', // a long name
+ * 'description' => 'path to the dir', // a description msg
+ * 'action' => 'StoreString',
+ * 'default' => '/tmp' // a default value
+ * ));
+ * $parser->parse();
+ * </code>
+ *
+ * In a terminal, the help will be displayed like this:
+ * <code>
+ * $ myscript.php --help
+ * Usage: myscript.php [options]
+ *
+ * Options:
+ * -h, --help display this help message and exit
+ * -p, --path path to the dir
+ *
+ * </code>
+ *
+ * Various methods to specify an option, these 3 commands are equivalent:
+ * <code>
+ * $ myscript.php --path=some/path
+ * $ myscript.php -p some/path
+ * $ myscript.php -psome/path
+ * </code>
+ *
+ * @param mixed $name a string containing the option name or an
+ * instance of PEAR2_Console_CommandLine_Option
+ * @param array $params an array containing the option attributes
+ *
+ * @return object PEAR2_Console_CommandLine_Option
+ * @access public
+ * @see PEAR2_Console_CommandLine_Option
+ */
+ public function addOption($name, $params=array())
+ {
+ if ($name instanceof PEAR2_Console_CommandLine_Option) {
+ $opt = $name;
+ } else {
+ $opt = new PEAR2_Console_CommandLine_Option($name, $params);
+ }
+ $opt->validate();
+ $this->options[$opt->name] = $opt;
+ return $opt;
+ }
+
+ // }}}
+ // displayError() {{{
+
+ /**
+ * Display an error to the user and exit with $exitCode.
+ *
+ * @param string $error the error message
+ * @param int $exitCode the exit code number
+ *
+ * @return void
+ * @access public
+ */
+ public function displayError($error, $exitCode = 1)
+ {
+ $this->outputter->stderr($this->renderer->error($error));
+ exit($exitCode);
+ }
+
+ // }}}
+ // displayUsage() {{{
+
+ /**
+ * Display the usage help message to the user and exit with $exitCode
+ *
+ * @param int $exitCode the exit code number
+ *
+ * @return void
+ * @access public
+ */
+ public function displayUsage($exitCode = 1)
+ {
+ $this->outputter->stderr($this->renderer->usage());
+ exit($exitCode);
+ }
+
+ // }}}
+ // displayVersion() {{{
+
+ /**
+ * Display the program version to the user
+ *
+ * @return void
+ * @access public
+ */
+ public function displayVersion()
+ {
+ $this->outputter->stdout($this->renderer->version());
+ exit(0);
+ }
+
+ // }}}
+ // findOption() {{{
+
+ /**
+ * Find the option that matches the given short_name (ex: -v), long_name
+ * (ex: --verbose) or name (ex: verbose).
+ *
+ * @param string $str the option identifier
+ *
+ * @return mixed a PEAR2_Console_CommandLine_Option instance or false
+ * @access public
+ */
+ public function findOption($str)
+ {
+ $str = trim($str);
+ if ($str === '') {
+ return false;
+ }
+ $matches = array();
+ foreach ($this->options as $opt) {
+ if ($opt->short_name == $str || $opt->long_name == $str ||
+ $opt->name == $str) {
+ // exact match
+ return $opt;
+ }
+ if (substr($opt->long_name, 0, strlen($str)) === $str) {
+ // abbreviated long option
+ $matches[] = $opt;
+ }
+ }
+ if ($count = count($matches)) {
+ if ($count > 1) {
+ $matches_str = '';
+ $padding = '';
+ foreach ($matches as $opt) {
+ $matches_str .= $padding . $opt->long_name;
+ $padding = ', ';
+ }
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'OPTION_AMBIGUOUS',
+ array('name' => $str, 'matches' => $matches_str),
+ $this
+ );
+ }
+ return $matches[0];
+ }
+ return false;
+ }
+ // }}}
+ // registerAction() {{{
+
+ /**
+ * Register a custom action for the parser, an example:
+ *
+ * <code>
+ * <?php
+ *
+ * // in this example we create a "range" action:
+ * // the user will be able to enter something like:
+ * // $ <program> -r 1,5
+ * // and in the result we will have:
+ * // $result->options['range']: array(1, 5)
+ *
+ * require_once 'Console/CommandLine.php';
+ * require_once 'Console/CommandLine/Action.php';
+ *
+ * class ActionRange extends PEAR2_Console_CommandLine_Action
+ * {
+ * public function execute($value=false, $params=array())
+ * {
+ * $range = explode(',', str_replace(' ', '', $value));
+ * if (count($range) != 2) {
+ * throw new Exception(sprintf(
+ * 'Option "%s" must be 2 integers separated by a comma',
+ * $this->option->name
+ * ));
+ * }
+ * $this->setResult($range);
+ * }
+ * }
+ * // then we can register our action
+ * PEAR2_Console_CommandLine::registerAction('Range', 'ActionRange');
+ * // and now our action is available !
+ * $parser = new PEAR2_Console_CommandLine();
+ * $parser->addOption('range', array(
+ * 'short_name' => '-r',
+ * 'long_name' => '--range',
+ * 'action' => 'Range', // note our custom action
+ * 'description' => 'A range of two integers separated by a comma'
+ * ));
+ * // etc...
+ *
+ * ?>
+ * </code>
+ *
+ * @param string $name the name of the custom action
+ * @param string $class the class name of the custom action
+ *
+ * @return void
+ * @access public
+ * @static
+ */
+ public static function registerAction($name, $class)
+ {
+ if (!isset(self::$actions[$name])) {
+ if (!class_exists($class)) {
+ self::triggerError('action_class_does_not_exists',
+ E_USER_ERROR,
+ array('{$name}' => $name, '{$class}' => $class));
+ }
+ self::$actions[$name] = array($class, false);
+ }
+ }
+
+ // }}}
+ // triggerError() {{{
+
+ /**
+ * A wrapper for programming errors triggering.
+ *
+ * @param string $msgId identifier of the message
+ * @param int $level the php error level
+ * @param array $params an array of search=>replaces entries
+ *
+ * @return void
+ * @access public
+ * @static
+ */
+ public static function triggerError($msgId, $level, $params=array())
+ {
+ if (isset(self::$errors[$msgId])) {
+ $msg = str_replace(array_keys($params),
+ array_values($params), self::$errors[$msgId]);
+ trigger_error($msg, $level);
+ } else {
+ trigger_error('unknown error', $level);
+ }
+ }
+
+ // }}}
+ // parse() {{{
+
+ /**
+ * Parse the command line arguments and return a PEAR2_Console_CommandLine_Result
+ * object.
+ *
+ * @param integer $userArgc number of arguments (optional)
+ * @param array $userArgv array containing arguments (optional)
+ * @param integer $beginAt beginning index of the argv array (optional)
+ *
+ * @return object PEAR2_Console_CommandLine_Result
+ * @access public
+ * @throws Exception on user errors
+ */
+ public function parse($userArgc=null, $userArgv=null, $beginAt=0)
+ {
+ // add "auto" options help and version if needed
+ if ($this->add_help_option) {
+ $this->addOption('help', array(
+ 'short_name' => '-h',
+ 'long_name' => '--help',
+ 'description' => 'show this help message and exit',
+ 'action' => 'Help'
+ ));
+ }
+ if ($this->add_version_option && !empty($this->version)) {
+ $this->addOption('version', array(
+ 'long_name' => '--version',
+ 'description' => 'show the program version and exit',
+ 'action' => 'Version'
+ ));
+ }
+ $argc = ($userArgc === null) ?
+ (isset($argc) ? $argc : $_SERVER['argc']) : $userArgc;
+ $argv = ($userArgv === null) ?
+ (isset($argv) ? $argv : $_SERVER['argv']) : $userArgv;
+ // case of a subcommand, skip main program args
+ for ($i=0; $i<$beginAt; $i++) {
+ $argc--;
+ array_shift($argv);
+ }
+ // remove script name
+ array_shift($argv);
+ $argc--;
+ // will contain aruments
+ $args = array();
+ // build an empty result
+ $result = new PEAR2_Console_CommandLine_Result();
+ foreach ($this->options as $name=>$option) {
+ $result->options[$name] = $option->default;
+ }
+ // parse command line tokens
+ $i = 0;
+ while (++$i && $argc--) {
+ $token = array_shift($argv);
+ try {
+ if (isset($this->commands[$token])) {
+ $result->command_name = $token;
+ $result->command = $this->commands[$token]->parse(null,
+ null, $i);
+ break;
+ } else {
+ $this->parseToken($token, $result, $args, $argc);
+ }
+ } catch (Exception $exc) {
+ throw $exc;
+ }
+ }
+ // minimum argument number check
+ $argnum = count($this->args);
+ if (count($args) < $argnum) {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'ARGUMENT_REQUIRED',
+ array('argnum' => $argnum, 'plural' => $argnum>1 ? 's': ''),
+ $this
+ );
+ }
+ // handle arguments
+ $c = count($this->args);
+ foreach ($this->args as $name=>$arg) {
+ $c--;
+ if ($arg->multiple) {
+ $result->args[$name] = $c ? array_splice($args, 0, -$c) : $args;
+ } else {
+ $result->args[$name] = array_shift($args);
+ }
+ }
+ // dispatch deferred options
+ foreach ($this->_dispatchLater as $optArray) {
+ $optArray[0]->dispatchAction($optArray[1], $optArray[2], $this);
+ }
+ return $result;
+ }
+
+ // }}}
+ // parseToken() {{{
+
+ /**
+ * Parse the command line token and modify *by reference* the $options and
+ * $args arrays.
+ *
+ * @param string $token the command line token to parse
+ * @param object $result the PEAR2_Console_CommandLine_Result instance
+ * @param array &$args the argv array
+ * @param int $argc number of lasting args
+ *
+ * @return void
+ * @access protected
+ * @throws Exception on user errors
+ */
+ protected function parseToken($token, $result, &$args, $argc)
+ {
+ static $lastopt = false;
+ static $stopflag = false;
+ $last = $argc === 0;
+ $token = trim($token);
+ if (!$stopflag && $lastopt) {
+ if (substr($token, 0, 1) == '-') {
+ if ($lastopt->argument_optional) {
+ $this->_dispatchAction($lastopt, '', $result);
+ if ($lastopt->action != 'StoreArray') {
+ $lastopt = false;
+ }
+ } else if (isset($result->options[$lastopt->name])) {
+ // case of an option that expect a list of args
+ $lastopt = false;
+ } else {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'OPTION_VALUE_REQUIRED',
+ array('name' => $lastopt->name),
+ $this
+ );
+ }
+ } else {
+ // when a StoreArray option is positioned last, the behavior
+ // is to consider that if there's already an element in the
+ // array, and the commandline expects one or more args, we
+ // leave last tokens to arguments
+ if ($lastopt->action == 'StoreArray' &&
+ !empty($result->options[$lastopt->name]) &&
+ count($this->args) > ($argc + count($args))) {
+ $args[] = $token;
+ return;
+ }
+ $this->_dispatchAction($lastopt, $token, $result);
+ if ($lastopt->action != 'StoreArray') {
+ $lastopt = false;
+ }
+ return;
+ }
+ }
+ if (!$stopflag && substr($token, 0, 2) == '--') {
+ // a long option
+ $optkv = explode('=', $token, 2);
+ if (trim($optkv[0]) == '--') {
+ // the special argument "--" forces in all cases the end of
+ // option scanning.
+ $stopflag = true;
+ return;
+ }
+ $opt = $this->findOption($optkv[0]);
+ if (!$opt) {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'OPTION_UNKNOWN',
+ array('name' => $optkv[0]),
+ $this
+ );
+ }
+ $value = isset($optkv[1]) ? $optkv[1] : false;
+ if (!$opt->expectsArgument() && $value !== false) {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'OPTION_VALUE_UNEXPECTED',
+ array('name' => $opt->name, 'value' => $value),
+ $this
+ );
+ }
+ if ($opt->expectsArgument() && $value === false) {
+ // maybe the long option argument is separated by a space, if
+ // this is the case it will be the next arg
+ if ($last && !$opt->argument_optional) {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'OPTION_VALUE_REQUIRED',
+ array('name' => $opt->name),
+ $this
+ );
+ }
+ // we will have a value next time
+ $lastopt = $opt;
+ return;
+ }
+ if ($opt->action == 'StoreArray') {
+ $lastopt = $opt;
+ }
+ $this->_dispatchAction($opt, $value, $result);
+ } else if (!$stopflag && substr($token, 0, 1) == '-') {
+ // a short option
+ $optname = substr($token, 0, 2);
+ if ($optname == '-') {
+ // special case of "-" passed on the command line, it should be
+ // treated as an argument
+ $args[] = $optname;
+ return;
+ }
+ $opt = $this->findOption($optname);
+ if (!$opt) {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'OPTION_UNKNOWN',
+ array('name' => $optname),
+ $this
+ );
+ }
+ // parse other options or set the value
+ // in short: handle -f<value> and -f <value>
+ $next = substr($token, 2, 1);
+ // check if we must wait for a value
+ if ($next === false) {
+ if ($opt->expectsArgument()) {
+ if ($last && !$opt->argument_optional) {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'OPTION_VALUE_REQUIRED',
+ array('name' => $opt->name),
+ $this
+ );
+ }
+ // we will have a value next time
+ $lastopt = $opt;
+ return;
+ }
+ $value = false;
+ } else {
+ if (!$opt->expectsArgument()) {
+ if ($nextopt = $this->findOption('-' . $next)) {
+ $this->_dispatchAction($opt, false, $result);
+ $this->parseToken('-' . substr($token, 2), $result,
+ $args, $last);
+ return;
+ } else {
+ throw PEAR2_Console_CommandLine_Exception::build(
+ 'OPTION_UNKNOWN',
+ array('name' => $next),
+ $this
+ );
+ }
+ }
+ if ($opt->action == 'StoreArray') {
+ $lastopt = $opt;
+ }
+ $value = substr($token, 2);
+ }
+ $this->_dispatchAction($opt, $value, $result);
+ } else {
+ // We have an argument.
+ // if we are in POSIX compliant mode, we must set the stop flag to
+ // true in order to stop option parsing.
+ if (!$stopflag && $this->force_posix) {
+ $stopflag = true;
+ }
+ $args[] = $token;
+ }
+ }
+
+ // }}}
+ // _dispatchAction() {{{
+
+ /**
+ * Dispatch the given option or store the option to dispatch it later.
+ *
+ * @param object $option an instance of PEAR2_Console_CommandLine_Option
+ * @param string $token the command line token to parse
+ * @param object $result the PEAR2_Console_CommandLine_Result instance
+ *
+ * @return void
+ * @access protected
+ * @throws Exception on user errors
+ */
+ private function _dispatchAction($option, $token, $result)
+ {
+ if ($option->action == 'Password') {
+ $this->_dispatchLater[] = array($option, $token, $result);
+ } else {
+ $option->dispatchAction($token, $result, $this);
+ }
+ }
+ // }}}
+}
+
+?>
View
135 src/Console/CommandLine/Action.php
@@ -0,0 +1,135 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+/**
+ * F
+ * Class that represent an option action.
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ * @abstract
+ */
+abstract class PEAR2_Console_CommandLine_Action
+{
+ // Properties {{{
+
+ /**
+ * A reference to the result instance.
+ *
+ * @var object PEAR2_Console_CommandLine_Result $result
+ * @access protected
+ */
+ protected $result;
+
+ /**
+ * A reference to the option instance.
+ *
+ * @var object PEAR2_Console_CommandLine_Option $option
+ * @access protected
+ */
+ protected $option;
+
+ /**
+ * A reference to the parser instance.
+ *
+ * @var object PEAR2_Console_CommandLine $parser
+ * @access protected
+ */
+ protected $parser;
+
+ // }}}
+ // __construct() {{{
+
+ /**
+ * Constructor
+ *
+ * @param object $result a PEAR2_Console_CommandLine_Result instance
+ * @param object $option a PEAR2_Console_CommandLine_Option instance
+ * @param object $parser a PEAR2_Console_CommandLine instance
+ *
+ * @access public
+ */
+ public function __construct($result, $option, $parser)
+ {
+ $this->result = $result;
+ $this->option = $option;
+ $this->parser = $parser;
+ }
+
+ // }}}
+ // getResult() {{{
+
+ /**
+ * Convenience method to retrieve the value of result->options[name].
+ *
+ * @return mixed $value the assigned value or null
+ * @access public
+ */
+ public function getResult()
+ {
+ if (isset($this->result->options[$this->option->name])) {
+ return $this->result->options[$this->option->name];
+ }
+ return null;
+ }
+
+ // }}}
+ // setResult() {{{
+
+ /**
+ * Convenience method to assign the result->options[name] value.
+ *
+ * @param mixed $result the option value
+ *
+ * @return void
+ * @access public
+ */
+ public function setResult($result)
+ {
+ $this->result->options[$this->option->name] = $result;
+ }
+
+ // }}}
+ // execute() {{{
+
+ /**
+ * Execute the action with the value entered by the user.
+ *
+ * @param mixed $value the option value
+ * @param array $params an optional array of parameters
+ *
+ * @return string
+ * @access public
+ * @abstract
+ */
+ abstract public function execute($value=false, $params=array());
+ // }}}
+}
+
+?>
View
79 src/Console/CommandLine/Action/Callback.php
@@ -0,0 +1,79 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+// require_once 'Console/CommandLine/Action.php';
+
+/**
+ * Class that represent the Callback action.
+ *
+ * The result option array entry value is set to the return value of the
+ * callback defined in the option.
+ *
+ * There are two steps to defining a callback option:
+ * - define the option itself using the callback action
+ * - write the callback; this is a function (or method) that takes five
+ * arguments, as described below.
+ *
+ * All callbacks are called as follows:
+ * <code>
+ * callable_func(
+ * $value, // the value of the option
+ * $option_instance, // the option instance
+ * $result_instance, // the result instance
+ * $parser_instance, // the parser instance
+ * $params // an array of params as specified in the option
+ * );
+ * </code>
+ * and *must* return the option value.
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ */
+class PEAR2_Console_CommandLine_Action_Callback extends PEAR2_Console_CommandLine_Action
+{
+ // execute() {{{
+
+ /**
+ * Execute the action with the value entered by the user.
+ *
+ * @param mixed $value the value of the option
+ * @param array $params an optional array of parameters
+ *
+ * @return string
+ * @access public
+ */
+ public function execute($value=false, $params=array())
+ {
+ $this->setResult(call_user_func($this->option->callback, $value,
+ $this->option, $this->result, $this->parser, $params));
+ }
+ // }}}
+}
+
+?>
View
85 src/Console/CommandLine/Action/Counter.php
@@ -0,0 +1,85 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+// require_once 'Console/CommandLine/Action.php';
+
+/**
+ * Class that represent the Version action.
+ *
+ * The execute methode add 1 to the value of the result option array entry.
+ * The value is incremented each time the option is found, for example
+ * with an option defined like that:
+ *
+ * <code>
+ * $parser->addOption(
+ * 'verbose',
+ * array(
+ * 'short_name' => '-v',
+ * 'action' => 'Counter'
+ * )
+ * );
+ * </code>
+ * If the user type:
+ * <code>
+ * $ script.php -v -v -v
+ * </code>
+ * or:
+ * <code>
+ * $ script.php -vvv
+ * </code>
+ * the verbose variable will be set to to 3.
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ */
+class PEAR2_Console_CommandLine_Action_Counter extends PEAR2_Console_CommandLine_Action
+{
+ // execute() {{{
+
+ /**
+ * Execute the action with the value entered by the user.
+ *
+ * @param mixed $value the option value
+ * @param array $params an optional array of parameters
+ *
+ * @return string
+ * @access public
+ */
+ public function execute($value=false, $params=array())
+ {
+ $result = $this->getResult();
+ if ($result === null) {
+ $result = 0;
+ }
+ $this->setResult(++$result);
+ }
+ // }}}
+}
+
+?>
View
59 src/Console/CommandLine/Action/Help.php
@@ -0,0 +1,59 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+// require_once 'Console/CommandLine/Action.php';
+
+/**
+ * Class that represent the Help action, a special action that displays the
+ * help message, telling the user how to use the program.
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ */
+class PEAR2_Console_CommandLine_Action_Help extends PEAR2_Console_CommandLine_Action
+{
+ // execute() {{{
+
+ /**
+ * Execute the action with the value entered by the user.
+ *
+ * @param mixed $value the option value
+ * @param array $params an optional array of parameters
+ *
+ * @return string
+ * @access public
+ */
+ public function execute($value=false, $params=array())
+ {
+ return $this->parser->displayUsage();
+ }
+ // }}}
+}
+
+?>
View
89 src/Console/CommandLine/Action/Password.php
@@ -0,0 +1,89 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+// require_once 'Console/CommandLine/Action.php';
+
+/**
+ * Class that represent the Password action, a special action that allow the
+ * user to specify the password on the commandline or to be prompted for
+ * entering it.
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ */
+class PEAR2_Console_CommandLine_Action_Password extends PEAR2_Console_CommandLine_Action
+{
+ // execute() {{{
+
+ /**
+ * Execute the action with the value entered by the user.
+ *
+ * @param mixed $value the option value
+ * @param array $params an array of optional parameters
+ *
+ * @return string
+ * @access public
+ */
+ public function execute($value=false, $params=array())
+ {
+ $this->setResult(empty($value) ? $this->_promptPassword() : $value);
+ }
+ // }}}
+ // _promptPassword() {{{
+
+ /**
+ * Prompt the password to the user without echoing it.
+ * XXX not echo-ing the password does not work on windows.
+ *
+ * @return string
+ * @access private
+ */
+ private function _promptPassword()
+ {
+ if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
+ fwrite(STDOUT,
+ $this->parser->message_provider->get('PASSWORD_PROMPT_ECHO'));
+ @flock(STDIN, LOCK_EX);
+ $passwd = fgets(STDIN);
+ @flock(STDIN, LOCK_UN);
+ } else {
+ fwrite(STDOUT, $this->parser->message_provider->get('PASSWORD_PROMPT'));
+ // disable echoing
+ system('stty -echo');
+ @flock(STDIN, LOCK_EX);
+ $passwd = fgets(STDIN);
+ @flock(STDIN, LOCK_UN);
+ system('stty echo');
+ }
+ return trim($passwd);
+ }
+ // }}}
+}
+
+?>
View
66 src/Console/CommandLine/Action/StoreArray.php
@@ -0,0 +1,66 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+// require_once 'Console/CommandLine/Action.php';
+
+/**
+ * Class that represent the StoreArray action.
+ *
+ * The execute method appends the value of the option entered by the user to
+ * the result option array entry.
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ */
+class PEAR2_Console_CommandLine_Action_StoreArray extends PEAR2_Console_CommandLine_Action
+{
+ // execute() {{{
+
+ /**
+ * Execute the action with the value entered by the user.
+ *
+ * @param mixed $value the option value
+ * @param array $params an optional array of parameters
+ *
+ * @return string
+ * @access public
+ */
+ public function execute($value=false, $params=array())
+ {
+ $result = $this->getResult();
+ if (null === $result) {
+ $result = array();
+ }
+ $result[] = $value;
+ $this->setResult($result);
+ }
+ // }}}
+}
+
+?>
View
62 src/Console/CommandLine/Action/StoreFalse.php
@@ -0,0 +1,62 @@
+<?php
+
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * This file is part of the PEAR2_Console_CommandLine package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This source file is subject to the MIT license that is available
+ * through the world-wide-web at the following URI:
+ * http://opensource.org/licenses/mit-license.php
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version SVN: $Id$
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since File available since release 0.1.0
+ */
+
+// require_once 'Console/CommandLine/Action.php';
+
+/**
+ * Class that represent the StoreFalse action.
+ *
+ * The execute method store the boolean 'false' in the corrsponding result
+ * option array entry (the value is true if the option is not present in the
+ * command line entered by the user).
+ *
+ * @category Console
+ * @package PEAR2_Console_CommandLine
+ * @author David JEAN LOUIS <izimobil@gmail.com>
+ * @copyright 2007 David JEAN LOUIS
+ * @license http://opensource.org/licenses/mit-license.php MIT License
+ * @version Release: @package_version@
+ * @link http://pear.php.net/package/Console_CommandLine
+ * @since Class available since release 0.1.0
+ */
+class PEAR2_Console_CommandLine_Action_StoreFalse extends PEAR2_Console_CommandLine_Action
+{
+ // execute() {{{
+
+ /**
+ * Execute the action with the value entered by the user.
+ *
+ * @param mixed $value the option value
+ * @param array $params an array of optional parameters
+ *
+ * @return string
+ * @access public
+ */
+ public function execute($value=false, $params=array())