/** * Class constructor * * @param \Console_CommandLine $parser * @param \Monolog\logger $logger */ public function add($command, $parameters) { if (empty($parameters["class"])) { $this->logger->error("Skipping command " . $command . ": invalid command definition", array("NAME" => $command, "PARAMETERS" => $parameters)); return false; } // replace double backslashes from classname (if any!) $class = str_replace('\\\\', '\\', $parameters["class"]); if (!class_exists($class)) { $this->logger->error("Skipping command " . $command . ": missing class", array("NAME" => $command, "CLASS" => $class)); return false; } $this->command_classes[$command] = $class; $params = array(); if (array_key_exists('description', $parameters)) { $params['description'] = $parameters['description']; } if (array_key_exists('aliases', $parameters) && is_array($parameters['aliases'])) { $params['aliases'] = $parameters['aliases']; } $command = $this->parser->addCommand($command, $params); if (array_key_exists('options', $parameters) && is_array($parameters['options'])) { foreach ($parameters['options'] as $option => $option_parameters) { $command->addOption($option, $option_parameters); } } if (array_key_exists('arguments', $parameters) && is_array($parameters['arguments'])) { foreach ($parameters['arguments'] as $argument => $argument_parameters) { $command->addArgument($argument, $argument_parameters); } } return true; }
/** * Returns a parser of the command line arguments. */ function getParser() { require_once 'Console/CommandLine.php'; $parser = new \Console_CommandLine(array('name' => 'hnu', 'description' => 'Photon command line manager.', 'version' => VERSION)); $options = array('verbose' => array('short_name' => '-v', 'long_name' => '--verbose', 'action' => 'StoreTrue', 'description' => 'turn on verbose output'), 'conf' => array('long_name' => '--conf', 'action' => 'StoreString', 'help_name' => 'path/conf.php', 'description' => 'where the configuration is to be found. By default, the configuration file is the config.php in the current working directory')); foreach ($options as $name => $option) { $parser->addOption($name, $option); } $cmds = array('init' => array('desc' => 'generate the skeleton of a new Photon project in the current folder'), 'pot' => array('desc' => 'generate a standard gettext template file for the project (.pot)', 'opts' => array('potfile' => array('long_name' => '--pot-file', 'action' => 'StoreString', 'help_name' => 'myproject.pot', 'description' => 'Output filename for the gettext template'))), 'show-config' => array('desc' => 'Dump the config file on the standard output, usefull to show phar packaged configuration'), 'serve' => array('desc' => 'start a Photon handler server', 'opts' => array('server_id' => array('long_name' => '--server-id', 'action' => 'StoreString', 'help_name' => 'id', 'description' => 'set the Photon handler id'), 'daemonize' => array('long_name' => '--daemonize', 'action' => 'StoreTrue', 'description' => 'run as daemon'))), 'worker' => array('desc' => 'start a Photon worker', 'args' => array('task' => array('description' => 'the name of the worker task')), 'opts' => array('server_id' => array('long_name' => '--server-id', 'action' => 'StoreString', 'help_name' => 'id', 'description' => 'set the Photon task id'), 'daemonize' => array('long_name' => '--daemonize', 'action' => 'StoreTrue', 'description' => 'run as daemon'))), 'test' => array('desc' => 'run the tests of your project. Uses config.test.php as default config file', 'opts' => array('directory' => array('long_name' => '--coverage-html', 'action' => 'StoreString', 'help_name' => 'path/folder', 'description' => 'directory to store the code coverage report'), 'bootstrap' => array('long_name' => '--bootstrap', 'action' => 'StoreString', 'help_name' => 'path/bootstrap.php', 'description' => 'bootstrap PHP file given to PHPUnit. By default the photon/testbootstrap.php file'))), 'selftest' => array('desc' => 'run the Photon self test procedure', 'opts' => array('directory' => array('long_name' => '--coverage-html', 'action' => 'StoreString', 'help_name' => 'path/folder', 'description' => 'directory to store the code coverage report'))), 'package' => array('desc' => 'package a project as a standalone .phar file', 'args' => array('project' => array('description' => 'the name of the project')), 'opts' => array('conf_file' => array('long_name' => '--include-conf', 'action' => 'StoreString', 'help_name' => 'path/config.prod.php', 'description' => 'path to the configuration file used in production'), 'composer' => array('long_name' => '--composer', 'action' => 'StoreTrue', 'description' => 'Build a phar for the composer version of photon'), 'exclude_files' => array('long_name' => '--exclude-files', 'action' => 'StoreString', 'help_name' => '\\..*', 'description' => 'comma separated list of patterns matching files to exclude'))), 'makekey' => array('desc' => 'prints out a unique random secret key for your configuration', 'opts' => array('length' => array('long_name' => '--length', 'action' => 'StoreInt', 'description' => 'length of the generate secret key (64)')))); $def_cmd = array('opts' => array(), 'args' => array()); foreach ($cmds as $name => $cmd) { $pcmd = $parser->addCommand($name, array('description' => $cmd['desc'])); $cmd = array_merge($def_cmd, $cmd); foreach ($cmd['opts'] as $oname => $oinfo) { $pcmd->addOption($oname, $oinfo); } foreach ($cmd['args'] as $aname => $ainfo) { $pcmd->addArgument($aname, $ainfo); } } return $parser; }
/** * 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; }
{ $ret = array(); for ($h = 0; $h < 360; $h += 15) { for ($l = 0.2; $l < 0.7; $l += 0.1) { for ($s = 0.2; $s < 1; $s += 0.1) { $ret[] = HSL2RGB($h, $s, $l); } } } return $ret; } // MAIN $parser = new Console_CommandLine(); $parser->description = "Convert zone point data into a convex hull."; $parser->version = "0.0.1"; $cmd = $parser->addCommand('basic', array('description' => 'Perform a basic calculation of the bounding polygon plot the points')); $cmd->addOption('outputfile', array('short_name' => '-o', 'description' => 'Output filename', 'default' => 'Zone.png', 'optional' => true, 'help_name' => 'FILE')); $cmd->addArgument('zoneids', array('multiple' => true, 'description' => 'the Zones to convert', 'optional' => true, 'help_name' => 'zones')); $cmd = $parser->addCommand('flood', array('description' => 'Map out the the zones so that a tracing algorithm can be used (half size)')); $cmd->addOption('outputfile', array('short_name' => '-o', 'description' => 'Output filename', 'default' => 'Zone.png', 'optional' => true, 'help_name' => 'FILE')); $cmd->addArgument('zoneids', array('multiple' => true, 'description' => 'the Zones to convert', 'optional' => true, 'help_name' => 'zones')); $cmd = $parser->addCommand('xyz', array('description' => 'Output xyz text file for GMT')); $cmd->addOption('outputfile', array('short_name' => '-o', 'description' => 'Output filename', 'default' => 'Zone.txt', 'optional' => true, 'help_name' => 'FILE')); $cmd->addArgument('zoneids', array('multiple' => true, 'description' => 'the Zones to convert', 'optional' => true, 'help_name' => 'zones')); $cmd = $parser->addCommand('trace', array('description' => 'Trace to SVG file using "My algorithm"')); $cmd->addOption('outputfile', array('short_name' => '-o', 'description' => 'Output filename', 'default' => 'Zone.png', 'optional' => true, 'help_name' => 'FILE')); $cmd->addArgument('zoneids', array('multiple' => true, 'description' => 'the Zones to convert', 'optional' => true, 'help_name' => 'zones')); $cmd = $parser->addCommand('potrace', array('description' => 'Trace to SVG file using potrace')); $cmd->addOption('outputfile', array('short_name' => '-o', 'description' => 'Output filename', 'default' => 'Zone.png', 'optional' => true, 'help_name' => 'FILE')); $cmd->addArgument('zoneids', array('multiple' => true, 'description' => 'the Zones to convert', 'optional' => true, 'help_name' => 'zones')); $cmd = $parser->addCommand('poly', array('description' => 'Convery Poly files (from trace commands) into GIS polygons in a DB'));
* @package Console_CommandLine * @author David JEAN LOUIS <*****@*****.**> * @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') {
/** * Builds the command line parser. * * @return object The command line parser. * @access private */ private function buildCommandLineParser() { require_once 'Console/CommandLine.php'; $parser = new \Console_CommandLine(array('name' => $this->cmd(), 'version' => $this->getVersion(), 'description' => $this->getDescription(), 'add_help_option' => true, 'add_version_option' => true, 'force_posix' => false)); $parser->addOption('proj_path', array('short_name' => '-p', 'long_name' => '--project', 'action' => 'StoreString', 'description' => 'path for the project directory to use')); $new_command = $parser->addCommand('new', array('description' => 'create a new Curator project')); $clean_command = $parser->addCommand('clean', array('description' => 'clean the Curator project')); $build_command = $parser->addCommand('build', array('description' => 'build the current Curator project')); $build_command->addOption('clean', array('short_name' => '-c', 'long_name' => '--clean', 'action' => 'StoreTrue', 'description' => 'clean the current project first')); return $parser; }
/** * コマンドの実行 * * @return void */ public function execute() { $argv = $this->_config['argv']; if (!isset($argv[1])) { return; } // parse $cli = $this->_config['cli']; $parser = new Console_CommandLine(array('name' => 'bear', 'description' => 'BEAR command line interface', 'version' => BEAR::VERSION, 'add_help_option' => true, 'add_version_option' => true)); // create resource $subCmd = $parser->addCommand(self::CMD_CREATE, array('description' => 'create resource.')); $subCmd->addOption('file', array('short_name' => '-g', 'long_name' => '--file', 'action' => 'StoreString', 'description' => 'load arguments file.')); $subCmd->addOption('app', array('short_name' => '-a', 'long_name' => '--app', 'action' => 'StoreString', 'description' => 'specify application path. *Notice* use this on the end of line.')); $subCmd->addArgument('uri', array('description' => 'resource URI')); // read resource $subCmd = $parser->addCommand(self::CMD_READ, array('description' => 'show resource.')); $subCmd->addOption('file', array('short_name' => '-g', 'long_name' => '--file', 'action' => 'StoreString', 'description' => 'load arguments file.')); $subCmd->addOption('length', array('short_name' => '-l', 'long_name' => '--len', 'action' => 'StoreInt', 'description' => 'filter specific lenght each data.')); $subCmd->addOption('format', array('short_name' => '-f', 'long_name' => '--format', 'action' => 'StoreString', 'description' => 'default | table | php | json | csv | printa ')); $subCmd->addOption('app', array('short_name' => '-a', 'long_name' => '--app', 'action' => 'StoreString', 'description' => 'specify application path. *Notice* use this on the end of line.')); $subCmd->addArgument('uri', array('description' => 'resource URI')); // update resource $subCmd = $parser->addCommand(self::CMD_UPDATE, array('description' => 'update resource.')); $subCmd->addOption('file', array('short_name' => '-g', 'long_name' => '--file', 'action' => 'StoreString', 'description' => 'load arguments file.')); $subCmd->addOption('app', array('short_name' => '-a', 'long_name' => '--app', 'action' => 'StoreString', 'description' => 'specify application path. *Notice* use this on the end of line.')); $subCmd->addArgument('uri', array('description' => 'resource URI')); // delete resource $subCmd = $parser->addCommand(self::CMD_DELETE, array('description' => 'delete resource.')); $subCmd->addOption('file', array('short_name' => '-a', 'long_name' => '--file', 'action' => 'StoreString', 'description' => 'load arguments file.')); $subCmd->addOption('app', array('short_name' => '-a', 'long_name' => '--app', 'action' => 'StoreString', 'description' => 'specify application path. *Notice* use this on the end of line.')); $subCmd->addArgument('uri', array('description' => 'resource URI')); // clear-cache $parser->addCommand('clear-cache', array('description' => 'clear all cache.')); // clear-log $parser->addCommand('clear-log', array('description' => 'clear all log.')); // clear-all $parser->addCommand('clear-all', array('description' => 'clear cache and log.')); if ($cli) { // create app $subCmd = $parser->addCommand(self::CMD_INIT_APP, array('description' => 'create new application.')); $subCmd->addArgument('path', array('description' => 'destination path. ex) /var/www/bear.test')); $subCmd->addOption('pearrc', array('short_name' => '-c', 'long_name' => '--pearrc', 'action' => 'StoreString', 'description' => 'find user configuration in `file`')); // set app $subCmd = $parser->addCommand(self::CMD_SET_APP, array('description' => 'set application path.')); $subCmd->addArgument('path', array('description' => 'application path. ex) /var/www/bear.test')); // show app $subCmd = $parser->addCommand(self::CMD_SHOW_APP, array('description' => 'show application path.')); } //exec try { ob_start(); $this->_command = $parser->parse(count($argv), $argv); $buff = ob_get_clean(); $commandName = $this->_command->command_name; switch ($this->_command->command_name) { case self::CMD_INIT_APP: $path = $this->_command->command->args['path']; $path = $this->_makeFullPath($path); $pearrc = $this->_command->command->options['pearrc']; $this->_initApp($path, $pearrc); $this->_setApp($path); break; case self::CMD_SET_APP: $path = $this->_command->command->args['path']; $path = $this->_makeFullPath($path); $this->_setApp($path); break; case self::CMD_SHOW_APP: $this->_checkAppExists(); $this->_showApp(); break; case self::CMD_CLEAR_CACHE: $this->_checkAppExists(); $this->clearCache(); break; case self::CMD_CLEAR_LOG: $this->_checkAppExists(); $this->clearLog(); break; case self::CMD_CLEAR_ALL: $this->_checkAppExists(); $this->clearCache(); $this->clearLog(); break; case self::CMD_CREATE: case self::CMD_READ: case self::CMD_UPDATE: case self::CMD_DELETE: $this->_checkAppExists(); $uri = $this->_command->command->args['uri']; $values = $this->_command->command->options['file'] ? BEAR::loadValues($this->_command->command->options['file']) : array(); $this->_result = $this->_request($commandName, $uri, $values)->getRo(); $this->_config['debug'] = true; break; default: if ($this->_config['cli']) { $this->_result = "BEAR: {$argv[1]}: command not found, try 'bear --help'"; } else { $this->_result = "BEAR: {$argv[1]}: command not found, try 'help'"; } return; } } catch (Exception $e) { $parser->displayError($e->getMessage()); } }
/** * Handle console input and produce the appropriate report requested * * @return void * @throws PHP_CompatInfo_Exception If report is not available. */ public static function main() { $input = new Console_CommandLine(array('name' => 'phpcompatinfo', 'description' => 'PHP_CompatInfo (cli) by Laurent Laville.', 'version' => self::getVersion())); // common options to all sub-commands $input->addOption('xmlFile', array('long_name' => '--configuration', 'action' => 'StoreString', 'description' => 'Read configuration from XML file')); $input->addOption('noConfiguration', array('long_name' => '--no-configuration', 'action' => 'StoreTrue', 'description' => 'Ignore default configuration file ' . '(phpcompatinfo.xml)')); $input->addOption('iniSet', array('short_name' => '-d', 'long_name' => '--ini-set', 'action' => 'StoreArray', 'description' => 'Sets a php.ini directive value')); $input->addOption('verbose', array('short_name' => '-v', 'long_name' => '--verbose', 'action' => 'Counter', 'description' => 'Output more verbose information')); // options relatives and common to sub-commands $referenceOption = new Console_CommandLine_Option('reference', array('long_name' => '--reference', 'action' => 'StoreString', 'description' => 'The name of the reference to use', 'choices' => array('PHP5', 'ALL', 'DYN'))); $reportOption = new Console_CommandLine_Option('report', array('long_name' => '--report', 'action' => 'StoreArray', 'description' => 'Type of report', 'choices' => array('full', 'summary', 'source', 'xml', 'token', 'extension', 'namespace', 'trait', 'interface', 'class', 'function', 'constant', 'global', 'condition'))); $helpReferenceOption = new Console_CommandLine_Option('helpReference', array('long_name' => '--help-reference', 'action' => 'List', 'description' => 'List of reference available', 'action_params' => array('list' => array('PHP5', 'ALL', 'DYN')))); $helpReportOption = new Console_CommandLine_Option('helpReport', array('long_name' => '--help-report', 'action' => 'List', 'description' => 'List of report available', 'action_params' => array('list' => array('full', 'summary', 'source', 'xml', 'token', 'extension', 'namespace', 'trait', 'interface', 'class', 'function', 'constant', 'global', 'condition')))); $reportFileOption = new Console_CommandLine_Option('reportFile', array('long_name' => '--report-file', 'action' => 'StoreString', 'description' => 'Write the report to the specified file path')); $excludeIDOption = new Console_CommandLine_Option('excludeID', array('long_name' => '--exclude-pattern', 'action' => 'StoreString', 'description' => 'Exclude components' . ' from list referenced by ID provided')); $recursiveOption = new Console_CommandLine_Option('recursive', array('short_name' => '-R', 'long_name' => '--recursive', 'action' => 'StoreTrue', 'description' => 'Includes the contents of subdirectories')); $fileExtensionsOption = new Console_CommandLine_Option('fileExtensions', array('long_name' => '--file-extensions', 'action' => 'StoreString', 'description' => 'A comma separated list of file extensions to check')); // options relatives to print sub-command $filterVersionOption = new Console_CommandLine_Option('filterVersion', array('long_name' => '--filter-version', 'action' => 'StoreString', 'description' => 'The version to compare with each element found')); $filterOperatorOption = new Console_CommandLine_Option('filterOperator', array('long_name' => '--filter-operator', 'action' => 'StoreString', 'description' => 'The version test relationship', 'choices' => array('lt', 'le', 'gt', 'ge', 'eq', 'ne'))); // argument common to all list sub-commands except to list and list-references $referenceArgument = new Console_CommandLine_Argument('reference', array('description' => '(optional) Limit output only to this reference', 'optional' => true)); // clear-cache sub-command $clearcacheCmd = $input->addCommand('clear-cache', array('description' => 'Clear Parser Cache')); $clearcacheCmd->addArgument('sourceFile', array('description' => 'The source file in cache entries to delete.', 'optional' => true)); // print sub-command $printCmd = $input->addCommand('print', array('description' => 'Print a report of data source parsed.')); $printCmd->addOption($referenceOption); $printCmd->addOption($reportOption); $printCmd->addOption($reportFileOption); $printCmd->addOption($excludeIDOption); $printCmd->addOption($recursiveOption); $printCmd->addOption($fileExtensionsOption); $printCmd->addOption($filterVersionOption); $printCmd->addOption($filterOperatorOption); $printCmd->addOption($helpReferenceOption); $printCmd->addOption($helpReportOption); $printCmd->addArgument('sourcePath', array('description' => 'The data source to scan (file or directory).')); // list-references sub-command $listReferencesCmd = $input->addCommand('list-references', array('description' => 'List all extensions supported.')); $listReferencesCmd->addOption($filterVersionOption); $listReferencesCmd->addOption($filterOperatorOption); $listReferencesCmd->addOption($reportFileOption); $listReferencesCmd->addArgument($referenceArgument); // list sub-command $listCmd = $input->addCommand('list', array('description' => 'List all "elements" referenced in the data base.')); $listCmd->addOption($referenceOption); $listCmd->addOption($filterVersionOption); $listCmd->addOption($filterOperatorOption); $listCmd->addOption($reportFileOption); $listCmd->addOption($helpReferenceOption); $listCmd->addArgument('element', array('description' => 'May be either ' . '"extensions", ' . '"interfaces", "classes", ' . '"functions" or "constants"', 'choices' => array('extensions', 'interfaces', 'classes', 'functions', 'constants'), 'multiple' => true)); // list-extensions sub-command $listExtensionsCmd = $input->addCommand('list-extensions', array('description' => 'List all extensions referenced in the data base.')); $listExtensionsCmd->addOption($referenceOption); $listExtensionsCmd->addOption($filterVersionOption); $listExtensionsCmd->addOption($filterOperatorOption); $listExtensionsCmd->addOption($reportFileOption); $listExtensionsCmd->addOption($helpReferenceOption); $listExtensionsCmd->addArgument($referenceArgument); // list-interfaces sub-command $listInterfacesCmd = $input->addCommand('list-interfaces', array('description' => 'List all interfaces referenced in the data base.')); $listInterfacesCmd->addOption($referenceOption); $listInterfacesCmd->addOption($filterVersionOption); $listInterfacesCmd->addOption($filterOperatorOption); $listInterfacesCmd->addOption($reportFileOption); $listInterfacesCmd->addOption($helpReferenceOption); $listInterfacesCmd->addArgument($referenceArgument); // list-classes sub-command $listClassesCmd = $input->addCommand('list-classes', array('description' => 'List all classes referenced in the data base.')); $listClassesCmd->addOption($referenceOption); $listClassesCmd->addOption($filterVersionOption); $listClassesCmd->addOption($filterOperatorOption); $listClassesCmd->addOption($reportFileOption); $listClassesCmd->addOption($helpReferenceOption); $listClassesCmd->addArgument($referenceArgument); // list-functions sub-command $listFunctionsCmd = $input->addCommand('list-functions', array('description' => 'List all functions referenced in the data base.')); $listFunctionsCmd->addOption($referenceOption); $listFunctionsCmd->addOption($filterVersionOption); $listFunctionsCmd->addOption($filterOperatorOption); $listFunctionsCmd->addOption($reportFileOption); $listFunctionsCmd->addOption($helpReferenceOption); $listFunctionsCmd->addArgument($referenceArgument); // list-constants sub-command $listConstantsCmd = $input->addCommand('list-constants', array('description' => 'List all constants referenced in the data base.')); $listConstantsCmd->addOption($referenceOption); $listConstantsCmd->addOption($filterVersionOption); $listConstantsCmd->addOption($filterOperatorOption); $listConstantsCmd->addOption($reportFileOption); $listConstantsCmd->addOption($helpReferenceOption); $listConstantsCmd->addArgument($referenceArgument); try { $result = $input->parse(); $command = $result->command_name; if (empty($command)) { $input->displayUsage(1); } } catch (Exception $e) { $input->displayError($e->getMessage()); } $warnings = array(); // Loads the default or custom configuration (if available) $options = array('reference' => '', 'verbose' => false, 'listeners' => array()); $reports = array(); $consoleProgress = true; $reportFileAppend = false; if ($result->options['noConfiguration'] !== true) { if (!isset($result->options['xmlFile'])) { // use default configuration $dir = '@cfg_dir@' . DIRECTORY_SEPARATOR . 'PHP_CompatInfo'; if (strpos($dir, '@') === false) { // PEAR installer was used to install the package } else { // manual install $dir = getcwd(); } $filename = $dir . DIRECTORY_SEPARATOR . 'phpcompatinfo.xml'; if (file_exists($filename)) { $config = $filename; } elseif (file_exists($filename . '.dist')) { $config = $filename . '.dist'; } else { $config = false; } } else { $filename = $result->options['xmlFile']; if (file_exists($filename)) { $config = realpath($filename); } else { $config = false; } } if ($config && is_file($config)) { // try to load the configuration file contents $configuration = PHP_CompatInfo_Configuration::getInstance($config); // check if components should be excluded if (isset($result->command->options['excludeID'])) { $patternID = $result->command->options['excludeID']; $excludes = $configuration->getExcludeConfiguration($patternID); if (count($excludes) == 0) { $warnings[] = "Exclude pattern ID '{$patternID}'" . " does not exist, or is empty"; } else { $haystack = array('extension', 'interface', 'trait', 'function', 'constant'); foreach ($excludes as $key => $values) { if (in_array($key, $haystack)) { $options['exclude'][$key . 's'] = $values; } elseif ('class' == $key) { $options['exclude']['classes'] = $values; } else { foreach ($values as $value) { $options['exclude']['files'][] = $value; } } } } } // set main options $phpcompatinfo = $configuration->getMainConfiguration(); if (isset($phpcompatinfo['reference'])) { $options['reference'] = $phpcompatinfo['reference']; } if (isset($phpcompatinfo['report'])) { $reports = $phpcompatinfo['report']; } if (isset($phpcompatinfo['reportFile'])) { $reportFile = $phpcompatinfo['reportFile']; } if (isset($phpcompatinfo['reportFileAppend'])) { $reportFileAppend = $phpcompatinfo['reportFileAppend']; } if (isset($phpcompatinfo['cacheDriver'])) { $options['cacheDriver'] = $phpcompatinfo['cacheDriver']; } else { $options['cacheDriver'] = 'null'; } if (isset($phpcompatinfo['consoleProgress'])) { $consoleProgress = $phpcompatinfo['consoleProgress']; } if (isset($phpcompatinfo['verbose'])) { $options['verbose'] = $phpcompatinfo['verbose']; } if (isset($phpcompatinfo['recursive'])) { $options['recursive'] = $phpcompatinfo['recursive']; } if (isset($phpcompatinfo['fileExtensions'])) { $options['fileExtensions'] = $phpcompatinfo['fileExtensions']; } // sets cache options $options['cacheOptions'] = $configuration->getCacheConfiguration($options['cacheDriver']); // sets extension references limit $extensions = $configuration->getReferenceConfiguration(); if (count($extensions) > 0) { $options['extensions'] = $extensions; } // sets php.ini directives $ini = $configuration->getPHPConfiguration(); foreach ($ini as $name => $value) { ini_set($name, $value); } // sets listeners instances $listeners = $configuration->getListenerConfiguration(); foreach ($listeners as $listener) { if (!class_exists($listener['class'], false) && $listener['file'] !== '') { include_once $listener['file']; } if (class_exists($listener['class'], true)) { if (count($listener['arguments']) == 0) { $listener = new $listener['class'](); } else { $listenerClass = new ReflectionClass($listener['class']); $listener = $listenerClass->newInstanceArgs($listener['arguments']); } if ($listener instanceof PHP_CompatInfo_Listener_Console && $consoleProgress === false) { /* Do not add the console listener if consoleProgress directive is off */ } else { if ($listener instanceof SplObserver) { $options['listeners'][] = $listener; } } } } // sets plugins system $plugins = $configuration->getPluginConfiguration(); foreach ($plugins as $plugin) { if (!class_exists($plugin['class'], false) && $plugin['file'] !== '') { include_once $plugin['file']; } if (class_exists($plugin['class'], true)) { $pluginClass = new ReflectionClass($plugin['class']); $reference = $pluginClass->newInstanceArgs($plugin['args']); if (!$reference instanceof PHP_CompatInfo_Reference_PluginsAbstract) { $warnings[] = "Plugin '" . $plugin['class'] . "' is not valid"; } unset($reference); } } if (count($plugins) > 0) { $options['referencePlugins'] = $plugins; } } elseif (isset($result->options['verbose'])) { $warnings[] = 'File "' . $filename . '" does not exist'; } } if ($consoleProgress === true) { $options['listeners'][] = new PHP_CompatInfo_Listener_Console(); } if (isset($result->command->options['reference'])) { $options['reference'] = $result->command->options['reference']; } if (empty($options['reference']) && !in_array($command, array('list-references', 'clear-cache'))) { $input->displayError('You must supply at least a reference'); } if (isset($result->options['iniSet'])) { foreach ($result->options['iniSet'] as $iniSet) { $ini = explode('=', $iniSet); if (isset($ini[0])) { if (isset($ini[1])) { ini_set($ini[0], $ini[1]); } else { ini_set($ini[0], true); } } } } if (isset($result->command->options['report'])) { $reports = $result->command->options['report']; } if (empty($reports)) { // default report $reports = array('summary'); } if (in_array('full', $reports)) { // when 'full' alias report is specified, ignored all others $reports = array(); $reportFileAppend = true; $fullReport = true; } $reportChilds = $reports; if (isset($result->command->options['reportFile'])) { $reportFile = $result->command->options['reportFile']; } if (isset($reportFile)) { if (is_dir($reportFile) || !file_exists(dirname($reportFile))) { $warnings[] = 'Report file: "' . $reportFile . '" is invalid'; } else { $options['reportFile'] = $reportFile; if ($reportFileAppend === true) { $options['reportFileFlags'] = FILE_APPEND; } else { $options['reportFileFlags'] = 0; } } } if (isset($result->command->options['filterVersion'])) { $options['filterVersion'] = $result->command->options['filterVersion']; } if (isset($result->command->options['filterOperator'])) { $options['filterOperator'] = $result->command->options['filterOperator']; } if ('print' == $command) { if (count($reports) == 0 && !isset($fullReport)) { $input->displayError('You must supply at least a type of report'); } $source = $result->command->args['sourcePath']; $report = 'full'; } elseif ('list' == $command) { $elements = $result->command->args['element']; $source = array_shift($elements); $report = 'reference'; $options['filterReference'] = null; } elseif ('list' == substr($command, 0, 4)) { list(, $source) = explode('-', $command); if ($source == 'references') { $report = 'database'; } else { $report = 'reference'; $elements = array(); } $options['filterReference'] = $result->command->args['reference']; } if (isset($result->command->options['recursive'])) { $options['recursive'] = $result->command->options['recursive']; } if (isset($result->command->options['fileExtensions'])) { $fileExtensions = explode(',', $result->command->options['fileExtensions']); $options['fileExtensions'] = array_map('trim', $fileExtensions); } if (isset($result->options['verbose'])) { $options['verbose'] = $result->options['verbose']; } if ('clear-cache' == $command) { $defaultOptions = PHP_CompatInfo::getDefaultOptions(); $driver = isset($options['cacheDriver']) ? $options['cacheDriver'] : $defaultOptions['cacheDriver']; $source = $result->command->args['sourceFile']; $cache = PHP_CompatInfo_Cache::getInstance($driver, $defaultOptions); $count = $cache->deleteCache($source); printf('%d cache entries cleared%s', $count, PHP_EOL); } else { try { self::factory($report, $source, $options, $warnings, $reportChilds); if ($report == 'reference') { $options['reportFileFlags'] = FILE_APPEND; while (count($elements) > 0) { $source = array_shift($elements); self::factory($report, $source, $options, $warnings, null); } } } catch (PHP_CompatInfo_Exception $e) { print $e->getMessage() . PHP_EOL; exit(1); } } }
/** * Runs Chef given some command-line arguments. */ public function runUnsafe($userArgc = null, $userArgv = null) { // Get the arguments. if ($userArgc == null || $userArgv == null) { $getopt = new \Console_Getopt(); $userArgv = $getopt->readPHPArgv(); // `readPHPArgv` returns a `PEAR_Error` (or something like it) if // it can't figure out the CLI arguments. if (!is_array($userArgv)) { throw new PieCrustException($userArgv->getMessage()); } $userArgc = count($userArgv); } // Find whether the '--root' parameter was given. $rootDir = null; foreach ($userArgv as $arg) { if (substr($arg, 0, strlen('--root=')) == '--root=') { $rootDir = substr($arg, strlen('--root=')); break; } } if ($rootDir == null) { // No root given. Find it ourselves. $rootDir = PathHelper::getAppRootDir(getcwd()); } else { // The root was given. $rootDir = PathHelper::getAbsolutePath($rootDir); if (!is_dir($rootDir)) { throw new PieCrustException("The given root directory doesn't exist: " . $rootDir); } } // Build the appropriate app. if ($rootDir == null) { $pieCrust = new NullPieCrust(); } else { $pieCrust = new PieCrust(array('root' => $rootDir, 'cache' => !in_array('--no-cache', $userArgv))); } // Set up the command line parser. $parser = new \Console_CommandLine(array('name' => 'chef', 'description' => 'The PieCrust chef manages your website.', 'version' => PieCrustDefaults::VERSION)); // Sort commands by name. $sortedCommands = $pieCrust->getPluginLoader()->getCommands(); usort($sortedCommands, function ($c1, $c2) { return strcmp($c1->getName(), $c2->getName()); }); // Add commands to the parser. foreach ($sortedCommands as $command) { $commandParser = $parser->addCommand($command->getName()); $command->setupParser($commandParser, $pieCrust); $this->addCommonOptionsAndArguments($commandParser); } // Parse the command line. try { $result = $parser->parse($userArgc, $userArgv); } catch (Exception $e) { $parser->displayError($e->getMessage()); return 1; } // If no command was given, use `help`. if (empty($result->command_name)) { $result = $parser->parse(2, array('chef', 'help')); } // Create the log. $debugMode = $result->command->options['debug']; $quietMode = $result->command->options['quiet']; if ($debugMode && $quietMode) { $parser->displayError("You can't specify both --debug and --quiet."); return 1; } $log = \Log::singleton('console', 'Chef', '', array('lineFormat' => '%{message}')); // Make the log available for debugging purposes. $GLOBALS['__CHEF_LOG'] = $log; // Handle deprecated stuff. if ($result->command->options['no_cache_old']) { $log->warning("The `--nocache` option has been renamed `--no-cache`."); $result->command->options['no_cache'] = true; } // Run the command. foreach ($pieCrust->getPluginLoader()->getCommands() as $command) { if ($command->getName() == $result->command_name) { try { if ($rootDir == null && $command->requiresWebsite()) { $cwd = getcwd(); throw new PieCrustException("No PieCrust website in '{$cwd}' ('_content/config.yml' not found!)."); } $context = new ChefContext($pieCrust, $result, $log); $context->setVerbosity($debugMode ? 'debug' : ($quietMode ? 'quiet' : 'default')); $command->run($context); return; } catch (Exception $e) { $log->emerg(self::getErrorMessage($e, $debugMode)); return 1; } } } }
#!/usr/bin/php <?php require_once 'Console/CommandLine.php'; /* * Create command line parser object. */ $parser = new Console_CommandLine(); $parser->description = <<<DESC Tooll for generating jsub command strings DESC; $parser->version = '1.0'; /* * Describe command line options and arguments. */ $parser->addCommand('create', array('description' => 'jsub create command')); $parser->addCommand('assemble', array('description' => 'jsub assemble command')); $parser->addCommand('service', array('description' => 'jsub service command')); $parser->addOption('pattern', array('long_name' => '--pattern', 'description' => 'projects directory pattern', 'action' => 'StoreString')); $parser->addOption('start', array('long_name' => '--start', 'short_name' => '-s', 'description' => 'start phase', 'action' => 'StoreString')); $parser->addOption('property', array('long_name' => '--property', 'short_name' => '-p', 'description' => 'input property', 'action' => 'StoreString')); $parser->addOption('rproperty', array('long_name' => '--rproperty', 'short_name' => '-r', 'description' => 'input regexp property', 'action' => 'StoreString')); $parser->addOption('type', array('long_name' => '--type', 'short_name' => '-t', 'description' => 'jsub project type', 'action' => 'StoreString')); /* * Set evironment variables. */ $workDir = getcwd(); try { $cli = $parser->parse(); /* * Create iterator for traverse through picked directories. */
/** * 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')); $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; }