pax_global_header00006660000000000000000000000064126240476510014521gustar00rootroot0000000000000052 comment=bcca484a30c68f2744c0779e965a89214914263d php-console-commandline-1.2.0/000077500000000000000000000000001262404765100162345ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/000077500000000000000000000000001262404765100225405ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/000077500000000000000000000000001262404765100241425ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine.php000066400000000000000000001303001262404765100270360ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 * @filesource */ /** * Required unconditionally */ require_once 'Console/CommandLine/Exception.php'; require_once 'Console/CommandLine/Outputter/Default.php'; require_once 'Console/CommandLine/Renderer/Default.php'; require_once 'Console/CommandLine/MessageProvider/Default.php'; /** * Main class for parsing command line options and arguments. * * There are three ways to create parsers with this class: * * // direct usage * $parser = new Console_CommandLine(); * * // with an xml definition file * $parser = Console_CommandLine::fromXmlFile('path/to/file.xml'); * * // with an xml definition string * $validXmlString = '..your xml string...'; * $parser = Console_CommandLine::fromXmlString($validXmlString); * * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @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 Console_CommandLine { // Public properties {{{ /** * Error messages. * * @var array $errors Error messages * @todo move this to Console_CommandLine_MessageProvider */ 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})', 'argument_no_default' => 'only optional arguments can have a default value', '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 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 Name of your program */ public $name; /** * A description text that will be displayed in the help message. * * @var string $description Description of your program */ 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 Whether to add a help option or not */ 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 Whether to add a version option or not */ public $add_version_option = true; /** * Boolean that determine if providing a subcommand is mandatory. * * @var bool $subcommand_required Whether a subcommand is required or not */ public $subcommand_required = false; /** * The command line parser renderer instance. * * @var object that implements Console_CommandLine_Renderer interface * @access protected */ public $renderer = false; /** * The command line parser outputter instance. * * @var Console_CommandLine_Outputter An outputter */ public $outputter = false; /** * The command line message provider instance. * * @var Console_CommandLine_MessageProvider A message provider instance */ 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 Whether to force posix compliance or not */ public $force_posix = false; /** * Boolean that tells the parser to set relevant options default values, * according to the option action. * * @see Console_CommandLine_Option::setDefaults() * @var bool $force_options_defaults Whether to force option default values */ public $force_options_defaults = false; /** * An array of Console_CommandLine_Option objects. * * @var array $options The options array */ public $options = array(); /** * An array of Console_CommandLine_Argument objects. * * @var array $args The arguments array */ public $args = array(); /** * An array of Console_CommandLine_Command objects (sub commands). * * @var array $commands The commands array */ public $commands = array(); /** * Parent, only relevant in Command objects but left here for interface * convenience. * * @var Console_CommandLine The parent instance * @todo move Console_CommandLine::parent to Console_CommandLine_Command */ public $parent = false; /** * Array of valid actions for an option, this array will also store user * registered actions. * * The array format is: *
     * array(
     *      => array(, )
     * )
     * 
* * @var array $actions List of valid actions */ public static $actions = array( 'StoreTrue' => array('Console_CommandLine_Action_StoreTrue', true), 'StoreFalse' => array('Console_CommandLine_Action_StoreFalse', true), 'StoreString' => array('Console_CommandLine_Action_StoreString', true), 'StoreInt' => array('Console_CommandLine_Action_StoreInt', true), 'StoreFloat' => array('Console_CommandLine_Action_StoreFloat', true), 'StoreArray' => array('Console_CommandLine_Action_StoreArray', true), 'Callback' => array('Console_CommandLine_Action_Callback', true), 'Counter' => array('Console_CommandLine_Action_Counter', true), 'Help' => array('Console_CommandLine_Action_Help', true), 'Version' => array('Console_CommandLine_Action_Version', true), 'Password' => array('Console_CommandLine_Action_Password', true), 'List' => array('Console_CommandLine_Action_List', true), ); /** * Custom errors messages for this command * * This array is of the form: * * $messageText, * $messageName => $messageText, * ... * ); * ?> * * * If specified, these messages override the messages provided by the * default message provider. For example: * * 'The argument foo is required.', * ); * ?> * * * @var array * @see Console_CommandLine_MessageProvider_Default */ public $messages = array(); // }}} // {{{ Private properties /** * Array of options that must be dispatched at the end. * * @var array $_dispatchLater Options to be dispatched */ private $_dispatchLater = array(); // }}} // __construct() {{{ /** * Constructor. * Example: * * * $parser = new 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 --help option * 'add_version_option' => true, // or false to disable --version option * 'force_posix' => false // or true to force posix compliance * )); * * * @param array $params An optional array of parameters * * @return void */ public function __construct(array $params = array()) { if (isset($params['name'])) { $this->name = $params['name']; } else if (isset($argv) && count($argv) > 0) { $this->name = $argv[0]; } else if (isset($_SERVER['argv']) && count($_SERVER['argv']) > 0) { $this->name = $_SERVER['argv'][0]; } else if (isset($_SERVER['SCRIPT_NAME'])) { $this->name = basename($_SERVER['SCRIPT_NAME']); } 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['subcommand_required'])) { $this->subcommand_required = $params['subcommand_required']; } if (isset($params['force_posix'])) { $this->force_posix = $params['force_posix']; } else if (getenv('POSIXLY_CORRECT')) { $this->force_posix = true; } if (isset($params['messages']) && is_array($params['messages'])) { $this->messages = $params['messages']; } // set default instances $this->renderer = new Console_CommandLine_Renderer_Default($this); $this->outputter = new Console_CommandLine_Outputter_Default(); $this->message_provider = new Console_CommandLine_MessageProvider_Default(); } // }}} // accept() {{{ /** * Method to allow Console_CommandLine to accept either: * + a custom renderer, * + a custom outputter, * + or a custom message provider * * @param mixed $instance The custom instance * * @return void * @throws Console_CommandLine_Exception if wrong argument passed */ public function accept($instance) { if ($instance instanceof Console_CommandLine_Renderer) { if (property_exists($instance, 'parser') && !$instance->parser) { $instance->parser = $this; } $this->renderer = $instance; } else if ($instance instanceof Console_CommandLine_Outputter) { $this->outputter = $instance; } else if ($instance instanceof Console_CommandLine_MessageProvider) { $this->message_provider = $instance; } else { throw Console_CommandLine_Exception::factory( 'INVALID_CUSTOM_INSTANCE', array(), $this, $this->messages ); } } // }}} // fromXmlFile() {{{ /** * Returns a command line parser instance built from an xml file. * * Example: * * require_once 'Console/CommandLine.php'; * $parser = Console_CommandLine::fromXmlFile('path/to/file.xml'); * $result = $parser->parse(); * * * @param string $file Path to the xml file * * @return Console_CommandLine The parser instance */ public static function fromXmlFile($file) { include_once 'Console/CommandLine/XmlParser.php'; return Console_CommandLine_XmlParser::parse($file); } // }}} // fromXmlString() {{{ /** * Returns a command line parser instance built from an xml string. * * Example: * * require_once 'Console/CommandLine.php'; * $xmldata = ' * * Compress files * * * a list of files * true * * '; * $parser = Console_CommandLine::fromXmlString($xmldata); * $result = $parser->parse(); * * * @param string $string The xml data * * @return Console_CommandLine The parser instance */ public static function fromXmlString($string) { include_once 'Console/CommandLine/XmlParser.php'; return Console_CommandLine_XmlParser::parseString($string); } // }}} // addArgument() {{{ /** * Adds an argument to the command line parser and returns it. * * Adds an argument with the name $name and set its attributes with the * array $params, then return the Console_CommandLine_Argument instance * created. * The method accepts another form: you can directly pass a * Console_CommandLine_Argument object as the sole argument, this allows * you to contruct the argument separately, in order to reuse it in * different command line parsers or commands for example. * * Example: * * $parser = new 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 * * * In a terminal, the help will be displayed like this: * * $ myscript.php install -h * Usage: myscript.php * * * @param mixed $name A string containing the argument name or an * instance of Console_CommandLine_Argument * @param array $params An array containing the argument attributes * * @return Console_CommandLine_Argument the added argument * @see Console_CommandLine_Argument */ public function addArgument($name, $params = array()) { if ($name instanceof Console_CommandLine_Argument) { $argument = $name; } else { include_once 'Console/CommandLine/Argument.php'; $argument = new Console_CommandLine_Argument($name, $params); } $argument->validate(); $this->args[$argument->name] = $argument; return $argument; } // }}} // addCommand() {{{ /** * Adds a sub-command to the command line parser. * * Adds a command with the given $name to the parser and returns the * 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 Console_CommandLine_Command inherits from * Console_CommandLine. * * An example: * * $parser = new 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(); * * Then in a terminal: * * $ 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... * $ * * * @param mixed $name A string containing the command name or an * instance of Console_CommandLine_Command * @param array $params An array containing the command attributes * * @return Console_CommandLine_Command the added subcommand * @see Console_CommandLine_Command */ public function addCommand($name, $params = array()) { if ($name instanceof Console_CommandLine_Command) { $command = $name; } else { include_once 'Console/CommandLine/Command.php'; $params['name'] = $name; $command = new Console_CommandLine_Command($params); // some properties must cascade to the child command if not // passed explicitely. This is done only in this case, because if // we have a Command object we have no way to determine if theses // properties have already been set $cascade = array( 'add_help_option', 'add_version_option', 'outputter', 'message_provider', 'force_posix', 'force_options_defaults' ); foreach ($cascade as $property) { if (!isset($params[$property])) { $command->$property = $this->$property; } } if (!isset($params['renderer'])) { $renderer = clone $this->renderer; $renderer->parser = $command; $command->renderer = $renderer; } } $command->parent = $this; $this->commands[$command->name] = $command; return $command; } // }}} // addOption() {{{ /** * Adds an option to the command line parser and returns it. * * Adds an option with the name $name and set its attributes with the * array $params, then return the Console_CommandLine_Option instance * created. * The method accepts another form: you can directly pass a * Console_CommandLine_Option object as the sole argument, this allows * you to contruct the option separately, in order to reuse it in different * command line parsers or commands for example. * * Example: * * $parser = new 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(); * * * In a terminal, the help will be displayed like this: * * $ myscript.php --help * Usage: myscript.php [options] * * Options: * -h, --help display this help message and exit * -p, --path path to the dir * * * * Various methods to specify an option, these 3 commands are equivalent: * * $ myscript.php --path=some/path * $ myscript.php -p some/path * $ myscript.php -psome/path * * * @param mixed $name A string containing the option name or an * instance of Console_CommandLine_Option * @param array $params An array containing the option attributes * * @return Console_CommandLine_Option The added option * @see Console_CommandLine_Option */ public function addOption($name, $params = array()) { include_once 'Console/CommandLine/Option.php'; if ($name instanceof Console_CommandLine_Option) { $opt = $name; } else { $opt = new Console_CommandLine_Option($name, $params); } $opt->validate(); if ($this->force_options_defaults) { $opt->setDefaults(); } $this->options[$opt->name] = $opt; if (!empty($opt->choices) && $opt->add_list_option) { $this->addOption('list_' . $opt->name, array( 'long_name' => '--list-' . $opt->name, 'description' => $this->message_provider->get( 'LIST_OPTION_MESSAGE', array('name' => $opt->name) ), 'action' => 'List', 'action_params' => array('list' => $opt->choices), )); } return $opt; } // }}} // displayError() {{{ /** * Displays an error to the user via stderr and exit with $exitCode if its * value is not equals to false. * * @param string $error The error message * @param int $exitCode The exit code number (default: 1). If set to * false, the exit() function will not be called * * @return void */ public function displayError($error, $exitCode = 1) { $this->outputter->stderr($this->renderer->error($error)); if ($exitCode !== false) { exit($exitCode); } } // }}} // displayUsage() {{{ /** * Displays the usage help message to the user via stdout and exit with * $exitCode if its value is not equals to false. * * @param int $exitCode The exit code number (default: 0). If set to * false, the exit() function will not be called * * @return void */ public function displayUsage($exitCode = 0) { $this->outputter->stdout($this->renderer->usage()); if ($exitCode !== false) { exit($exitCode); } } // }}} // displayVersion() {{{ /** * Displays the program version to the user via stdout and exit with * $exitCode if its value is not equals to false. * * * @param int $exitCode The exit code number (default: 0). If set to * false, the exit() function will not be called * * @return void */ public function displayVersion($exitCode = 0) { $this->outputter->stdout($this->renderer->version()); if ($exitCode !== false) { exit($exitCode); } } // }}} // findOption() {{{ /** * Finds 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 Console_CommandLine_Option instance or false */ 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 Console_CommandLine_Exception::factory( 'OPTION_AMBIGUOUS', array('name' => $str, 'matches' => $matches_str), $this, $this->messages ); } return $matches[0]; } return false; } // }}} // registerAction() {{{ /** * Registers a custom action for the parser, an example: * * * * // in this example we create a "range" action: * // the user will be able to enter something like: * // $ -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 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 * Console_CommandLine::registerAction('Range', 'ActionRange'); * // and now our action is available ! * $parser = new 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... * * * * @param string $name The name of the custom action * @param string $class The class name of the custom action * * @return void */ 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 * @todo remove Console::triggerError() and use exceptions only */ 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() {{{ /** * Parses the command line arguments and returns a * Console_CommandLine_Result instance. * * @param integer $userArgc Number of arguments (optional) * @param array $userArgv Array containing arguments (optional) * * @return Console_CommandLine_Result The result instance * @throws Exception on user errors */ public function parse($userArgc=null, $userArgv=null) { $this->addBuiltinOptions(); if ($userArgc !== null && $userArgv !== null) { $argc = $userArgc; $argv = $userArgv; } else { list($argc, $argv) = $this->getArgcArgv(); } // build an empty result include_once 'Console/CommandLine/Result.php'; $result = new Console_CommandLine_Result(); if (!($this instanceof Console_CommandLine_Command)) { // remove script name if we're not in a subcommand array_shift($argv); $argc--; } // will contain arguments $args = array(); foreach ($this->options as $name=>$option) { $result->options[$name] = $option->default; } // parse command line tokens while ($argc--) { $token = array_shift($argv); try { if ($cmd = $this->_getSubCommand($token)) { $result->command_name = $cmd->name; $result->command = $cmd->parse($argc, $argv); break; } else { $this->parseToken($token, $result, $args, $argc); } } catch (Exception $exc) { throw $exc; } } // Parse a null token to allow any undespatched actions to be despatched. $this->parseToken(null, $result, $args, 0); // Check if an invalid subcommand was specified. If there are // subcommands and no arguments, but an argument was provided, it is // an invalid subcommand. if ( count($this->commands) > 0 && count($this->args) === 0 && count($args) > 0 ) { throw Console_CommandLine_Exception::factory( 'INVALID_SUBCOMMAND', array('command' => $args[0]), $this, $this->messages ); } // if subcommand_required is set to true we must check that we have a // subcommand. if ( count($this->commands) && $this->subcommand_required && !$result->command_name ) { throw Console_CommandLine_Exception::factory( 'SUBCOMMAND_REQUIRED', array('commands' => implode(array_keys($this->commands), ', ')), $this, $this->messages ); } // minimum argument number check $argnum = 0; foreach ($this->args as $name=>$arg) { if (!$arg->optional) { $argnum++; } } if (count($args) < $argnum) { throw Console_CommandLine_Exception::factory( 'ARGUMENT_REQUIRED', array('argnum' => $argnum, 'plural' => $argnum>1 ? 's': ''), $this, $this->messages ); } // 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); } if (!$result->args[$name] && $arg->optional && $arg->default) { $result->args[$name] = $arg->default; } // check value is in argument choices if (!empty($this->args[$name]->choices)) { foreach ($result->args[$name] as $value) { if (!in_array($value, $arg->choices)) { throw Console_CommandLine_Exception::factory( 'ARGUMENT_VALUE_NOT_VALID', array( 'name' => $name, 'choices' => implode('", "', $arg->choices), 'value' => implode(' ', $result->args[$name]), ), $this, $arg->messages ); } } } } // dispatch deferred options foreach ($this->_dispatchLater as $optArray) { $optArray[0]->dispatchAction($optArray[1], $optArray[2], $this); } return $result; } // }}} // parseToken() {{{ /** * Parses the command line token and modifies *by reference* the $options * and $args arrays. * * @param string $token The command line token to parse * @param object $result The 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; 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 Console_CommandLine_Exception::factory( 'OPTION_VALUE_REQUIRED', array('name' => $lastopt->name), $this, $this->messages ); } } 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)) ) { if (!is_null($token)) { $args[] = $token; } return; } if (!is_null($token) || $lastopt->action == 'Password') { $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 Console_CommandLine_Exception::factory( 'OPTION_UNKNOWN', array('name' => $optkv[0]), $this, $this->messages ); } $value = isset($optkv[1]) ? $optkv[1] : false; if (!$opt->expectsArgument() && $value !== false) { throw Console_CommandLine_Exception::factory( 'OPTION_VALUE_UNEXPECTED', array('name' => $opt->name, 'value' => $value), $this, $this->messages ); } 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 Console_CommandLine_Exception::factory( 'OPTION_VALUE_REQUIRED', array('name' => $opt->name), $this, $this->messages ); } // 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 "-": try to read stdin $args[] = file_get_contents('php://stdin'); return; } $opt = $this->findOption($optname); if (!$opt) { throw Console_CommandLine_Exception::factory( 'OPTION_UNKNOWN', array('name' => $optname), $this, $this->messages ); } // parse other options or set the value // in short: handle -f and -f $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 Console_CommandLine_Exception::factory( 'OPTION_VALUE_REQUIRED', array('name' => $opt->name), $this, $this->messages ); } // 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 Console_CommandLine_Exception::factory( 'OPTION_UNKNOWN', array('name' => $next), $this, $this->messages ); } } 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; } if (!is_null($token)) { $args[] = $token; } } } // }}} // addBuiltinOptions() {{{ /** * Adds the builtin "Help" and "Version" options if needed. * * @return void */ public function addBuiltinOptions() { if ($this->add_help_option) { $helpOptionParams = array( 'long_name' => '--help', 'description' => 'show this help message and exit', 'action' => 'Help' ); if (!($option = $this->findOption('-h')) || $option->action == 'Help') { // short name is available, take it $helpOptionParams['short_name'] = '-h'; } $this->addOption('help', $helpOptionParams); } if ($this->add_version_option && !empty($this->version)) { $versionOptionParams = array( 'long_name' => '--version', 'description' => 'show the program version and exit', 'action' => 'Version' ); if (!$this->findOption('-v')) { // short name is available, take it $versionOptionParams['short_name'] = '-v'; } $this->addOption('version', $versionOptionParams); } } // }}} // getArgcArgv() {{{ /** * Tries to return an array containing argc and argv, or trigger an error * if it fails to get them. * * @return array The argc/argv array * @throws Console_CommandLine_Exception */ protected function getArgcArgv() { if (php_sapi_name() != 'cli') { // we have a web request $argv = array($this->name); if (isset($_REQUEST)) { foreach ($_REQUEST as $key => $value) { if (!is_array($value)) { $value = array($value); } $opt = $this->findOption($key); if ($opt instanceof Console_CommandLine_Option) { // match a configured option $argv[] = $opt->short_name ? $opt->short_name : $opt->long_name; foreach ($value as $v) { if ($opt->expectsArgument()) { $argv[] = isset($_REQUEST[$key]) ? urldecode($v) : $v; } else if ($v == '0' || $v == 'false') { array_pop($argv); } } } else if (isset($this->args[$key])) { // match a configured argument foreach ($value as $v) { $argv[] = isset($_REQUEST[$key]) ? urldecode($v) : $v; } } } } return array(count($argv), $argv); } if (isset($argc) && isset($argv)) { // case of register_argv_argc = 1 return array($argc, $argv); } if (isset($_SERVER['argc']) && isset($_SERVER['argv'])) { return array($_SERVER['argc'], $_SERVER['argv']); } return array(0, array()); } // }}} // _dispatchAction() {{{ /** * Dispatches the given option or store the option to dispatch it later. * * @param Console_CommandLine_Option $option The option instance * @param string $token Command line token to parse * @param Console_CommandLine_Result $result The result instance * * @return void */ private function _dispatchAction($option, $token, $result) { if ($option->action == 'Password') { $this->_dispatchLater[] = array($option, $token, $result); } else { $option->dispatchAction($token, $result, $this); } } // }}} // _getSubCommand() {{{ /** * Tries to return the subcommand that matches the given token or returns * false if no subcommand was found. * * @param string $token Current command line token * * @return mixed An instance of Console_CommandLine_Command or false */ private function _getSubCommand($token) { foreach ($this->commands as $cmd) { if ($cmd->name == $token || in_array($token, $cmd->aliases)) { return $cmd; } } return false; } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/000077500000000000000000000000001262404765100263305ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action.php000066400000000000000000000070071262404765100302620ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Class that represent an option action. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ abstract class Console_CommandLine_Action { // Properties {{{ /** * A reference to the result instance. * * @var Console_CommandLine_Result $result The result instance */ protected $result; /** * A reference to the option instance. * * @var Console_CommandLine_Option $option The action option */ protected $option; /** * A reference to the parser instance. * * @var Console_CommandLine $parser The parser */ protected $parser; // }}} // __construct() {{{ /** * Constructor * * @param Console_CommandLine_Result $result The result instance * @param Console_CommandLine_Option $option The action option * @param Console_CommandLine $parser The current parser * * @return void */ 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 The result value or null */ public function getResult() { if (isset($this->result->options[$this->option->name])) { return $this->result->options[$this->option->name]; } return null; } // }}} // format() {{{ /** * Allow a value to be pre-formatted prior to being used in a choices test. * Setting $value to the new format will keep the formatting. * * @param mixed &$value The value to format * * @return mixed The formatted value */ public function format(&$value) { return $value; } // }}} // setResult() {{{ /** * Convenience method to assign the result->options[name] value. * * @param mixed $result The result value * * @return void */ public function setResult($result) { $this->result->options[$this->option->name] = $result; } // }}} // execute() {{{ /** * Executes the action with the value entered by the user. * All children actions must implement this method. * * @param mixed $value The option value * @param array $params An optional array of parameters * * @return string */ abstract public function execute($value = false, $params = array()); // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/000077500000000000000000000000001262404765100275455ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/Callback.php000066400000000000000000000047121262404765100317560ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ 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: * * 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 * ); * * and *must* return the option value. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_Callback extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { $this->setResult(call_user_func($this->option->callback, $value, $this->option, $this->result, $this->parser, $params)); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/Counter.php000066400000000000000000000043441262404765100317020ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ 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: * * * $parser->addOption( * 'verbose', * array( * 'short_name' => '-v', * 'action' => 'Counter' * ) * ); * * If the user type: * * $ script.php -v -v -v * * or: * * $ script.php -vvv * * the verbose variable will be set to to 3. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_Counter extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { $result = $this->getResult(); if ($result === null) { $result = 0; } $this->setResult(++$result); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/Help.php000066400000000000000000000033321262404765100311470ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ 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 Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_Help extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { return $this->parser->displayUsage(); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/List.php000066400000000000000000000045651262404765100312030ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ require_once 'Console/CommandLine/Action.php'; /** * Class that represent the List action, a special action that simply output an * array as a list. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_List extends Console_CommandLine_Action { // execute() {{{ /** * Executes the action with the value entered by the user. * Possible parameters are: * - message: an alternative message to display instead of the default * message, * - delimiter: an alternative delimiter instead of the comma, * - post: a string to append after the message (default is the new line * char). * * @param mixed $value The option value * @param array $params An optional array of parameters * * @return string */ public function execute($value = false, $params = array()) { $list = isset($params['list']) ? $params['list'] : array(); $msg = isset($params['message']) ? $params['message'] : $this->parser->message_provider->get('LIST_DISPLAYED_MESSAGE'); $del = isset($params['delimiter']) ? $params['delimiter'] : ', '; $post = isset($params['post']) ? $params['post'] : "\n"; $this->parser->outputter->stdout($msg . implode($del, $list) . $post); exit(0); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/Password.php000066400000000000000000000053011262404765100320570ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ 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 Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_Password extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { $this->setResult(empty($value) ? $this->_promptPassword() : $value); } // }}} // _promptPassword() {{{ /** * Prompts the password to the user without echoing it. * * @return string * @todo not echo-ing the password does not work on windows is there a way * to make this work ? */ 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); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/StoreArray.php000066400000000000000000000042731262404765100323570ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ 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 Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_StoreArray extends Console_CommandLine_Action { // Protected properties {{{ /** * Force a clean result when first called, overriding any defaults assigned. * * @var object $firstPass First time this action has been called. */ protected $firstPass = true; // }}} // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { $result = $this->getResult(); if (null === $result || $this->firstPass) { $result = array(); $this->firstPass = false; } $result[] = $value; $this->setResult($result); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/StoreFalse.php000066400000000000000000000034771262404765100323400ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ 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 Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_StoreFalse extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { $this->setResult(false); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/StoreFloat.php000066400000000000000000000044231262404765100323430ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ require_once 'Console/CommandLine/Action.php'; /** * Class that represent the StoreFloat action. * * The execute method store the value of the option entered by the user as a * float in the result option array entry, if the value passed is not a float * an Exception is raised. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_StoreFloat extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 * @throws Console_CommandLine_Exception */ public function execute($value = false, $params = array()) { if (!is_numeric($value)) { include_once 'Console/CommandLine/Exception.php'; throw Console_CommandLine_Exception::factory( 'OPTION_VALUE_TYPE_ERROR', array( 'name' => $this->option->name, 'type' => 'float', 'value' => $value ), $this->parser ); } $this->setResult((float)$value); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/StoreInt.php000066400000000000000000000044221262404765100320270ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ require_once 'Console/CommandLine/Action.php'; /** * Class that represent the StoreInt action. * * The execute method store the value of the option entered by the user as an * integer in the result option array entry, if the value passed is not an * integer an Exception is raised. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_StoreInt extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 * @throws Console_CommandLine_Exception */ public function execute($value = false, $params = array()) { if (!is_numeric($value)) { include_once 'Console/CommandLine/Exception.php'; throw Console_CommandLine_Exception::factory( 'OPTION_VALUE_TYPE_ERROR', array( 'name' => $this->option->name, 'type' => 'int', 'value' => $value ), $this->parser ); } $this->setResult((int)$value); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/StoreString.php000066400000000000000000000034041262404765100325420ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ require_once 'Console/CommandLine/Action.php'; /** * Class that represent the StoreString action. * * The execute method store the value of the option entered by the user as a * string in the result option array entry. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_StoreString extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { $this->setResult((string)$value); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/StoreTrue.php000066400000000000000000000034731262404765100322210ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ require_once 'Console/CommandLine/Action.php'; /** * Class that represent the StoreTrue action. * * The execute method store the boolean 'true' in the corrsponding result * option array entry (the value is false if the option is not present in the * command line entered by the user). * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_StoreTrue extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { $this->setResult(true); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Action/Version.php000066400000000000000000000033121262404765100317020ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ require_once 'Console/CommandLine/Action.php'; /** * Class that represent the Version action, a special action that displays the * version string of the program. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Action_Version extends Console_CommandLine_Action { // execute() {{{ /** * Executes 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 */ public function execute($value = false, $params = array()) { return $this->parser->displayVersion(); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Argument.php000066400000000000000000000056121262404765100306270ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Include base element class. */ require_once 'Console/CommandLine/Element.php'; /** * Class that represent a command line argument. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Argument extends Console_CommandLine_Element { // Public properties {{{ /** * Setting this to true will tell the parser that the argument expects more * than one argument and that argument values should be stored in an array. * * @var boolean $multiple Whether the argument expects multiple values */ public $multiple = false; /** * Setting this to true will tell the parser that the argument is optional * and can be ommited. * Note that it is not a good practice to make arguments optional, it is * the role of the options to be optional, by essence. * * @var boolean $optional Whether the argument is optional or not. */ public $optional = false; /** * An array of possible values for the argument. * * @var array $choices Valid choices for the argument */ public $choices = array(); // }}} // validate() {{{ /** * Validates the argument instance. * * @return void * @throws Console_CommandLine_Exception * @todo use exceptions */ public function validate() { // check if the argument name is valid if (!preg_match('/^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/', $this->name)) { Console_CommandLine::triggerError( 'argument_bad_name', E_USER_ERROR, array('{$name}' => $this->name) ); } if (!$this->optional && $this->default !== null) { Console_CommandLine::triggerError( 'argument_no_default', E_USER_ERROR ); } parent::validate(); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Command.php000066400000000000000000000037671262404765100304340ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * File containing the parent class. */ require_once 'Console/CommandLine.php'; /** * Class that represent a command with option and arguments. * * This class exist just to clarify the interface but at the moment it is * strictly identical to Console_CommandLine class, it could change in the * future though. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Command extends Console_CommandLine { // Public properties {{{ /** * An array of aliases for the subcommand. * * @var array $aliases Aliases for the subcommand. */ public $aliases = array(); // }}} // __construct() {{{ /** * Constructor. * * @param array $params An optional array of parameters * * @return void */ public function __construct($params = array()) { if (isset($params['aliases'])) { $this->aliases = $params['aliases']; } parent::__construct($params); } // }}} } CustomMessageProvider.php000066400000000000000000000042021262404765100332520ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine * @author Michael Gauthier * @copyright 2007 David JEAN LOUIS, 2009 silverorange * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 1.1.0 * @filesource */ /** * Common interfacefor message providers that allow overriding with custom * messages * * Message providers may optionally implement this interface. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @author Michael Gauthier * @copyright 2007 David JEAN LOUIS, 2009 silverorange * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Interface available since release 1.1.0 */ interface Console_CommandLine_CustomMessageProvider { // getWithCustomMesssages() {{{ /** * Retrieves the given string identifier corresponding message. * * For a list of identifiers please see the provided default message * provider. * * @param string $code The string identifier of the message * @param array $vars An array of template variables * @param array $messages An optional array of messages to use. Array * indexes are message codes. * * @return string * @see Console_CommandLine_MessageProvider * @see Console_CommandLine_MessageProvider_Default */ public function getWithCustomMessages( $code, $vars = array(), $messages = array() ); // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Element.php000066400000000000000000000072041262404765100304350ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Class that represent a command line element (an option, or an argument). * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ abstract class Console_CommandLine_Element { // Public properties {{{ /** * The element name. * * @var string $name Element name */ public $name; /** * The name of variable displayed in the usage message, if no set it * defaults to the "name" property. * * @var string $help_name Element "help" variable name */ public $help_name; /** * The element description. * * @var string $description Element description */ public $description; /** * The default value of the element if not provided on the command line. * * @var mixed $default Default value of the option. */ public $default; /** * Custom errors messages for this element * * This array is of the form: * * $messageText, * $messageName => $messageText, * ... * ); * ?> * * * If specified, these messages override the messages provided by the * default message provider. For example: * * 'The argument foo is required.', * ); * ?> * * * @var array * @see Console_CommandLine_MessageProvider_Default */ public $messages = array(); // }}} // __construct() {{{ /** * Constructor. * * @param string $name The name of the element * @param array $params An optional array of parameters * * @return void */ public function __construct($name = null, $params = array()) { $this->name = $name; foreach ($params as $attr => $value) { if (property_exists($this, $attr)) { $this->$attr = $value; } } } // }}} // toString() {{{ /** * Returns the string representation of the element. * * @return string The string representation of the element * @todo use __toString() instead */ public function toString() { return $this->help_name; } // }}} // validate() {{{ /** * Validates the element instance and set it's default values. * * @return void * @throws Console_CommandLine_Exception */ public function validate() { // if no help_name passed, default to name if ($this->help_name == null) { $this->help_name = $this->name; } } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Exception.php000066400000000000000000000057621262404765100310110ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Include the PEAR_Exception class */ require_once 'PEAR/Exception.php'; /** * Interface for custom message provider. */ require_once 'Console/CommandLine/CustomMessageProvider.php'; /** * Class for exceptions raised by the Console_CommandLine package. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Exception extends PEAR_Exception { // Codes constants {{{ /**#@+ * Exception code constants. */ const OPTION_VALUE_REQUIRED = 1; const OPTION_VALUE_UNEXPECTED = 2; const OPTION_VALUE_TYPE_ERROR = 3; const OPTION_UNKNOWN = 4; const ARGUMENT_REQUIRED = 5; const INVALID_SUBCOMMAND = 6; /**#@-*/ // }}} // factory() {{{ /** * Convenience method that builds the exception with the array of params by * calling the message provider class. * * @param string $code The string identifier of the * exception. * @param array $params Array of template vars/values * @param Console_CommandLine $parser An instance of the parser * @param array $messages An optional array of messages * passed to the message provider. * * @return object an instance of Console_CommandLine_Exception */ public static function factory( $code, $params, $parser, array $messages = array() ) { $provider = $parser->message_provider; if ($provider instanceof Console_CommandLine_CustomMessageProvider) { $msg = $provider->getWithCustomMessages( $code, $params, $messages ); } else { $msg = $provider->get($code, $params); } $const = 'Console_CommandLine_Exception::' . $code; $code = defined($const) ? constant($const) : 0; return new Console_CommandLine_Exception($msg, $code); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/MessageProvider.php000066400000000000000000000032411262404765100321400ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Message providers common interface, all message providers must implement * this interface. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ interface Console_CommandLine_MessageProvider { // get() {{{ /** * Retrieves the given string identifier corresponding message. * For a list of identifiers please see the provided default message * provider. * * @param string $code The string identifier of the message * @param array $vars An array of template variables * * @return string * @see Console_CommandLine_MessageProvider_Default */ public function get($code, $vars=array()); // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/MessageProvider/000077500000000000000000000000001262404765100314275ustar00rootroot00000000000000Default.php000066400000000000000000000125451262404765100334540ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/MessageProvider * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * The message provider interface. */ require_once 'Console/CommandLine/MessageProvider.php'; /** * The custom message provider interface. */ require_once 'Console/CommandLine/CustomMessageProvider.php'; /** * Lightweight class that manages messages used by Console_CommandLine package, * allowing the developper to customize these messages, for example to * internationalize a command line frontend. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_MessageProvider_Default implements Console_CommandLine_MessageProvider, Console_CommandLine_CustomMessageProvider { // Properties {{{ /** * Associative array of messages * * @var array $messages */ protected $messages = array( 'OPTION_VALUE_REQUIRED' => 'Option "{$name}" requires a value.', 'OPTION_VALUE_UNEXPECTED' => 'Option "{$name}" does not expect a value (got "{$value}").', 'OPTION_VALUE_NOT_VALID' => 'Option "{$name}" must be one of the following: "{$choices}" (got "{$value}").', 'ARGUMENT_VALUE_NOT_VALID'=> 'Argument "{$name}" must be one of the following: "{$choices}" (got "{$value}").', 'OPTION_VALUE_TYPE_ERROR' => 'Option "{$name}" requires a value of type {$type} (got "{$value}").', 'OPTION_AMBIGUOUS' => 'Ambiguous option "{$name}", can be one of the following: {$matches}.', 'OPTION_UNKNOWN' => 'Unknown option "{$name}".', 'ARGUMENT_REQUIRED' => 'You must provide at least {$argnum} argument{$plural}.', 'PROG_HELP_LINE' => 'Type "{$progname} --help" to get help.', 'PROG_VERSION_LINE' => '{$progname} version {$version}.', 'COMMAND_HELP_LINE' => 'Type "{$progname} --help" to get help on specific command.', 'USAGE_WORD' => 'Usage', 'OPTION_WORD' => 'Options', 'ARGUMENT_WORD' => 'Arguments', 'COMMAND_WORD' => 'Commands', 'PASSWORD_PROMPT' => 'Password: ', 'PASSWORD_PROMPT_ECHO' => 'Password (warning: will echo): ', 'INVALID_CUSTOM_INSTANCE' => 'Instance does not implement the required interface', 'LIST_OPTION_MESSAGE' => 'lists valid choices for option {$name}', 'LIST_DISPLAYED_MESSAGE' => 'Valid choices are: ', 'INVALID_SUBCOMMAND' => 'Command "{$command}" is not valid.', 'SUBCOMMAND_REQUIRED' => 'Please enter one of the following command: {$commands}.', ); // }}} // get() {{{ /** * Retrieve the given string identifier corresponding message. * * @param string $code The string identifier of the message * @param array $vars An array of template variables * * @return string */ public function get($code, $vars = array()) { if (!isset($this->messages[$code])) { return 'UNKNOWN'; } return $this->replaceTemplateVars($this->messages[$code], $vars); } // }}} // getWithCustomMessages() {{{ /** * Retrieve the given string identifier corresponding message. * * @param string $code The string identifier of the message * @param array $vars An array of template variables * @param array $messages An optional array of messages to use. Array * indexes are message codes. * * @return string */ public function getWithCustomMessages( $code, $vars = array(), $messages = array() ) { // get message if (isset($messages[$code])) { $message = $messages[$code]; } elseif (isset($this->messages[$code])) { $message = $this->messages[$code]; } else { $message = 'UNKNOWN'; } return $this->replaceTemplateVars($message, $vars); } // }}} // replaceTemplateVars() {{{ /** * Replaces template vars in a message * * @param string $message The message * @param array $vars An array of template variables * * @return string */ protected function replaceTemplateVars($message, $vars = array()) { $tmpkeys = array_keys($vars); $keys = array(); foreach ($tmpkeys as $key) { $keys[] = '{$' . $key . '}'; } return str_replace($keys, array_values($vars), $message); } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Option.php000066400000000000000000000264271262404765100303240ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required by this class. */ require_once 'Console/CommandLine.php'; require_once 'Console/CommandLine/Element.php'; /** * Class that represent a commandline option. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Option extends Console_CommandLine_Element { // Public properties {{{ /** * The option short name (ex: -v). * * @var string $short_name Short name of the option */ public $short_name; /** * The option long name (ex: --verbose). * * @var string $long_name Long name of the option */ public $long_name; /** * The option action, defaults to "StoreString". * * @var string $action Option action */ public $action = 'StoreString'; /** * An array of possible values for the option. If this array is not empty * and the value passed is not in the array an exception is raised. * This only make sense for actions that accept values of course. * * @var array $choices Valid choices for the option */ public $choices = array(); /** * The callback function (or method) to call for an action of type * Callback, this can be any callable supported by the php function * call_user_func. * * Example: * * * $parser->addOption('myoption', array( * 'short_name' => '-m', * 'long_name' => '--myoption', * 'action' => 'Callback', * 'callback' => 'myCallbackFunction' * )); * * * @var callable $callback The option callback */ public $callback; /** * An associative array of additional params to pass to the class * corresponding to the action, this array will also be passed to the * callback defined for an action of type Callback, Example: * * * // for a custom action * $parser->addOption('myoption', array( * 'short_name' => '-m', * 'long_name' => '--myoption', * 'action' => 'MyCustomAction', * 'action_params' => array('foo'=>true, 'bar'=>false) * )); * * // if the user type: * // $ -m spam * // in your MyCustomAction class the execute() method will be called * // with the value 'spam' as first parameter and * // array('foo'=>true, 'bar'=>false) as second parameter * * * @var array $action_params Additional parameters to pass to the action */ public $action_params = array(); /** * For options that expect an argument, this property tells the parser if * the option argument is optional and can be ommited. * * @var bool $argumentOptional Whether the option arg is optional or not */ public $argument_optional = false; /** * For options that uses the "choice" property only. * Adds a --list- option to the parser that displays the list of * choices for the option. * * @var bool $add_list_option Whether to add a list option or not */ public $add_list_option = false; // }}} // Private properties {{{ /** * When an action is called remember it to allow for multiple calls. * * @var object $action_instance Placeholder for action */ private $_action_instance = null; // }}} // __construct() {{{ /** * Constructor. * * @param string $name The name of the option * @param array $params An optional array of parameters * * @return void */ public function __construct($name = null, $params = array()) { parent::__construct($name, $params); if ($this->action == 'Password') { // special case for Password action, password can be passed to the // commandline or prompted by the parser $this->argument_optional = true; } } // }}} // toString() {{{ /** * Returns the string representation of the option. * * @param string $delim Delimiter to use between short and long option * * @return string The string representation of the option * @todo use __toString() instead */ public function toString($delim = ", ") { $ret = ''; $padding = ''; if ($this->short_name != null) { $ret .= $this->short_name; if ($this->expectsArgument()) { $ret .= ' ' . $this->help_name; } $padding = $delim; } if ($this->long_name != null) { $ret .= $padding . $this->long_name; if ($this->expectsArgument()) { $ret .= '=' . $this->help_name; } } return $ret; } // }}} // expectsArgument() {{{ /** * Returns true if the option requires one or more argument and false * otherwise. * * @return bool Whether the option expects an argument or not */ public function expectsArgument() { if ($this->action == 'StoreTrue' || $this->action == 'StoreFalse' || $this->action == 'Help' || $this->action == 'Version' || $this->action == 'Counter' || $this->action == 'List') { return false; } return true; } // }}} // dispatchAction() {{{ /** * Formats the value $value according to the action of the option and * updates the passed Console_CommandLine_Result object. * * @param mixed $value The value to format * @param Console_CommandLine_Result $result The result instance * @param Console_CommandLine $parser The parser instance * * @return void * @throws Console_CommandLine_Exception */ public function dispatchAction($value, $result, $parser) { $actionInfo = Console_CommandLine::$actions[$this->action]; if (true === $actionInfo[1]) { // we have a "builtin" action $tokens = explode('_', $actionInfo[0]); include_once implode('/', $tokens) . '.php'; } $clsname = $actionInfo[0]; if ($this->_action_instance === null) { $this->_action_instance = new $clsname($result, $this, $parser); } // check value is in option choices if (!empty($this->choices) && !in_array($this->_action_instance->format($value), $this->choices)) { throw Console_CommandLine_Exception::factory( 'OPTION_VALUE_NOT_VALID', array( 'name' => $this->name, 'choices' => implode('", "', $this->choices), 'value' => $value, ), $parser, $this->messages ); } $this->_action_instance->execute($value, $this->action_params); } // }}} // validate() {{{ /** * Validates the option instance. * * @return void * @throws Console_CommandLine_Exception * @todo use exceptions instead */ public function validate() { // check if the option name is valid if (!preg_match('/^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/', $this->name)) { Console_CommandLine::triggerError('option_bad_name', E_USER_ERROR, array('{$name}' => $this->name)); } // call the parent validate method parent::validate(); // a short_name or a long_name must be provided if ($this->short_name == null && $this->long_name == null) { Console_CommandLine::triggerError('option_long_and_short_name_missing', E_USER_ERROR, array('{$name}' => $this->name)); } // check if the option short_name is valid if ($this->short_name != null && !(preg_match('/^\-[a-zA-Z]{1}$/', $this->short_name))) { Console_CommandLine::triggerError('option_bad_short_name', E_USER_ERROR, array( '{$name}' => $this->name, '{$short_name}' => $this->short_name )); } // check if the option long_name is valid if ($this->long_name != null && !preg_match('/^\-\-[a-zA-Z]+[a-zA-Z0-9_\-]*$/', $this->long_name)) { Console_CommandLine::triggerError('option_bad_long_name', E_USER_ERROR, array( '{$name}' => $this->name, '{$long_name}' => $this->long_name )); } // check if we have a valid action if (!is_string($this->action)) { Console_CommandLine::triggerError('option_bad_action', E_USER_ERROR, array('{$name}' => $this->name)); } if (!isset(Console_CommandLine::$actions[$this->action])) { Console_CommandLine::triggerError('option_unregistered_action', E_USER_ERROR, array( '{$action}' => $this->action, '{$name}' => $this->name )); } // if the action is a callback, check that we have a valid callback if ($this->action == 'Callback' && !is_callable($this->callback)) { Console_CommandLine::triggerError('option_invalid_callback', E_USER_ERROR, array('{$name}' => $this->name)); } } // }}} // setDefaults() {{{ /** * Set the default value according to the configured action. * * Note that for backward compatibility issues this method is only called * when the 'force_options_defaults' is set to true, it will become the * default behaviour in the next major release of Console_CommandLine. * * @return void */ public function setDefaults() { if ($this->default !== null) { // already set return; } switch ($this->action) { case 'Counter': case 'StoreInt': $this->default = 0; break; case 'StoreFloat': $this->default = 0.0; break; case 'StoreArray': $this->default = array(); break; case 'StoreTrue': $this->default = false; break; case 'StoreFalse': $this->default = true; break; default: return; } } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Outputter.php000066400000000000000000000032361262404765100310600ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Outputters common interface, all outputters must implement this interface. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ interface Console_CommandLine_Outputter { // stdout() {{{ /** * Processes the output for a message that should be displayed on STDOUT. * * @param string $msg The message to output * * @return void */ public function stdout($msg); // }}} // stderr() {{{ /** * Processes the output for a message that should be displayed on STDERR. * * @param string $msg The message to output * * @return void */ public function stderr($msg); // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Outputter/000077500000000000000000000000001262404765100303435ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Outputter/Default.php000066400000000000000000000036661262404765100324530ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * The Outputter interface. */ require_once 'Console/CommandLine/Outputter.php'; /** * Console_CommandLine default Outputter. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Outputter_Default implements Console_CommandLine_Outputter { // stdout() {{{ /** * Writes the message $msg to STDOUT. * * @param string $msg The message to output * * @return void */ public function stdout($msg) { if (defined('STDOUT')) { fwrite(STDOUT, $msg); } else { echo $msg; } } // }}} // stderr() {{{ /** * Writes the message $msg to STDERR. * * @param string $msg The message to output * * @return void */ public function stderr($msg) { if (defined('STDERR')) { fwrite(STDERR, $msg); } else { echo $msg; } } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Renderer.php000066400000000000000000000033561262404765100306160ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Renderers common interface, all renderers must implement this interface. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ interface Console_CommandLine_Renderer { // usage() {{{ /** * Returns the full usage message. * * @return string The usage message */ public function usage(); // }}} // error() {{{ /** * Returns a formatted error message. * * @param string $error The error message to format * * @return string The error string */ public function error($error); // }}} // version() {{{ /** * Returns the program version string. * * @return string The version string */ public function version(); // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Renderer/000077500000000000000000000000001262404765100300765ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Renderer/Default.php000066400000000000000000000275661262404765100322130ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * The renderer interface. */ require_once 'Console/CommandLine/Renderer.php'; /** * Console_CommandLine default renderer. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Renderer_Default implements Console_CommandLine_Renderer { // Properties {{{ /** * Integer that define the max width of the help text. * * @var integer $line_width Line width */ public $line_width = 75; /** * Integer that define the max width of the help text. * * @var integer $line_width Line width */ public $options_on_different_lines = false; /** * An instance of Console_CommandLine. * * @var Console_CommandLine $parser The parser */ public $parser = false; // }}} // __construct() {{{ /** * Constructor. * * @param object $parser A Console_CommandLine instance * * @return void */ public function __construct($parser = false) { $this->parser = $parser; } // }}} // usage() {{{ /** * Returns the full usage message. * * @return string The usage message */ public function usage() { $ret = ''; if (!empty($this->parser->description)) { $ret .= $this->description() . "\n\n"; } $ret .= $this->usageLine() . "\n"; if (count($this->parser->commands) > 0) { $ret .= $this->commandUsageLine() . "\n"; } if (count($this->parser->options) > 0) { $ret .= "\n" . $this->optionList() . "\n"; } if (count($this->parser->args) > 0) { $ret .= "\n" . $this->argumentList() . "\n"; } if (count($this->parser->commands) > 0) { $ret .= "\n" . $this->commandList() . "\n"; } $ret .= "\n"; return $ret; } // }}} // error() {{{ /** * Returns a formatted error message. * * @param string $error The error message to format * * @return string The error string */ public function error($error) { $ret = 'Error: ' . $error . "\n"; if ($this->parser->add_help_option) { $name = $this->name(); $ret .= $this->wrap($this->parser->message_provider->get('PROG_HELP_LINE', array('progname' => $name))) . "\n"; if (count($this->parser->commands) > 0) { $ret .= $this->wrap($this->parser->message_provider->get('COMMAND_HELP_LINE', array('progname' => $name))) . "\n"; } } return $ret; } // }}} // version() {{{ /** * Returns the program version string. * * @return string The version string */ public function version() { return $this->parser->message_provider->get('PROG_VERSION_LINE', array( 'progname' => $this->name(), 'version' => $this->parser->version )) . "\n"; } // }}} // name() {{{ /** * Returns the full name of the program or the sub command * * @return string The name of the program */ protected function name() { $name = $this->parser->name; $parent = $this->parser->parent; while ($parent) { if (count($parent->options) > 0) { $name = '[' . strtolower($this->parser->message_provider->get('OPTION_WORD', array('plural' => 's'))) . '] ' . $name; } $name = $parent->name . ' ' . $name; $parent = $parent->parent; } return $this->wrap($name); } // }}} // description() {{{ /** * Returns the command line description message. * * @return string The description message */ protected function description() { return $this->wrap($this->parser->description); } // }}} // usageLine() {{{ /** * Returns the command line usage message * * @return string the usage message */ protected function usageLine() { $usage = $this->parser->message_provider->get('USAGE_WORD') . ":\n"; $ret = $usage . ' ' . $this->name(); if (count($this->parser->options) > 0) { $ret .= ' [' . strtolower($this->parser->message_provider->get('OPTION_WORD')) . ']'; } if (count($this->parser->args) > 0) { foreach ($this->parser->args as $name=>$arg) { $arg_str = $arg->help_name; if ($arg->multiple) { $arg_str .= '1 ' . $arg->help_name . '2 ...'; } if ($arg->optional) { $arg_str = '[' . $arg_str . ']'; } $ret .= ' ' . $arg_str; } } return $this->columnWrap($ret, 2); } // }}} // commandUsageLine() {{{ /** * Returns the command line usage message for subcommands. * * @return string The usage line */ protected function commandUsageLine() { if (count($this->parser->commands) == 0) { return ''; } $ret = ' ' . $this->name(); if (count($this->parser->options) > 0) { $ret .= ' [' . strtolower($this->parser->message_provider->get('OPTION_WORD')) . ']'; } $ret .= " "; $hasArgs = false; $hasOptions = false; foreach ($this->parser->commands as $command) { if (!$hasArgs && count($command->args) > 0) { $hasArgs = true; } if (!$hasOptions && ($command->add_help_option || $command->add_version_option || count($command->options) > 0)) { $hasOptions = true; } } if ($hasOptions) { $ret .= ' [options]'; } if ($hasArgs) { $ret .= ' [args]'; } return $this->columnWrap($ret, 2); } // }}} // argumentList() {{{ /** * Render the arguments list that will be displayed to the user, you can * override this method if you want to change the look of the list. * * @return string The formatted argument list */ protected function argumentList() { $col = 0; $args = array(); foreach ($this->parser->args as $arg) { $argstr = ' ' . $arg->toString(); $args[] = array($argstr, $arg->description); $ln = strlen($argstr); if ($col < $ln) { $col = $ln; } } $ret = $this->parser->message_provider->get('ARGUMENT_WORD') . ":"; foreach ($args as $arg) { $text = str_pad($arg[0], $col) . ' ' . $arg[1]; $ret .= "\n" . $this->columnWrap($text, $col+2); } return $ret; } // }}} // optionList() {{{ /** * Render the options list that will be displayed to the user, you can * override this method if you want to change the look of the list. * * @return string The formatted option list */ protected function optionList() { $col = 0; $options = array(); foreach ($this->parser->options as $option) { $delim = $this->options_on_different_lines ? "\n" : ', '; $optstr = $option->toString($delim); $lines = explode("\n", $optstr); $lines[0] = ' ' . $lines[0]; if (count($lines) > 1) { $lines[1] = ' ' . $lines[1]; $ln = strlen($lines[1]); } else { $ln = strlen($lines[0]); } $options[] = array($lines, $option->description); if ($col < $ln) { $col = $ln; } } $ret = $this->parser->message_provider->get('OPTION_WORD') . ":"; foreach ($options as $option) { if (count($option[0]) > 1) { $text = str_pad($option[0][1], $col) . ' ' . $option[1]; $pre = $option[0][0] . "\n"; } else { $text = str_pad($option[0][0], $col) . ' ' . $option[1]; $pre = ''; } $ret .= "\n" . $pre . $this->columnWrap($text, $col+2); } return $ret; } // }}} // commandList() {{{ /** * Render the command list that will be displayed to the user, you can * override this method if you want to change the look of the list. * * @return string The formatted subcommand list */ protected function commandList() { $commands = array(); $col = 0; foreach ($this->parser->commands as $cmdname=>$command) { $cmdname = ' ' . $cmdname; $commands[] = array($cmdname, $command->description, $command->aliases); $ln = strlen($cmdname); if ($col < $ln) { $col = $ln; } } $ret = $this->parser->message_provider->get('COMMAND_WORD') . ":"; foreach ($commands as $command) { $text = str_pad($command[0], $col) . ' ' . $command[1]; if ($aliasesCount = count($command[2])) { $pad = ''; $text .= ' ('; $text .= $aliasesCount > 1 ? 'aliases: ' : 'alias: '; foreach ($command[2] as $alias) { $text .= $pad . $alias; $pad = ', '; } $text .= ')'; } $ret .= "\n" . $this->columnWrap($text, $col+2); } return $ret; } // }}} // wrap() {{{ /** * Wraps the text passed to the method. * * @param string $text The text to wrap * @param int $lw The column width (defaults to line_width property) * * @return string The wrapped text */ protected function wrap($text, $lw=null) { if ($this->line_width > 0) { if ($lw === null) { $lw = $this->line_width; } return wordwrap($text, $lw, "\n", false); } return $text; } // }}} // columnWrap() {{{ /** * Wraps the text passed to the method at the specified width. * * @param string $text The text to wrap * @param int $cw The wrap width * * @return string The wrapped text */ protected function columnWrap($text, $cw) { $tokens = explode("\n", $this->wrap($text)); $ret = $tokens[0]; $chunks = $this->wrap(trim(substr($text, strlen($ret))), $this->line_width - $cw); $tokens = explode("\n", $chunks); foreach ($tokens as $token) { if (!empty($token)) { $ret .= "\n" . str_repeat(' ', $cw) . $token; } } return $ret; } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/Result.php000066400000000000000000000036201262404765100303200ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * A lightweight class to store the result of the command line parsing. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 0.1.0 */ class Console_CommandLine_Result { // Public properties {{{ /** * The result options associative array. * Key is the name of the option and value its value. * * @var array $options Result options array */ public $options = array(); /** * The result arguments array. * * @var array $args Result arguments array */ public $args = array(); /** * Name of the command invoked by the user, false if no command invoked. * * @var string $command_name Result command name */ public $command_name = false; /** * A result instance for the subcommand. * * @var Console_CommandLine_Result Result instance for the subcommand */ public $command = false; // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/Console/CommandLine/XmlParser.php000066400000000000000000000230351262404765100307610ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 * @filesource */ /** * Required file */ require_once 'Console/CommandLine.php'; /** * Parser for command line xml definitions. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @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 Console_CommandLine_XmlParser { // parse() {{{ /** * Parses the given xml definition file and returns a * Console_CommandLine instance constructed with the xml data. * * @param string $xmlfile The xml file to parse * * @return Console_CommandLine A parser instance */ public static function parse($xmlfile) { if (!is_readable($xmlfile)) { Console_CommandLine::triggerError('invalid_xml_file', E_USER_ERROR, array('{$file}' => $xmlfile)); } $doc = new DomDocument(); $doc->load($xmlfile); self::validate($doc); $nodes = $doc->getElementsByTagName('command'); $root = $nodes->item(0); return self::_parseCommandNode($root, true); } // }}} // parseString() {{{ /** * Parses the given xml definition string and returns a * Console_CommandLine instance constructed with the xml data. * * @param string $xmlstr The xml string to parse * * @return Console_CommandLine A parser instance */ public static function parseString($xmlstr) { $doc = new DomDocument(); $doc->loadXml($xmlstr); self::validate($doc); $nodes = $doc->getElementsByTagName('command'); $root = $nodes->item(0); return self::_parseCommandNode($root, true); } // }}} // validate() {{{ /** * Validates the xml definition using Relax NG. * * @param DomDocument $doc The document to validate * * @return boolean Whether the xml data is valid or not. * @throws Console_CommandLine_Exception * @todo use exceptions */ public static function validate($doc) { if (is_dir('@data_dir@' . DIRECTORY_SEPARATOR . 'Console_CommandLine')) { $rngfile = '@data_dir@' . DIRECTORY_SEPARATOR . 'Console_CommandLine' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'xmlschema.rng'; } else { $rngfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'xmlschema.rng'; } if (!is_readable($rngfile)) { Console_CommandLine::triggerError('invalid_xml_file', E_USER_ERROR, array('{$file}' => $rngfile)); } return $doc->relaxNGValidate($rngfile); } // }}} // _parseCommandNode() {{{ /** * Parses the root command node or a command node and returns the * constructed Console_CommandLine or Console_CommandLine_Command instance. * * @param DomDocumentNode $node The node to parse * @param bool $isRootNode Whether it is a root node or not * * @return mixed Console_CommandLine or Console_CommandLine_Command */ private static function _parseCommandNode($node, $isRootNode = false) { if ($isRootNode) { $obj = new Console_CommandLine(); } else { include_once 'Console/CommandLine/Command.php'; $obj = new Console_CommandLine_Command(); } foreach ($node->childNodes as $cNode) { $cNodeName = $cNode->nodeName; switch ($cNodeName) { case 'name': case 'description': case 'version': $obj->$cNodeName = trim($cNode->nodeValue); break; case 'add_help_option': case 'add_version_option': case 'force_posix': $obj->$cNodeName = self::_bool(trim($cNode->nodeValue)); break; case 'option': $obj->addOption(self::_parseOptionNode($cNode)); break; case 'argument': $obj->addArgument(self::_parseArgumentNode($cNode)); break; case 'command': $obj->addCommand(self::_parseCommandNode($cNode)); break; case 'aliases': if (!$isRootNode) { foreach ($cNode->childNodes as $subChildNode) { if ($subChildNode->nodeName == 'alias') { $obj->aliases[] = trim($subChildNode->nodeValue); } } } break; case 'messages': $obj->messages = self::_messages($cNode); break; default: break; } } return $obj; } // }}} // _parseOptionNode() {{{ /** * Parses an option node and returns the constructed * Console_CommandLine_Option instance. * * @param DomDocumentNode $node The node to parse * * @return Console_CommandLine_Option The built option */ private static function _parseOptionNode($node) { include_once 'Console/CommandLine/Option.php'; $obj = new Console_CommandLine_Option($node->getAttribute('name')); foreach ($node->childNodes as $cNode) { $cNodeName = $cNode->nodeName; switch ($cNodeName) { case 'choices': foreach ($cNode->childNodes as $subChildNode) { if ($subChildNode->nodeName == 'choice') { $obj->choices[] = trim($subChildNode->nodeValue); } } break; case 'messages': $obj->messages = self::_messages($cNode); break; default: if (property_exists($obj, $cNodeName)) { $obj->$cNodeName = trim($cNode->nodeValue); } break; } } if ($obj->action == 'Password') { $obj->argument_optional = true; } return $obj; } // }}} // _parseArgumentNode() {{{ /** * Parses an argument node and returns the constructed * Console_CommandLine_Argument instance. * * @param DomDocumentNode $node The node to parse * * @return Console_CommandLine_Argument The built argument */ private static function _parseArgumentNode($node) { include_once 'Console/CommandLine/Argument.php'; $obj = new Console_CommandLine_Argument($node->getAttribute('name')); foreach ($node->childNodes as $cNode) { $cNodeName = $cNode->nodeName; switch ($cNodeName) { case 'description': case 'help_name': case 'default': $obj->$cNodeName = trim($cNode->nodeValue); break; case 'multiple': $obj->multiple = self::_bool(trim($cNode->nodeValue)); break; case 'optional': $obj->optional = self::_bool(trim($cNode->nodeValue)); break; case 'choices': foreach ($cNode->childNodes as $subChildNode) { if ($subChildNode->nodeName == 'choice') { $obj->choices[] = trim($subChildNode->nodeValue); } } break; case 'messages': $obj->messages = self::_messages($cNode); break; default: break; } } return $obj; } // }}} // _bool() {{{ /** * Returns a boolean according to true/false possible strings. * * @param string $str The string to process * * @return boolean */ private static function _bool($str) { return in_array(strtolower((string)$str), array('true', '1', 'on', 'yes')); } // }}} // _messages() {{{ /** * Returns an array of custom messages for the element * * @param DOMNode $node The messages node to process * * @return array an array of messages * * @see Console_CommandLine::$messages * @see Console_CommandLine_Element::$messages */ private static function _messages(DOMNode $node) { $messages = array(); foreach ($node->childNodes as $cNode) { if ($cNode->nodeType == XML_ELEMENT_NODE) { $name = $cNode->getAttribute('name'); $value = trim($cNode->nodeValue); $messages[$name] = $value; } } return $messages; } // }}} } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/data/000077500000000000000000000000001262404765100234515ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/data/xmlschema.rng000066400000000000000000000127131262404765100261460ustar00rootroot00000000000000 [Tt][Rr][Uu][Ee] [On][Nn] [Yy][Ee][Ss] 1 [Ff][Aa][Ll][Ss][Ee] [Of][Ff][Ff] [Nn][Oo] 0 php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/000077500000000000000000000000001262404765100234705ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/000077500000000000000000000000001262404765100253065ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/ex1.php000066400000000000000000000042421262404765100265160ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 */ // Include the Console_CommandLine package. require_once 'Console/CommandLine.php'; // create the parser $parser = new 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_list_option' => true )); // 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()); } ?> php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/ex2.php000066400000000000000000000024411262404765100265160ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 */ // Include the Console_CommandLine package. require_once 'Console/CommandLine.php'; // create the parser from xml file $xmlfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ex2.xml'; $parser = 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()); } ?> php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/ex2.xml000066400000000000000000000022421262404765100265260ustar00rootroot00000000000000 zip given files using the php zip module. 1.0.0 a list of files to zip together true path to the zip file to generate php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/ex3.php000066400000000000000000000051411262404765100265170ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 */ // Include the Console_CommandLine package. require_once 'Console/CommandLine.php'; // create the parser $parser = new Console_CommandLine(array( 'description' => 'A great program that can foo and bar !', 'version' => '1.0.0' )); // add a global option to make the program verbose $parser->addOption('verbose', array( 'short_name' => '-v', 'long_name' => '--verbose', 'action' => 'StoreTrue', 'description' => 'turn on verbose output' )); // add the foo subcommand $foo_cmd = $parser->addCommand('foo', array( 'description' => 'output the given string with a foo prefix' )); $foo_cmd->addOption('reverse', array( 'short_name' => '-r', 'long_name' => '--reverse', 'action' => 'StoreTrue', 'description' => 'reverse the given string before echoing it' )); $foo_cmd->addArgument('text', array( 'description' => 'the text to output' )); // add the bar subcommand with a "baz" alias $bar_cmd = $parser->addCommand('bar', array( 'description' => 'output the given string with a bar prefix', 'aliases' => array('baz'), )); $bar_cmd->addOption('reverse', array( 'short_name' => '-r', 'long_name' => '--reverse', 'action' => 'StoreTrue', 'description' => 'reverse the given string before echoing it' )); $bar_cmd->addArgument('text', array( 'description' => 'the text to output' )); // run the parser try { $result = $parser->parse(); if ($result->command_name) { $st = $result->command->options['reverse'] ? strrev($result->command->args['text']) : $result->command->args['text']; if ($result->command_name == 'foo') { echo "Foo says: $st\n"; } else if ($result->command_name == 'bar') { echo "Bar says: $st\n"; } } } catch (Exception $exc) { $parser->displayError($exc->getMessage()); } ?> php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/ex4.php000066400000000000000000000030041262404765100265140ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 */ // Include the Console_CommandLine package. require_once 'Console/CommandLine.php'; // create the parser $xmlfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ex4.xml'; $parser = Console_CommandLine::fromXmlFile($xmlfile); // run the parser try { $result = $parser->parse(); if ($result->command_name) { $st = $result->command->options['reverse'] ? strrev($result->command->args['text']) : $result->command->args['text']; if ($result->command_name == 'foo') { echo "Foo says: $st\n"; } else if ($result->command_name == 'bar') { echo "Bar says: $st\n"; } } } catch (Exception $exc) { $parser->displayError($exc->getMessage()); } ?> php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/ex4.xml000066400000000000000000000025301262404765100265300ustar00rootroot00000000000000 A great program that can foo and bar ! 1.0.0 foo output the given string with a foo prefix the text to output bar output the given string with a bar prefix the text to output php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/ex5.php000066400000000000000000000016201262404765100265170ustar00rootroot00000000000000 * @link http://pear.php.net/package/Console_CommandLine */ // Include the Console_CommandLine package. require_once 'Console/CommandLine.php'; // create the parser $xmlfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ex5.xml'; $parser = Console_CommandLine::fromXmlFile($xmlfile); // run the parser try { $result = $parser->parse(); if ($result->command_name) { $st = implode(', ', $result->command->args['item']); echo "List says: $st\n"; } } catch (Exception $exc) { $parser->displayError($exc->getMessage()); } ?> php-console-commandline-1.2.0/Console_CommandLine-1.2.0/docs/examples/ex5.xml000066400000000000000000000015021262404765100265270ustar00rootroot00000000000000 A great program that can list foo elements ! 1.0.0 list output the list of foo elements May be either "foo", "bar", "baz" true foo bar baz php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/000077500000000000000000000000001262404765100237025ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/AllTests.php000066400000000000000000000042711262404765100261520ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 1.0.0 */ if (!defined('PHPUnit_MAIN_METHOD')) { define('PHPUnit_MAIN_METHOD', 'Console_CommandLine_AllTests::main'); } if ($fp = @fopen('PHPUnit/Autoload.php', 'r', true)) { require_once 'PHPUnit/Autoload.php'; } elseif ($fp = @fopen('PHPUnit/Framework.php', 'r', true)) { require_once 'PHPUnit/Framework.php'; } else { die("skip could not find PHPUnit"); } fclose($fp); /** * Console_CommandLine phpt test suite. * * Run all tests from the package root directory: * $ phpunit Console_CommandLine_AllTests tests/AllTests.php * or * $ php tests/AllTests.php * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since Class available since release 1.0.0 */ class Console_CommandLine_AllTests { /** * Runs the test suite * * @return void * @static */ public static function main() { PHPUnit_TextUI_TestRunner::run(self::suite()); } /** * Return the phpt test suite * * @return object the PHPUnit_Framework_TestSuite object * @static */ public static function suite() { return new PHPUnit_Extensions_PhptTestSuite(dirname(__FILE__)); } } if (PHPUnit_MAIN_METHOD == 'Console_CommandLine_AllTests::main') { Console_CommandLine_AllTests::main(); } ?> php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_accept.phpt000066400000000000000000000013671262404765100321350ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::accept() method. --FILE-- accept(new CustomRenderer()); echo get_class($parser->renderer) . "\n"; // outputter $parser->accept(new CustomOutputter()); echo get_class($parser->outputter) . "\n"; $parser->accept(new CustomMessageProvider()); echo get_class($parser->message_provider) . "\n"; $parser->accept(new stdclass()); } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- CustomRenderer CustomOutputter CustomMessageProvider STDERR >> CustomRenderer::error(INVALID_CUSTOM_INSTANCE) php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_addargument.phpt000066400000000000000000000040221262404765100331600ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::addArgument() method. --FILE-- addArgument('arg1'); $parser->addArgument('arg2', array( 'multiple' => true, 'description' => 'description of arg2' )); $arg3 = new Console_CommandLine_Argument('arg3', array( 'multiple' => true, 'description' => 'description of arg3' )); $parser->addArgument($arg3); $parser->addArgument('arg4', array('optional' => true)); var_dump($parser->args); // a bad argument $parser->addArgument('Some invalid name'); ?> --EXPECTF-- array(4) { ["arg1"]=> object(Console_CommandLine_Argument)#5 (7) { ["multiple"]=> bool(false) ["optional"]=> bool(false) ["name"]=> string(4) "arg1" ["help_name"]=> string(4) "arg1" ["description"]=> NULL ["default"]=> NULL ["messages"]=> array(0) { } } ["arg2"]=> object(Console_CommandLine_Argument)#6 (7) { ["multiple"]=> bool(true) ["optional"]=> bool(false) ["name"]=> string(4) "arg2" ["help_name"]=> string(4) "arg2" ["description"]=> string(19) "description of arg2" ["default"]=> NULL ["messages"]=> array(0) { } } ["arg3"]=> object(Console_CommandLine_Argument)#7 (7) { ["multiple"]=> bool(true) ["optional"]=> bool(false) ["name"]=> string(4) "arg3" ["help_name"]=> string(4) "arg3" ["description"]=> string(19) "description of arg3" ["default"]=> NULL ["messages"]=> array(0) { } } ["arg4"]=> object(Console_CommandLine_Argument)#8 (7) { ["multiple"]=> bool(false) ["optional"]=> bool(true) ["name"]=> string(4) "arg4" ["help_name"]=> string(4) "arg4" ["description"]=> NULL ["default"]=> NULL ["messages"]=> array(0) { } } } Fatal error: argument name must be a valid php variable name (got: Some invalid name) in %sCommandLine.php on line %d php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_addargument_2.phpt000066400000000000000000000012221262404765100334000ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::addArgument() method. --SKIPIF-- --ARGS-- foo --FILE-- addArgument('arg1'); $parser->addArgument('arg2', array( 'optional' => true, 'default' => 'bar' )); $result = $parser->parse(); echo $result->args['arg1'] . ' ' . $result->args['arg2']; // a bad argument $parser->addArgument('arg3', array('default' => 'baz')); ?> --EXPECTF-- foo bar Fatal error: only optional arguments can have a default value in %sCommandLine.php on line %d php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_addcommand.phpt000066400000000000000000000013721262404765100327610ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::addCommand() method. --FILE-- addCommand('cmd1'); $parser->addCommand('cmd2', array( 'description' => 'description of cmd2' )); $cmd3 = new Console_CommandLine_Command(array( 'name' => 'cmd3', 'description' => 'description of cmd3' )); $parser->addCommand($cmd3); var_dump(array_keys($parser->commands)); var_dump($parser->commands['cmd2']->description); var_dump($parser->commands['cmd3']->description); ?> --EXPECT-- array(3) { [0]=> string(4) "cmd1" [1]=> string(4) "cmd2" [2]=> string(4) "cmd3" } string(19) "description of cmd2" string(19) "description of cmd3" php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_addcommand_2.phpt000066400000000000000000000012151262404765100331760ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::addCommand() method. --ARGS-- cmd1 --help 2>&1 --FILE-- renderer->line_width = 30; $parser->addCommand('cmd1', array( 'description' => '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30' )); $parser->parse(); ?> --EXPECTF-- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Usage: %sconsole_commandline_addcommand_2.php [options] cmd1 [options] Options: -h, --help show this help message and exit php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_addcommand_3.phpt000066400000000000000000000007651262404765100332100ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::addCommand() method. --ARGS-- --FILE-- true)); $parser->addCommand('cmd1'); $parser->addCommand('cmd2'); $parser->addCommand('cmd3'); try { $parser->parse(); } catch (Console_CommandLine_Exception $exc) { echo $exc->getMessage(); } ?> --EXPECTF-- Please enter one of the following command: cmd1, cmd2, cmd3. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_addoption.phpt000066400000000000000000000064311262404765100326540ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::addOption() method. --FILE-- addOption('opt1', array( 'short_name' => '-a' )); $parser->addOption('opt2', array( 'short_name' => '-b', 'long_name' => '--foo', 'description' => 'description of opt2', 'action' => 'StoreInt', 'help_name' => 'bar', 'choices' => array(1, 2, 3), 'add_list_option' => true, 'default' => 2 )); $opt3 = new Console_CommandLine_Option('opt3', array( 'long_name' => '--bar', 'description' => 'description of opt3', )); $parser->addOption($opt3); var_dump($parser->options); ?> --EXPECTF-- array(4) { ["opt1"]=> object(Console_CommandLine_Option)#5 (14) { ["short_name"]=> string(2) "-a" ["long_name"]=> NULL ["action"]=> string(11) "StoreString" ["choices"]=> array(0) { } ["callback"]=> NULL ["action_params"]=> array(0) { } ["argument_optional"]=> bool(false) ["add_list_option"]=> bool(false) [%s]=> NULL ["name"]=> string(4) "opt1" ["help_name"]=> string(4) "opt1" ["description"]=> NULL ["default"]=> NULL ["messages"]=> array(0) { } } ["opt2"]=> object(Console_CommandLine_Option)#6 (14) { ["short_name"]=> string(2) "-b" ["long_name"]=> string(5) "--foo" ["action"]=> string(8) "StoreInt" ["choices"]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } ["callback"]=> NULL ["action_params"]=> array(0) { } ["argument_optional"]=> bool(false) ["add_list_option"]=> bool(true) [%s]=> NULL ["name"]=> string(4) "opt2" ["help_name"]=> string(3) "bar" ["description"]=> string(19) "description of opt2" ["default"]=> int(2) ["messages"]=> array(0) { } } ["list_opt2"]=> object(Console_CommandLine_Option)#7 (14) { ["short_name"]=> NULL ["long_name"]=> string(11) "--list-opt2" ["action"]=> string(4) "List" ["choices"]=> array(0) { } ["callback"]=> NULL ["action_params"]=> array(1) { ["list"]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } } ["argument_optional"]=> bool(false) ["add_list_option"]=> bool(false) [%s]=> NULL ["name"]=> string(9) "list_opt2" ["help_name"]=> string(9) "list_opt2" ["description"]=> string(35) "lists valid choices for option opt2" ["default"]=> NULL ["messages"]=> array(0) { } } ["opt3"]=> object(Console_CommandLine_Option)#8 (14) { ["short_name"]=> NULL ["long_name"]=> string(5) "--bar" ["action"]=> string(11) "StoreString" ["choices"]=> array(0) { } ["callback"]=> NULL ["action_params"]=> array(0) { } ["argument_optional"]=> bool(false) ["add_list_option"]=> bool(false) [%s]=> NULL ["name"]=> string(4) "opt3" ["help_name"]=> string(4) "opt3" ["description"]=> string(19) "description of opt3" ["default"]=> NULL ["messages"]=> array(0) { } } } console_commandline_addoption_errors_1.phpt000066400000000000000000000005621262404765100344100ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine::addOption() method (errors 1). --FILE-- addOption('Some invalid name'); ?> --EXPECTF-- Fatal error: option name must be a valid php variable name (got: Some invalid name) in %sCommandLine.php on line %d console_commandline_addoption_errors_2.phpt000066400000000000000000000005651262404765100344140ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine::addOption() method (errors 2). --FILE-- addOption('name', array()); ?> --EXPECTF-- Fatal error: you must provide at least an option short name or long name for option "name" in %sCommandLine.php on line %d console_commandline_addoption_errors_3.phpt000066400000000000000000000006001262404765100344030ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine::addOption() method (errors 3). --FILE-- addOption('name', array('short_name'=>'d')); ?> --EXPECTF-- Fatal error: option "name" short name must be a dash followed by a letter (got: "d") in %sCommandLine.php on line %d console_commandline_addoption_errors_4.phpt000066400000000000000000000005761262404765100344200ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine::addOption() method (errors 4). --FILE-- addOption('name', array('long_name'=>'d')); ?> --EXPECTF-- Fatal error: option "name" long name must be 2 dashes followed by a word (got: "d") in %sCommandLine.php on line %d console_commandline_addoption_errors_5.phpt000066400000000000000000000005531262404765100344140ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine::addOption() method (errors 5). --FILE-- addOption('name', array('short_name'=>'-d', 'action'=>true)); ?> --EXPECTF-- Fatal error: invalid action for option "name". in %sCommandLine.php on line %d console_commandline_addoption_errors_6.phpt000066400000000000000000000006051262404765100344130ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine::addOption() method (errors 6). --FILE-- addOption('name', array('short_name'=>'-d', 'action'=>'Inexistant')); ?> --EXPECTF-- Fatal error: unregistered action "Inexistant" for option "name". in %sCommandLine.php on line %d console_commandline_addoption_errors_7.phpt000066400000000000000000000006031262404765100344120ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine::addOption() method (errors 7). --FILE-- addOption('name', array('short_name'=>'-d', 'action'=>'Callback')); ?> --EXPECTF-- Fatal error: you must provide a valid callback for option "name" in %sCommandLine.php on line %d php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_fromxmlfile.phpt000066400000000000000000000017231262404765100332160ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::fromXmlFile() method. --SKIPIF-- --ARGS-- --help 2>&1 --FILE-- parse(); ?> --EXPECTF-- zip/unzip files Usage: test [options] test [options] [options] [args] Options: -c choice, --choice=choice choice option --list-choice lists valid choices for option choice -p password, --password=password zip file password -v, --verbose turn on verbose output -h, --help show this help message and exit --version show the program version and exit Commands: zip zip given files in the destination file (aliases: compress, zp) unzip unzip given file in the destination dir (alias: uzp) php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_fromxmlfile_1.phpt000066400000000000000000000011631262404765100334340ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::fromXmlFile() method. --SKIPIF-- --ARGS-- zip --help 2>&1 --FILE-- parse(); ?> --EXPECTF-- zip given files in the destination file Usage: test [options] zip [options] files1 files2 ... zipfile Options: -h, --help show this help message and exit Arguments: files a list of files to zip together zipfile path to the zip file to generate php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_fromxmlfile_2.phpt000066400000000000000000000011461262404765100334360ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::fromXmlFile() method. --SKIPIF-- --ARGS-- unzip --help 2>&1 --FILE-- parse(); ?> --EXPECTF-- unzip given file in the destination dir Usage: test [options] unzip [options] outputdir zipfile Options: -h, --help show this help message and exit Arguments: outputdir destination directory zipfile path to the zip file to unzip console_commandline_fromxmlfile_error.phpt000066400000000000000000000010101262404765100343350ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine::fromXmlFile() method (error). --SKIPIF-- --ARGS-- --help 2>&1 --FILE-- parse(); ?> --EXPECTF-- Fatal error: XML definition file "%sunexisting.xml" does not exists or is not readable in %sCommandLine.php on line %d php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_fromxmlstring.phpt000066400000000000000000000017661262404765100336140ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::fromXmlString() method. --SKIPIF-- --ARGS-- --help 2>&1 --FILE-- parse(); ?> --EXPECT-- zip/unzip files Usage: test [options] test [options] [options] [args] Options: -c choice, --choice=choice choice option --list-choice lists valid choices for option choice -p password, --password=password zip file password -v, --verbose turn on verbose output -h, --help show this help message and exit --version show the program version and exit Commands: zip zip given files in the destination file (aliases: compress, zp) unzip unzip given file in the destination dir (alias: uzp) console_commandline_options_defaults.phpt000066400000000000000000000012411262404765100341700ustar00rootroot00000000000000php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests--TEST-- Test for Console_CommandLine options defaults. --SKIPIF-- --FILE-- force_options_defaults = true; $result = $parser->parse(); foreach ($result->options as $k => $v) { echo $k . ":"; var_dump($v); } } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- true:bool(false) false:bool(true) int:int(0) float:float(0) string:NULL counter:int(0) callback:NULL array:array(0) { } password:NULL help:NULL version:NULL php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_1.phpt000066400000000000000000000005021262404765100322160ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (--version). --SKIPIF-- --ARGS-- --version --FILE-- parse(); ?> --EXPECT-- some_program version 0.1.0. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_10.phpt000066400000000000000000000011271262404765100323020ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (subcommand). --SKIPIF-- --ARGS-- -v install -f foo --FILE-- parse(); var_dump($result->options); var_dump($result->command_name); var_dump($result->command->options); ?> --EXPECT-- array(4) { ["verbose"]=> bool(true) ["logfile"]=> NULL ["help"]=> NULL ["version"]=> NULL } string(7) "install" array(2) { ["force"]=> bool(true) ["help"]=> NULL } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_11.phpt000066400000000000000000000014171262404765100323050ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (subcommand help 1). --SKIPIF-- --ARGS-- --help 2>&1 --FILE-- parse(); ?> --EXPECT-- Description of our parser goes here... Usage: some_program [options] some_program [options] [options] [args] Options: -v, --verbose verbose mode -l logfile, --logfile=logfile path to logfile -h, --help show this help message and exit --version show the program version and exit Commands: install install given package (aliases: inst, instbis) uninstall uninstall given package php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_12.phpt000066400000000000000000000010251262404765100323010ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (subcommand help 2). --SKIPIF-- --ARGS-- inst --help 2>&1 --FILE-- parse(); ?> --EXPECT-- install given package Usage: some_program [options] install [options] package Options: -f, --force force installation -h, --help show this help message and exit Arguments: package package to install php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_13.phpt000066400000000000000000000006751262404765100323140ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (user errors 1). --SKIPIF-- --ARGS-- --float=foo foo bar --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Option "float" requires a value of type float (got "foo"). php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_14.phpt000066400000000000000000000006671262404765100323160ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (user errors 2). --SKIPIF-- --ARGS-- --int=foo foo bar --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Option "int" requires a value of type int (got "foo"). php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_15.phpt000066400000000000000000000010561262404765100323100ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (subcommand error). --SKIPIF-- --ARGS-- install -f 2>&1 --FILE-- parse(); } catch (Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- Error: You must provide at least 1 argument. Type "some_program --help" to get help. Type "some_program --help" to get help on specific command. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_16.phpt000066400000000000000000000007161262404765100323130ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (user errors 3). --SKIPIF-- --ARGS-- -s fooz foo bar --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Option "string" must be one of the following: "foo", "bar", "baz" (got "fooz"). php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_17.phpt000066400000000000000000000022551262404765100323140ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (user argc/argv 1). --SKIPIF-- --FILE-- parse($argc, $argv); var_dump($result); } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- object(Console_CommandLine_Result)#18 (4) { ["options"]=> array(11) { ["true"]=> bool(true) ["false"]=> bool(false) ["int"]=> int(1) ["float"]=> float(1.2) ["string"]=> NULL ["counter"]=> NULL ["callback"]=> NULL ["array"]=> array(2) { [0]=> string(4) "spam" [1]=> string(3) "egg" } ["password"]=> NULL ["help"]=> NULL ["version"]=> NULL } ["args"]=> array(2) { ["simple"]=> string(3) "foo" ["multiple"]=> array(1) { [0]=> string(3) "bar" } } ["command_name"]=> bool(false) ["command"]=> bool(false) } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_18.phpt000066400000000000000000000021121262404765100323050ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (user argc/argv 2). --SKIPIF-- --FILE-- parse($argc, $argv); var_dump($result); } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- object(Console_CommandLine_Result)#16 (4) { ["options"]=> array(4) { ["verbose"]=> bool(true) ["logfile"]=> NULL ["help"]=> NULL ["version"]=> NULL } ["args"]=> array(0) { } ["command_name"]=> string(7) "install" ["command"]=> object(Console_CommandLine_Result)#19 (4) { ["options"]=> array(2) { ["force"]=> bool(true) ["help"]=> NULL } ["args"]=> array(1) { ["package"]=> string(3) "foo" } ["command_name"]=> bool(false) ["command"]=> bool(false) } } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_19.phpt000066400000000000000000000020431262404765100323110ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (subcommand help 1). --STDIN-- some_package --SKIPIF-- --ARGS-- -v instbis -f - --FILE-- parse(); print_r($result); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Console_CommandLine_Result Object ( [options] => Array ( [verbose] => 1 [logfile] => [help] => [version] => ) [args] => Array ( ) [command_name] => install [command] => Console_CommandLine_Result Object ( [options] => Array ( [force] => 1 [help] => ) [args] => Array ( [package] => some_package ) [command_name] => [command] => ) ) php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_2.phpt000066400000000000000000000022441262404765100322240ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (--help). --SKIPIF-- --ARGS-- --help 2>&1 --FILE-- parse(); ?> --EXPECT-- Description of our parser goes here... Usage: some_program [options] simple [multiple1 multiple2 ...] Options: -t, --true test the StoreTrue action -f, --false test the StoreFalse action --int=INT test the StoreInt action --float=FLOAT test the StoreFloat action -s STRING, --string=STRING test the StoreString action -c, --counter test the Counter action --callback=callback test the Callback action -a ARRAY, --array=ARRAY test the StoreArray action -p password, --password=password test the Password action -h, --help show this help message and exit -v, --version show the program version and exit Arguments: simple test a simple argument multiple test a multiple argument php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_20.phpt000066400000000000000000000006121262404765100323010ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::fromXmlFile() method. --SKIPIF-- --ARGS-- --list-choice --FILE-- parse(); ?> --EXPECTF-- Valid choices are: ham, spam php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_21.phpt000066400000000000000000000023021262404765100323000ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (--help with renderer options). --SKIPIF-- --ARGS-- --help 2>&1 --FILE-- renderer->line_width = 0; $parser->renderer->options_on_different_lines = true; $parser->parse(); ?> --EXPECT-- Description of our parser goes here... Usage: some_program [options] simple [multiple1 multiple2 ...] Options: -t --true test the StoreTrue action -f --false test the StoreFalse action --int=INT test the StoreInt action --float=FLOAT test the StoreFloat action -s STRING --string=STRING test the StoreString action -c --counter test the Counter action --callback=callback test the Callback action -a ARRAY --array=ARRAY test the StoreArray action -p password --password=password test the Password action -h --help show this help message and exit -v --version show the program version and exit Arguments: simple test a simple argument multiple test a multiple argument php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_22.phpt000066400000000000000000000012151262404765100323030ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (--help with renderer options). --SKIPIF-- --ARGS-- --list --FILE-- addOption('list', array( 'long_name' => '--list', 'action' => 'List', 'action_params' => array( 'list' => array('foo', 'bar', 'baz'), 'message' => 'foobarbaz---', 'delimiter' => '|', 'post' => '---foobarbaz', ), )); $parser->parse(); ?> --EXPECT-- foobarbaz---foo|bar|baz---foobarbaz php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_23.phpt000066400000000000000000000006631262404765100323120ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (invalid subcommand detection). --SKIPIF-- --ARGS-- -v invalid subcommand --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Command "invalid" is not valid. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_24.phpt000066400000000000000000000006371262404765100323140ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (invalid subcommand detection). --SKIPIF-- --ARGS-- upgrade --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Package name is required. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_25.phpt000066400000000000000000000006621262404765100323130ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (invalid subcommand detection). --SKIPIF-- --ARGS-- upgrade -s foo --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Valid states are "stable" and "beta". php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_26.phpt000066400000000000000000000006371262404765100323160ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (invalid subcommand detection). --SKIPIF-- --ARGS-- upgrade -s --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Option requires value. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_27.phpt000066400000000000000000000006471262404765100323200ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (invalid subcommand detection). --SKIPIF-- --ARGS-- upgrade -t --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Mysterious option encountered. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_28.phpt000066400000000000000000000006631262404765100323170ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (invalid subcommand detection). --SKIPIF-- --ARGS-- upgrade --dry-run=foo --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Option should not have a value. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_29.phpt000066400000000000000000000006361262404765100323200ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (invalid subcommand detection). --SKIPIF-- --ARGS-- foo --FILE-- parse(); } catch (Exception $exc) { echo $exc->getMessage(); } ?> --EXPECT-- Only "upgrade" is supported. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_3.phpt000066400000000000000000000016711262404765100322300ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (various options). --SKIPIF-- --ARGS-- -tfsfoo --int=3 --flo 4.0 -cccc --callback=somestring -a foo bar baz foo bar --FILE-- parse(); var_dump($result->options); var_dump($result->args); ?> --EXPECT-- array(11) { ["true"]=> bool(true) ["false"]=> bool(false) ["int"]=> int(3) ["float"]=> float(4) ["string"]=> string(3) "foo" ["counter"]=> int(4) ["callback"]=> string(20) "foo__fbzrfgevat__bar" ["array"]=> array(3) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(3) "baz" } ["password"]=> NULL ["help"]=> NULL ["version"]=> NULL } array(2) { ["simple"]=> string(3) "foo" ["multiple"]=> array(1) { [0]=> string(3) "bar" } } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_4.phpt000066400000000000000000000007371262404765100322330ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (errors 1). --SKIPIF-- --ARGS-- -d 2>&1 --FILE-- parse(); } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- Error: Unknown option "-d". Type "some_program --help" to get help. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_5.phpt000066400000000000000000000007601262404765100322300ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (errors 2). --SKIPIF-- --ARGS-- --float 2>&1 --FILE-- parse(); } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- Error: Option "float" requires a value. Type "some_program --help" to get help. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_6.phpt000066400000000000000000000007711262404765100322330ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (errors 3). --SKIPIF-- --ARGS-- --float=1.2 2>&1 --FILE-- parse(); } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- Error: You must provide at least 1 argument. Type "some_program --help" to get help. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_7.phpt000066400000000000000000000022601262404765100322270ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (special cases 1). --SKIPIF-- --ARGS-- -t -- -f - --float=1.2 foo 2>&1 --FILE-- parse(); var_dump($result); } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- object(Console_CommandLine_Result)#18 (4) { ["options"]=> array(11) { ["true"]=> bool(true) ["false"]=> NULL ["int"]=> int(1) ["float"]=> float(1) ["string"]=> NULL ["counter"]=> NULL ["callback"]=> NULL ["array"]=> array(2) { [0]=> string(4) "spam" [1]=> string(3) "egg" } ["password"]=> NULL ["help"]=> NULL ["version"]=> NULL } ["args"]=> array(2) { ["simple"]=> string(2) "-f" ["multiple"]=> array(3) { [0]=> string(1) "-" [1]=> string(11) "--float=1.2" [2]=> string(3) "foo" } } ["command_name"]=> bool(false) ["command"]=> bool(false) } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_8.phpt000066400000000000000000000022331262404765100322300ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (special cases 2). --SKIPIF-- --ARGS-- -t foo bar -f 2>&1 --FILE-- force_posix = true; $result = $parser->parse(); var_dump($result); } catch (Console_CommandLine_Exception $exc) { $parser->displayError($exc->getMessage()); } ?> --EXPECT-- object(Console_CommandLine_Result)#18 (4) { ["options"]=> array(11) { ["true"]=> bool(true) ["false"]=> NULL ["int"]=> int(1) ["float"]=> float(1) ["string"]=> NULL ["counter"]=> NULL ["callback"]=> NULL ["array"]=> array(2) { [0]=> string(4) "spam" [1]=> string(3) "egg" } ["password"]=> NULL ["help"]=> NULL ["version"]=> NULL } ["args"]=> array(2) { ["simple"]=> string(3) "foo" ["multiple"]=> array(2) { [0]=> string(3) "bar" [1]=> string(2) "-f" } } ["command_name"]=> bool(false) ["command"]=> bool(false) } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_parse_9.phpt000066400000000000000000000015321262404765100322320ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() method (password option). --SKIPIF-- --ARGS-- -p -- foo bar --STDIN-- secretpass --FILE-- parse(); var_dump($result->options); var_dump($result->args); ?> --EXPECTF-- Password%s array(11) { ["true"]=> NULL ["false"]=> NULL ["int"]=> int(1) ["float"]=> float(1) ["string"]=> NULL ["counter"]=> NULL ["callback"]=> NULL ["array"]=> array(2) { [0]=> string(4) "spam" [1]=> string(3) "egg" } ["password"]=> string(10) "secretpass" ["help"]=> NULL ["version"]=> NULL } array(2) { ["simple"]=> string(3) "foo" ["multiple"]=> array(1) { [0]=> string(3) "bar" } } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_webrequest_1.phpt000066400000000000000000000004061262404765100332750ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() with a web request 1 --GET-- version=1 --FILE-- parse(); ?> --EXPECT-- some_program version 0.1.0. php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_webrequest_2.phpt000066400000000000000000000021321262404765100332740ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() with a web request 2 --GET-- help --FILE-- parse(); ?> --EXPECT-- Description of our parser goes here... Usage: some_program [options] Options: -t, --true test the StoreTrue action -f, --false test the StoreFalse action --int=INT test the StoreInt action --float=FLOAT test the StoreFloat action -s STRING, --string=STRING test the StoreString action -c, --counter test the Counter action --callback=callback test the Callback action -a ARRAY, --array=ARRAY test the StoreArray action -p password, --password=password test the Password action -h, --help show this help message and exit -v, --version show the program version and exit Arguments: simple test a simple argument multiple test a multiple argument php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/console_commandline_webrequest_3.phpt000066400000000000000000000016321262404765100333010ustar00rootroot00000000000000--TEST-- Test for Console_CommandLine::parse() with a web request 3 --POST-- true=1&false=1&string=foo&int=3&float=4.0&callback=somestring&-a[]=foo&-a[]=bar&-a[]=baz&simple=foo&multiple=bar --FILE-- parse(); var_dump($result->options); var_dump($result->args); ?> --EXPECT-- array(11) { ["true"]=> bool(true) ["false"]=> bool(false) ["int"]=> int(3) ["float"]=> float(4) ["string"]=> string(3) "foo" ["counter"]=> NULL ["callback"]=> string(20) "foo__fbzrfgevat__bar" ["array"]=> array(3) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(3) "baz" } ["password"]=> NULL ["help"]=> NULL ["version"]=> NULL } array(2) { ["simple"]=> string(3) "foo" ["multiple"]=> array(1) { [0]=> string(3) "bar" } } php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/test.xml000066400000000000000000000041771262404765100254140ustar00rootroot00000000000000 true test zip/unzip files 1.0.0 compress zp zip zip given files in the destination file a list of files to zip together True path to the zip file to generate destination directory False unzip uzp unzip given file in the destination dir path to the zip file to unzip php-console-commandline-1.2.0/Console_CommandLine-1.2.0/tests/tests.inc.php000066400000000000000000000325621262404765100263350ustar00rootroot00000000000000 * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version CVS: $Id$ * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 */ if (php_sapi_name() != 'cli') { // tests with php-cgi need this ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . dirname(__FILE__) . '/../'); } /** * Required classes */ require_once 'Console/CommandLine.php'; require_once 'Console/CommandLine/Renderer.php'; require_once 'Console/CommandLine/Outputter.php'; require_once 'Console/CommandLine/MessageProvider.php'; // rot13Callback() {{{ /** * A dummy callback for tests purposes. * * @param mixed $value value provided by the user * @param object $option the option instance * @param object $result the result instance * @param object $parser the parser instance * @param array $params optional params array * * @return string */ function rot13Callback($value, $option, $result, $parser, $params=array()) { $ret = ''; if (isset($params['prefix'])) { $ret .= $params['prefix'] . '__'; } $ret .= str_rot13($value); if (isset($params['suffix'])) { $ret .= '__' . $params['suffix']; } return $ret; } // }}} // buildParser1() {{{ /** * Build a parser instance and return it. * * @return object Console_CommandLine instance */ function buildParser1() { $parser = new Console_CommandLine(); $parser->name = 'some_program'; $parser->version = '0.1.0'; $parser->description = 'Description of our parser goes here...'; // add options $parser->addOption('true', array( 'short_name' => '-t', 'long_name' => '--true', 'action' => 'StoreTrue', 'description' => 'test the StoreTrue action' )); $parser->addOption('false', array( 'short_name' => '-f', 'long_name' => '--false', 'action' => 'StoreFalse', 'description' => 'test the StoreFalse action' )); $parser->addOption('int', array( 'long_name' => '--int', 'action' => 'StoreInt', 'description' => 'test the StoreInt action', 'help_name' => 'INT', 'default' => 1 )); $parser->addOption('float', array( 'long_name' => '--float', 'action' => 'StoreFloat', 'description' => 'test the StoreFloat action', 'help_name' => 'FLOAT', 'default' => 1.0 )); $parser->addOption('string', array( 'short_name' => '-s', 'long_name' => '--string', 'action' => 'StoreString', 'description' => 'test the StoreString action', 'help_name' => 'STRING', 'choices' => array('foo', 'bar', 'baz') )); $parser->addOption('counter', array( 'short_name' => '-c', 'long_name' => '--counter', 'action' => 'Counter', 'description' => 'test the Counter action' )); $parser->addOption('callback', array( 'long_name' => '--callback', 'action' => 'Callback', 'description' => 'test the Callback action', 'callback' => 'rot13Callback', 'action_params' => array('prefix' => 'foo', 'suffix' => 'bar') )); $parser->addOption('array', array( 'short_name' => '-a', 'long_name' => '--array', 'default' => array('spam', 'egg'), 'action' => 'StoreArray', 'help_name' => 'ARRAY', 'description' => 'test the StoreArray action' )); $parser->addOption('password', array( 'short_name' => '-p', 'long_name' => '--password', 'action' => 'Password', 'description' => 'test the Password action' )); $parser->addArgument('simple', array( 'description' => 'test a simple argument' )); $parser->addArgument('multiple', array( 'description' => 'test a multiple argument', 'multiple' => true, 'optional' => true )); return $parser; } // }}} // buildParser2() {{{ /** * Build a parser instance and return it. * * @return object Console_CommandLine instance */ function buildParser2() { $parser = new Console_CommandLine(); $parser->name = 'some_program'; $parser->version = '0.1.0'; $parser->description = 'Description of our parser goes here...'; // add general options $parser->addOption('verbose', array( 'short_name' => '-v', 'long_name' => '--verbose', 'action' => 'StoreTrue', 'description' => 'verbose mode' )); $parser->addOption('logfile', array( 'short_name' => '-l', 'long_name' => '--logfile', 'action' => 'StoreString', 'description' => 'path to logfile' )); // install subcommand $cmd1 = $parser->addCommand('install', array( 'description' => 'install given package', 'aliases' => array('inst', 'instbis'), )); $cmd1->addOption('force', array( 'short_name' => '-f', 'long_name' => '--force', 'action' => 'StoreTrue', 'description' => 'force installation' )); $cmd1->addArgument('package', array( 'description' => 'package to install' )); // uninstall subcommand $cmd2 = $parser->addCommand('uninstall', array( 'description' => 'uninstall given package' )); $cmd2->addArgument('package', array( 'description' => 'package to uninstall' )); return $parser; } // }}} // buildParser3() {{{ /** * Build a parser instance and return it. * * @return object Console_CommandLine instance */ function buildParser3() { $parser = new Console_CommandLine(); $parser->name = 'some_program'; $parser->version = '0.1.0'; $parser->description = 'Description of our parser goes here...'; // we force options default values $parser->force_options_defaults = true; // add options $parser->addOption('true', array( 'short_name' => '-t', 'long_name' => '--true', 'action' => 'StoreTrue', 'description' => 'test the StoreTrue action', )); $parser->addOption('false', array( 'short_name' => '-f', 'long_name' => '--false', 'action' => 'StoreFalse', 'description' => 'test the StoreFalse action', )); $parser->addOption('int', array( 'long_name' => '--int', 'action' => 'StoreInt', 'description' => 'test the StoreInt action', 'help_name' => 'INT', )); $parser->addOption('float', array( 'long_name' => '--float', 'action' => 'StoreFloat', 'description' => 'test the StoreFloat action', 'help_name' => 'FLOAT', )); $parser->addOption('string', array( 'short_name' => '-s', 'long_name' => '--string', 'action' => 'StoreString', 'description' => 'test the StoreString action', 'help_name' => 'STRING', 'choices' => array('foo', 'bar', 'baz') )); $parser->addOption('counter', array( 'short_name' => '-c', 'long_name' => '--counter', 'action' => 'Counter', 'description' => 'test the Counter action' )); $parser->addOption('callback', array( 'long_name' => '--callback', 'action' => 'Callback', 'description' => 'test the Callback action', 'callback' => 'rot13Callback', 'action_params' => array('prefix' => 'foo', 'suffix' => 'bar') )); $parser->addOption('array', array( 'short_name' => '-a', 'long_name' => '--array', 'action' => 'StoreArray', 'help_name' => 'ARRAY', 'description' => 'test the StoreArray action' )); $parser->addOption('password', array( 'short_name' => '-p', 'long_name' => '--password', 'action' => 'Password', 'description' => 'test the Password action' )); return $parser; } // }}} // {{{ buildParser4() /** * Build a parser instance and return it. * * For testing custom messages. * * @return object Console_CommandLine instance */ function buildParser4() { $parser = new Console_CommandLine(array( 'messages' => array( 'INVALID_SUBCOMMAND' => 'Only "upgrade" is supported.', ), )); $parser->name = 'some_program'; $parser->version = '0.1.0'; $parser->description = 'Description of our parser goes here...'; // some subcommand $cmd1 = $parser->addCommand('upgrade', array( 'description' => 'upgrade given package', 'aliases' => array('up'), 'messages' => array( 'ARGUMENT_REQUIRED' => 'Package name is required.', 'OPTION_VALUE_REQUIRED' => 'Option requires value.', 'OPTION_VALUE_UNEXPECTED' => 'Option should not have a value.', 'OPTION_UNKNOWN' => 'Mysterious option encountered.', ), )); // add option $cmd1->addOption('state', array( 'short_name' => '-s', 'long_name' => '--state', 'action' => 'StoreString', 'choices' => array('stable', 'beta'), 'description' => 'accepted package states', 'messages' => array( 'OPTION_VALUE_NOT_VALID' => 'Valid states are "stable" and "beta".', ), )); // add another option $cmd1->addOption('dry_run', array( 'short_name' => '-d', 'long_name' => '--dry-run', 'action' => 'StoreTrue', 'description' => 'dry run', )); // add argument $cmd1->addArgument('package', array( 'description' => 'package to upgrade' )); return $parser; } // }}} // CustomRenderer() {{{ /** * Some custom renderer for tests purposes. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 */ class CustomRenderer implements Console_CommandLine_Renderer { // usage() {{{ /** * Return the full usage message * * @return string the usage message * @access public */ public function usage() { return __METHOD__ . '()'; } // }}} // error() {{{ /** * Return a formatted error message * * @param string $error the error message to format * * @return string the error string * @access public */ public function error($error) { return __METHOD__ . "($error)"; } // }}} // version() {{{ /** * Return the program version string * * @return string the version string * @access public */ public function version() { return __METHOD__ . '()'; } // }}} } // }}} // CustomOutputter() {{{ /** * Some custom outputter for tests purposes. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 */ class CustomOutputter implements Console_CommandLine_Outputter { // stdout() {{{ /** * Called for stdout messages. * * @param string $msg the message to output * * @return void * @access public */ public function stdout($msg) { echo "STDOUT >> $msg\n"; } // }}} // stderr() {{{ /** * Called for stderr messages. * * @param string $msg the message to output * * @return void * @access public */ public function stderr($msg) { echo "STDERR >> $msg\n"; } // }}} } // }}} // CustomMessageProvider() {{{ /** * Some custom message provider for tests purposes. * * @category Console * @package Console_CommandLine * @author David JEAN LOUIS * @copyright 2007 David JEAN LOUIS * @license http://opensource.org/licenses/mit-license.php MIT License * @version Release: 1.2.0 * @link http://pear.php.net/package/Console_CommandLine * @since File available since release 0.1.0 */ class CustomMessageProvider implements Console_CommandLine_MessageProvider { // get() {{{ /** * Retrieve the given string identifier corresponding message. * * @param string $code the string identifier of the message * @param array $vars an array of template variables * * @return string * @access public */ public function get($code, $vars = array()) { return $code; } // }}} } // }}} ?> php-console-commandline-1.2.0/package.xml000066400000000000000000000710101262404765100203500ustar00rootroot00000000000000 Console_CommandLine pear.php.net A full featured command line options and arguments parser 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... David JEAN LOUIS izi izimobil@gmail.com yes Richard Quadling rquadling rquadling@gmail.com yes 2012-10-25 1.2.0 1.2.0 stable stable MIT * Implemented feature request #18583 (default values for arguments) [izi] * Implemented feature request #18582 (add possibility to require a subcommand) [izi] * Booleans read from an XML file or string are now case insensitive [rquadling] * Fixed unit tests [CloCkWeRX] * arguments now accept "choices" [izi, thanks Laurent Laville] 5.1.0 1.4.0b1 2007-12-19 0.1.0 0.1.0 alpha alpha MIT License Initial release. 2007-12-21 0.1.1 0.1.1 alpha alpha MIT License * bugs - fixed bug #12711, - fixed wrong error triggered when argument name is invalid. * changes - some cosmetic changes, - added a lot of phpt test files. 2008-01-09 0.2.0 0.2.0 beta beta MIT License - fixed a bug in Option::toString() (values were not displayed for short options), - fixed a parsing bug: if "-" is passed on the command line it should be treated as an argument, - stop option parsing when a "--" is found as gnu getopt does, - added a "force_posix" boolean attribute that tells the parser to be POSIX compliant, POSIX demands the following behavior: the first non-option stops option processing, - added more regression tests. 2008-01-09 0.2.1 0.2.1 beta beta MIT License fixed bug #12859: xmlschema.rng gets searched at the wrong folder 2008-01-18 1.0.0RC1 1.0.0RC1 beta beta MIT License - fixed a missing check when a short option require an argument and is the last in the argv array, - more GNU getopt compliance: long option/argument can also be separated by a space now and long options abbreviations are supported, - added a "Password" action: with this action it is possible to specify a password on the command line, and if it is missing it will be prompted to user (and will not be echo on stdin on UNIX systems), - allow "force_posix" option to be passed to the constructor, - added more tests. 2008-03-10 1.0.0RC2 1.0.0RC2 beta beta MIT License - allow "force_posix" option to be passed to the constructor; - fixed bug #13038 changed the signature of the parse method to allow the developer to pass argc and argv array (instead of using $_SERVER values); - fixed bug #13132 : "choices" not supported in xml definition (also added "force_posix" attribute support in xml). 2008-03-12 1.0.0RC3 1.0.0RC3 beta beta MIT - fixed a strict standards notice: Console_CommandLine_Exception::build() should be static; - changed behaviour when a StoreArray option is positioned at the end; - now use pfm (so removed package.php and package2.xml). 2008-03-12 1.0.0RC3 1.0.0RC3 beta beta MIT - fixed a strict standards notice: Console_CommandLine_Exception::build() should be static; - changed behaviour when a StoreArray option is positioned at the end; - now use pfm (so removed package.php and package2.xml). 2008-05-22 1.0.0 1.0.0 stable stable MIT - doc is now in peardoc format (thanks to cweiske for his precious help); - better handling of custom instances (added an accept() method); - added an AllTests.php file to make phpunit happy; - added tests for xml usage; - some cosmetic changes. 2008-08-01 1.0.1 1.0.1 stable stable MIT - Better code coverage of tests (nearly 100%); - fixed two bad include_once; - fixed bug #14435 (own -h short option doesn't remove help short option) and did the same for "version" option; - fixed bug #14436 (Typo in error message) and some fixed other typos. 2008-08-22 1.0.2 1.0.2 stable stable MIT - fixed bug #14454 (Console_Commandline hangs when called via browser); - fixed outputter bug (STDOUT/STDERR not defined with php-cgi); - Console_CommandLine can now handle web requests (it convert automatically a request to options/arguments). 2008-09-30 1.0.3 1.0.3 stable stable MIT - now handles stdin with the "-" special switch; - fixed bug #14717 (Password not optional when parser built from an xml file); - added relevant unit tests; - removed useless require_once's in some tests. 2008-10-09 1.0.4 1.0.4 stable stable MIT - implemented feature request #14753 (add_list_option parameter for --list-XXX option); - fixed bug #14762 (error message always tells me to use "-h" for help); - added relevant unit tests; - cleaned up phpdoc tags and some cosmetic changes. 2008-12-06 1.0.5 1.0.5 stable stable MIT * implemented feature request #15251: Allow specifying optional arguments for sub-commands, * use "name" instead of "help_name" when generating list-xxx options, * updated relevant unit tests, * added examples for sub-commands usage. 2008-12-26 1.0.6 1.0.6 stable stable MIT Bugfix release: * fixed bug #15374 (RelaxNG validation should be less strict); * fixed bug #15375 (Cannot add a comment before the root node of the xml file); * fixed bug #15376 (short option and long options in separated lines in help); * fixed bug #15377 (StoreFalse/True actions should have a boolean default value); * added relevant unit tests. 2009-06-19 1.1.0 1.1.0 stable stable MIT * changed sources layout to make easier to use / run tests without installing the package with pear * implemented subcommand aliases (as requested by Greg for pyrus) * implemented request #15325: add ability to detect missing sub-command (patch by gauthierm, thanks) * implemented request #15324: add ability to set custom error messages (patch by gauthierm, thanks) * fixed bug #16320: storeArray default value not cleared when options arguments given (patch by Richard Quadling, thanks!) * fixed bug #16329: sub command aliases do not work (was a "too early documentation" issue) * fixed bug #16330: nested subCommands help output not quite right * implemented request #16332: add support for optional arguments in XML (patch by gauthierm, thanks) 2009-11-11 1.1.1 1.1.1 stable stable MIT Bugfix release: * fixed bug #16507: typo in code example (thanks Richard) * fixed bug #16497: cascade command properties to sub-commands * fixed bug #16370: allow pre-processing of arguments for list (thanks rquadling for the patch) * fixed bug #16764: Invalid Package.xml (thanks mklappstuhl for the patch) * fixed some test cases 2010-04-10 1.1.2 1.1.0 stable stable MIT Bugfix release: * fixed bug #16848: Trailing spaces in quoted argument are truncated, * fixed bug #16849: Replaced $_GET by $_REQUEST to handle POST correctly, * fixed bug #16850: Parse9 test (password) fails (on windows), * fixed bug #16914: Password action now operates as expected when it is the last parameter or the last parameter before a command, * displayUsage() should output to stdout instead of stderr, * added the possibility to pass "false" as exitCode to the display*() methods to prevent exit() calls, * fixed some typos in code comments. 2010-04-10 1.1.3 1.1.0 stable stable MIT * fixed package.xml to allow installation via pyrus.