/** * Process the request * * @param array $params Runner options * * @return void */ public function run($params = null) { $this->parser = new Parser($this->paths); try { $argc = $params === null ? null : count($params); $this->result = $this->parser->parse($argc, $params); } catch (\Exception $e) { $this->parser->displayError($e->getMessage()); } $this->parse(); }
/** * Run tasks (basically, try to parse a command line) */ public function run() { // Parse the command line arguments try { $this->cli = $this->parser->parse(); } catch (Exception $e) { $this->parser->displayError($e->getMessage()); exit($e->getCode()); } }
/** * Process command * * @return string */ public function process() { try { $this->command = $this->parser->parse(); if (empty($this->command->command_name)) { $this->parser->displayUsage(); self::end(0); } $return = $this->controller->execute($this->command->command_name, $this->command->command->options, $this->command->command->args, $this->color, $this->logger, $this->tasks); } catch (ShellException $se) { $this->parser->displayError($this->color->convert("\n\n%R" . $se->getMessage() . "%n\n")); self::end(1); } catch (Exception $e) { $this->parser->displayError($this->color->convert("\n\n%r" . $e->getMessage() . "%n\n")); self::end(1); } echo "\n" . $return . "\n\n"; self::end(0); }
$consoleParser->addOption("restrict_input_file", array("help_name" => "/tmp/missing.txt", "short_name" => "-r", "long_name" => "--restrict-file", "description" => "Domain list, one per line. Others won't be imported.", 'default' => "")); $consoleParser->addOption("force_uid", array("help_name" => "2001", "short_name" => "-u", "long_name" => "--force-uid", "description" => "Force the domain owner", 'default' => null)); // Run the command line parser try { $commandLineResult = $consoleParser->parse(); // Run the service if (!($result = $service->import($commandLineResult))) { throw new \Exception("Import process failed"); } $message = ""; $level = Logger\AbstractLogger::INFO; if (isset($result["message"])) { $message .= $result["message"] . "\n"; } if (isset($result["successList"]) && count($result["successList"])) { $message .= "# Success\n"; $message .= implode("\n", $result["successList"]) . "\n"; } if (isset($result["errorsList"]) && count($result["errorsList"])) { $level = Logger\AbstractLogger::WARNING; $message .= "# Errors \n"; $message .= implode("\n", $result["errorsList"]) . "\n"; } echo $message . "\n"; $logger->logMessage($level, $message); // Boom goes your request } catch (\Exception $exc) { $message = $exc->getMessage(); $logger->logMessage(Logger\AbstractLogger::CRITICAL, $message); $consoleParser->displayError($message); }
* @package PharUtil */ // Include the Console_CommandLine package. require_once 'Console/CommandLine.php'; require_once 'PharUtil/RemotePharVerifier.php'; // create the parser $parser = new Console_CommandLine(array('description' => 'Verify Phar archive signature using a public key file', 'version' => '@package_version@', 'name' => 'phar-verify')); $parser->addOption('public', array('short_name' => '-P', 'long_name' => '--public', 'action' => 'StoreString', 'default' => './cert/pub.pem', 'description' => "Public key file (PEM) to verify signature\n(./cert/pub.pem by default)")); $parser->addOption('nosign', array('short_name' => '-n', 'long_name' => '--ns', 'action' => 'StoreTrue', 'description' => 'Archive is not signed, don\'t require an OpenSSL signature')); $parser->addOption('temp', array('short_name' => '-t', 'long_name' => '--temp', 'action' => 'StoreString', 'description' => 'Temporary directory (' . sys_get_temp_dir() . ' by default)')); $parser->addArgument('phar', array('action' => 'StoreString', 'description' => "Input Phar archive URI e.g.\n/path/to/local/phar.phar or http://path/to/remote/phar.phar")); // run the parser try { $result = $parser->parse(); } catch (Exception $exc) { $parser->displayError($exc->getMessage()); } $options = $result->options; $args = $result->args; echo $parser->name . ' ' . $parser->version . PHP_EOL . PHP_EOL; // validate parameters if (substr($args['phar'], -5) !== '.phar') { $parser->displayError("Input Phar must have .phar extension, {$args['phar']} given.", 2); } if ($options['nosign']) { $options['public'] = null; // no public key } if ($options['public']) { if (!file_exists($options['public']) || !is_readable($options['public'])) { $parser->displayError("Public key in '{$options['public']}' does not exist or is not readable.", 4);
set_include_path(".:" . get_include_path()); require_once "bootstrap.php"; // Instanciate export service $service = new Alternc_Tools_Mailbox_Export(array("db" => $db)); // Instanciate command line parser $consoleParser = new Console_CommandLine(array("description" => "Exports Alternc mailboxes to a file for export.")); // Configure command line parser $consoleParser->add_version_option = false; $consoleParser->addOption("output_file", array("help_name" => "/tmp/out.json", "short_name" => "-o", "long_name" => "--output-file", "description" => "Export file name and path", 'default' => $service->default_output)); $consoleParser->addOption("single_domain", array("help_name" => "domain.com", "short_name" => "-d", "long_name" => "--single-domain", "description" => "A single domain to export")); $consoleParser->addOption("single_account", array("help_name" => "foobar", "short_name" => "-a", "long_name" => "--single-account", "description" => "A single account name (i.e. AlternC login) to export\n")); $consoleParser->addOption("exclude_mails", array("help_name" => "/tmp/mailboxes.txt", "long_name" => "--exclude-mails", "description" => "Path of a file containing mailboxes to exclude, separated by breaklines")); $consoleParser->addOption("include_mails", array("help_name" => "/tmp/mailboxes.txt", "long_name" => "--include-mails", "description" => "Path of a file containing mailboxes to include, separated by breaklines")); $consoleParser->addOption("exclude_domain", array("help_name" => "/tmp/domain.txt", "long_name" => "--exclude-domains", "description" => "Path of a file containing domains to include, separated by breaklines")); $consoleParser->addOption("include_domains", array("help_name" => "/tmp/domain.txt", "long_name" => "--include-domains", "description" => "Path of a file containing domains to exclude, separated by breaklines")); // Run the command line parser try { $commandLineResult = $consoleParser->parse(); // Run the service if (!($result = $service->run($commandLineResult))) { throw new \Exception("Export process failed"); } $msg = $result["message"]; $logger->logMessage(Logger\AbstractLogger::INFO, $msg); echo $msg . "\n"; // Boom goes your request } catch (\Exception $exc) { $msg = $exc->getMessage(); $logger->logMessage(Logger\AbstractLogger::CRITICAL, $msg); $consoleParser->displayError($msg); }
/** * Entry-point for Erebot. * * \return * This method never returns. * Instead, the program exits with an appropriate * return code when Erebot is stopped. */ public static function run() { // Apply patches. \Erebot\Patches::patch(); // Load the configuration for the Dependency Injection Container. $dic = new \Symfony\Component\DependencyInjection\ContainerBuilder(); $dic->setParameter('Erebot.src_dir', __DIR__); $loader = new \Symfony\Component\DependencyInjection\Loader\XmlFileLoader($dic, new \Symfony\Component\Config\FileLocator(getcwd())); $dicConfig = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'defaults.xml'; $dicCwdConfig = getcwd() . DIRECTORY_SEPARATOR . 'defaults.xml'; if (!strncasecmp(__FILE__, 'phar://', 7)) { if (!file_exists($dicCwdConfig)) { copy($dicConfig, $dicCwdConfig); } $dicConfig = $dicCwdConfig; } elseif (file_exists($dicCwdConfig)) { $dicConfig = $dicCwdConfig; } $loader->load($dicConfig); // Determine availability of PHP extensions // needed by some of the command-line options. $hasPosix = in_array('posix', get_loaded_extensions()); $hasPcntl = in_array('pcntl', get_loaded_extensions()); $logger = $dic->get('logging'); $localeGetter = $dic->getParameter('i18n.default_getter'); $coreTranslatorCls = $dic->getParameter('core.classes.i18n'); $translator = new $coreTranslatorCls("Erebot\\Core"); $categories = array('LC_MESSAGES', 'LC_MONETARY', 'LC_TIME', 'LC_NUMERIC'); foreach ($categories as $category) { $locales = call_user_func($localeGetter); $locales = empty($locales) ? array() : array($locales); $localeSources = array('LANGUAGE' => true, 'LC_ALL' => false, $category => false, 'LANG' => false); foreach ($localeSources as $source => $multiple) { if (!isset($_SERVER[$source])) { continue; } if ($multiple) { $locales = explode(':', $_SERVER[$source]); } else { $locales = array($_SERVER[$source]); } break; } $translator->setLocale($translator->nameToCategory($category), $locales); } // Also, include some information about the version // of currently loaded PHAR modules, if any. $version = 'dev-master'; if (!strncmp(__FILE__, 'phar://', 7)) { $phar = new \Phar(\Phar::running(true)); $md = $phar->getMetadata(); $version = $md['version']; } if (defined('Erebot_PHARS')) { $phars = unserialize(Erebot_PHARS); ksort($phars); foreach ($phars as $module => $metadata) { if (strncasecmp($module, 'Erebot_Module_', 14)) { continue; } $version .= "\n with {$module} version {$metadata['version']}"; } } \Console_CommandLine::registerAction('StoreProxy', '\\Erebot\\Console\\StoreProxyAction'); $parser = new \Console_CommandLine(array('name' => 'Erebot', 'description' => $translator->gettext('A modular IRC bot written in PHP'), 'version' => $version, 'add_help_option' => true, 'add_version_option' => true, 'force_posix' => false)); $parser->accept(new \Erebot\Console\MessageProvider()); $parser->renderer->options_on_different_lines = true; $defaultConfigFile = getcwd() . DIRECTORY_SEPARATOR . 'Erebot.xml'; $parser->addOption('config', array('short_name' => '-c', 'long_name' => '--config', 'description' => $translator->gettext('Path to the configuration file to use instead ' . 'of "Erebot.xml", relative to the current ' . 'directory.'), 'help_name' => 'FILE', 'action' => 'StoreString', 'default' => $defaultConfigFile)); $parser->addOption('daemon', array('short_name' => '-d', 'long_name' => '--daemon', 'description' => $translator->gettext('Run the bot in the background (daemon).' . ' [requires the POSIX and pcntl extensions]'), 'action' => 'StoreTrue')); $noDaemon = new \Erebot\Console\ParallelOption('no_daemon', array('short_name' => '-n', 'long_name' => '--no-daemon', 'description' => $translator->gettext('Do not run the bot in the background. ' . 'This is the default, unless the -d option ' . 'is used or the bot is configured otherwise.'), 'action' => 'StoreProxy', 'action_params' => array('option' => 'daemon'))); $parser->addOption($noDaemon); $parser->addOption('pidfile', array('short_name' => '-p', 'long_name' => '--pidfile', 'description' => $translator->gettext("Store the bot's PID in this file."), 'help_name' => 'FILE', 'action' => 'StoreString', 'default' => null)); $parser->addOption('group', array('short_name' => '-g', 'long_name' => '--group', 'description' => $translator->gettext('Set group identity to this GID/group during ' . 'startup. The default is to NOT change group ' . 'identity, unless configured otherwise.' . ' [requires the POSIX extension]'), 'help_name' => 'GROUP/GID', 'action' => 'StoreString', 'default' => null)); $parser->addOption('user', array('short_name' => '-u', 'long_name' => '--user', 'description' => $translator->gettext('Set user identity to this UID/username during ' . 'startup. The default is to NOT change user ' . 'identity, unless configured otherwise.' . ' [requires the POSIX extension]'), 'help_name' => 'USER/UID', 'action' => 'StoreString', 'default' => null)); try { $parsed = $parser->parse(); } catch (\Exception $exc) { $parser->displayError($exc->getMessage()); exit(1); } // Parse the configuration file. $config = new \Erebot\Config\Main($parsed->options['config'], \Erebot\Config\Main::LOAD_FROM_FILE, $translator); $coreCls = $dic->getParameter('core.classes.core'); $bot = new $coreCls($config, $translator); $dic->set('bot', $bot); // Use values from the XML configuration file // if there is no override from the command line. $overrides = array('daemon' => 'mustDaemonize', 'group' => 'getGroupIdentity', 'user' => 'getUserIdentity', 'pidfile' => 'getPidfile'); foreach ($overrides as $option => $func) { if ($parsed->options[$option] === null) { $parsed->options[$option] = $config->{$func}(); } } /* Handle daemonization. * See also: * - http://www.itp.uzh.ch/~dpotter/howto/daemonize * - http://andytson.com/blog/2010/05/daemonising-a-php-cli-script */ if ($parsed->options['daemon']) { if (!$hasPosix) { $logger->error($translator->gettext('The posix extension is required in order ' . 'to start the bot in the background')); exit(1); } if (!$hasPcntl) { $logger->error($translator->gettext('The pcntl extension is required in order ' . 'to start the bot in the background')); exit(1); } foreach (array('SIGCHLD', 'SIGUSR1', 'SIGALRM') as $signal) { if (defined($signal)) { pcntl_signal(constant($signal), array(__CLASS__, 'startupSighandler')); } } $logger->info($translator->gettext('Starting the bot in the background...')); $pid = pcntl_fork(); if ($pid < 0) { $logger->error($translator->gettext('Could not start in the background (unable to fork)')); exit(1); } if ($pid > 0) { pcntl_wait($dummy, WUNTRACED); pcntl_alarm(2); pcntl_signal_dispatch(); exit(1); } $parent = posix_getppid(); // Ignore some of the signals. foreach (array('SIGTSTP', 'SIGTOU', 'SIGTIN', 'SIGHUP') as $signal) { if (defined($signal)) { pcntl_signal(constant($signal), SIG_IGN); } } // Restore the signal handlers we messed with. foreach (array('SIGCHLD', 'SIGUSR1', 'SIGALRM') as $signal) { if (defined($signal)) { pcntl_signal(constant($signal), SIG_DFL); } } umask(0); if (umask() != 0) { $logger->warning($translator->gettext('Could not change umask')); } if (posix_setsid() == -1) { $logger->error($translator->gettext('Could not start in the background (unable to setsid)')); exit(1); } // Prevent the child from ever acquiring a controlling terminal. // Not required under Linux, but required by at least System V. $pid = pcntl_fork(); if ($pid < 0) { $logger->error($translator->gettext('Could not start in the background (unable to fork)')); exit(1); } if ($pid > 0) { exit(0); } // Avoid locking up the current directory. if (!chdir(DIRECTORY_SEPARATOR)) { $logger->error($translator->gettext('Could not chdir to "%(path)s"'), array('path' => DIRECTORY_SEPARATOR)); } // Explicitly close the magic stream-constants (just in case). foreach (array('STDIN', 'STDOUT', 'STDERR') as $stream) { if (defined($stream)) { fclose(constant($stream)); } } // Re-open them with the system's blackhole. /** * \todo * should be made portable, but the requirement on the POSIX * extension prevents this, so this is okay for now. */ $stdin = fopen('/dev/null', 'r'); $stdout = fopen('/dev/null', 'w'); $stderr = fopen('/dev/null', 'w'); if (defined('SIGUSR1')) { posix_kill($parent, SIGUSR1); } $logger->info($translator->gettext('Successfully started in the background')); } try { /// @TODO: Check the interface or something like that. $identd = $dic->get('identd'); } catch (\InvalidArgumentException $e) { $identd = null; } try { /// @TODO: Check the interface or something like that. $prompt = $dic->get('prompt'); } catch (\InvalidArgumentException $e) { $prompt = null; } // Change group identity if necessary. if ($parsed->options['group'] !== null && $parsed->options['group'] != '') { if (!$hasPosix) { $logger->warning($translator->gettext('The posix extension is needed in order ' . 'to change group identity.')); } elseif (posix_getuid() !== 0) { $logger->warning($translator->gettext('Only root can change group identity! ' . 'Your current UID is %(uid)d'), array('uid' => posix_getuid())); } else { if (ctype_digit($parsed->options['group'])) { $info = posix_getgrgid((int) $parsed->options['group']); } else { $info = posix_getgrnam($parsed->options['group']); } if ($info === false) { $logger->error($translator->gettext('No such group "%(group)s"'), array('group' => $parsed->options['group'])); exit(1); } if (!posix_setgid($info['gid'])) { $logger->error($translator->gettext('Could not set group identity ' . 'to "%(name)s" (%(id)d)'), array('id' => $info['gid'], 'name' => $info['name'])); exit(1); } $logger->debug($translator->gettext('Successfully changed group identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['gid'])); } } // Change user identity if necessary. if ($parsed->options['user'] !== null || $parsed->options['user'] != '') { if (!$hasPosix) { $logger->warning($translator->gettext('The posix extension is needed in order ' . 'to change user identity.')); } elseif (posix_getuid() !== 0) { $logger->warning($translator->gettext('Only root can change user identity! ' . 'Your current UID is %(uid)d'), array('uid' => posix_getuid())); } else { if (ctype_digit($parsed->options['user'])) { $info = posix_getpwuid((int) $parsed->options['user']); } else { $info = posix_getpwnam($parsed->options['user']); } if ($info === false) { $logger->error($translator->gettext('No such user "%(user)s"'), array('user' => $parsed->options['user'])); exit(1); } if (!posix_setuid($info['uid'])) { $logger->error($translator->gettext('Could not set user identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['uid'])); exit(1); } $logger->debug($translator->gettext('Successfully changed user identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['uid'])); } } // Write new pidfile. if ($parsed->options['pidfile'] !== null && $parsed->options['pidfile'] != '') { $pid = @file_get_contents($parsed->options['pidfile']); // If the file already existed, the bot may already be started // or it may contain data not related to Erebot at all. if ($pid !== false) { $pid = (int) rtrim($pid); if (!$pid) { $logger->error($translator->gettext('The pidfile (%(pidfile)s) contained garbage. ' . 'Exiting'), array('pidfile' => $parsed->options['pidfile'])); exit(1); } else { posix_kill($pid, 0); $res = posix_errno(); switch ($res) { case 0: // No error. $logger->error($translator->gettext('Erebot is already running ' . 'with PID %(pid)d'), array('pid' => $pid)); exit(1); case 3: // ESRCH. $logger->warning($translator->gettext('Found stalled PID %(pid)d in pidfile ' . '"%(pidfile)s". Removing it'), array('pidfile' => $parsed->options['pidfile'], 'pid' => $pid)); @unlink($parsed->options['pidfile']); break; case 1: // EPERM. $logger->error($translator->gettext('Found another program\'s PID %(pid)d in ' . 'pidfile "%(pidfile)s". Exiting'), array('pidfile' => $parsed->options['pidfile'], 'pid' => $pid)); exit(1); default: $logger->error($translator->gettext('Unknown error while checking for ' . 'the existence of another running ' . 'instance of Erebot (%(error)s)'), array('error' => posix_get_last_error())); exit(1); } } } $pidfile = fopen($parsed->options['pidfile'], 'wt'); flock($pidfile, LOCK_EX | LOCK_NB, $wouldBlock); if ($wouldBlock) { $logger->error($translator->gettext('Could not lock pidfile (%(pidfile)s). ' . 'Is the bot already running?'), array('pidfile' => $parsed->options['pidfile'])); exit(1); } $pid = sprintf("%u\n", getmypid()); $res = fwrite($pidfile, $pid); if ($res !== strlen($pid)) { $logger->error($translator->gettext('Unable to write PID to pidfile (%(pidfile)s)'), array('pidfile' => $parsed->options['pidfile'])); exit(1); } $logger->debug($translator->gettext('PID (%(pid)d) written into %(pidfile)s'), array('pidfile' => $parsed->options['pidfile'], 'pid' => getmypid())); // Register a callback to remove the pidfile upon exit. register_shutdown_function(array(__CLASS__, 'cleanupPidfile'), $pidfile, $parsed->options['pidfile']); } // Display a desperate warning when run as user root. if ($hasPosix && posix_getuid() === 0) { $logger->warning($translator->gettext('You SHOULD NOT run Erebot as root!')); } if ($identd !== null) { $identd->connect(); } if ($prompt !== null) { $prompt->connect(); } // This doesn't return until we purposely // make the bot drop all active connections. $bot->start($dic->get('factory.connection')); exit(0); }
*/ require_once 'Console/CommandLine.php'; // create the parser $parser = new Console_CommandLine(array('description' => 'Check to see if a PHAR archive rebuild is necessary.', 'version' => '@package_version@', 'name' => 'phar-file-checksums')); $parser->addOption('src', array('short_name' => '-s', 'long_name' => '--src', 'action' => 'StoreString', 'default' => './src', 'description' => "Source files directory\n(./src)")); $parser->addOption('exclude_files', array('short_name' => '-x', 'long_name' => '--exclude', 'action' => 'StoreString', 'default' => '~$', 'description' => "Space separated regular expressions of filenames that should be excluded\n(\"~\$\" by default)")); $parser->addOption('exclude_dirs', array('short_name' => '-X', 'long_name' => '--exclude-dir', 'action' => 'StoreString', 'default' => '/\\.svn /\\.git', 'description' => "Space separated regular expressions of directories that should be excluded\n(\"/\\.svn /\\.git\" by default)")); $parser->addOption('quiet', array('short_name' => '-q', 'long_name' => '--quiet', 'action' => 'StoreTrue', 'description' => 'Suppress most of the output statements.')); $parser->addOption('verbose', array('short_name' => '-v', 'long_name' => '--verbose', 'action' => 'StoreTrue', 'description' => 'Outputs additional information to the console.')); $parser->addOption('checksum_file', array('short_name' => '-c', 'long_name' => '--checksumfile', 'action' => 'StoreString', 'default' => './checksum-file.json', 'description' => "JSON file for storing source file checksums \n(./checksum-file.json).")); $parser->addOption('nowrites_checksum', array('long_name' => '--no-save-checksums', 'action' => 'StoreTrue', 'description' => 'Do not save checksums obtained to the checksum file.')); // run the parser try { $result = $parser->parse(); } catch (Exception $exc) { $parser->displayError($exc->getMessage()); } $options = $result->options; // Use a constant to avoid globals. define('QUIET_MODE', (bool) $options['quiet']); define('VERBOSE_MODE', (bool) $options['verbose']); if (!QUIET_MODE) { echo $parser->name . ' ' . $parser->version . PHP_EOL . PHP_EOL; } // validate parameters if (!class_exists('Phar')) { $parser->displayError("No Phar support found, you need to build and enable Phar extension. Exiting...", 10); } if (!is_dir($options['src']) || !is_readable($options['src'])) { $parser->displayError("Source directory in '{$options['src']}' does not exist or is not readable.\n,", 5); }
protected function parseOptions() { $argf = new ARGF(); $argc =& $argf->argc(); $argv =& $argf->argv(); $optparser = new Console_CommandLine(array('name' => basename($argv[0]), 'description' => 'A php migratory tool from 4 to 5 written in pure php', 'version' => '0.0.1')); $optparser->addOption('format', array('choices' => array('nodes', 'string', 'terminals', 'tokens', 'tree'), 'default' => 'string', 'description' => 'format of output (default: string)', 'long_name' => '--format', 'short_name' => '-f')); $optparser->addOption('in_place', array('action' => 'StoreTrue', 'description' => 'edit files in place', 'long_name' => '--in-place', 'short_name' => '-i')); $optparser->addOption('recursive', array('action' => 'StoreTrue', 'description' => 'migrate recursively', 'long_name' => '--recursive', 'short_name' => '-r')); $optparser->addOption('suffixes', array('default' => 'php,php4,php5,inc', 'description' => 'suffixes of files to be migrated (default: php,php4,php5,inc)', 'long_name' => '--suffixes', 'short_name' => '-s')); $optparser->addArgument('files', array('multiple' => true)); try { $result = $optparser->parse(); } catch (Exception $e) { $optparser->displayError($e->getMessage()); } $options =& $result->options; $args =& $result->args['files']; if ($options['recursive']) { if (count($args) < 2) { $optparser->displayError('target directory must be specified with -r'); } $target = $args[count($args) - 1]; if (!is_dir($target) && file_exists($target)) { $optparser->displayError('target directory cannot be a regular file'); } } $options['suffixes'] = split(',', $options['suffixes']); return array('options' => $options, 'args' => $args); }
/** * 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; } } } }
} define("CUPCAKE_PATH", $cupcake_path); if (CUPCAKE_PATH === null) { echo "\nCupcake Not Found\nMake sure to set the include_path\n"; exit; } # Load any commands extended by the application from /cli if (file_exists("cli") && is_dir("cli")) { foreach (glob("cli/*.php") as $cli_file) { include_once $cli_file; } } try { $result = $command->parse(); } catch (Exception $exc) { $command->displayError($exc->getMessage()); exit; } $options = $result->options; foreach ($options as $k => $name) { if (!empty($name)) { $terminal = $command->options[$k]; $callback = $terminal->callback; if (is_string($callback) && strlen($callback) > 0) { $callback($options, $terminal); } } } function application_path($opts = array()) { $path = empty($opts['path']) === true ? "." : $opts['path'];
protected function parseOptions() { $argf = new ARGF(); $argc =& $argf->argc(); $argv =& $argf->argv(); $optparser = new Console_CommandLine(array('name' => basename($argv[0]), 'description' => 'Find bugs in PHP5 Programs', 'version' => '0.0.1')); $optparser->addOption('format', array('long_name' => '--format', 'help_name' => 'FORMAT', 'choices' => array('nodes', 'string', 'terminals', 'tokens', 'tree'), 'default' => 'string', 'description' => 'format of output (default: string)')); $optparser->addOption('suffixes', array('long_name' => '--suffixes', 'help_name' => 'PATTERNS', 'default' => 'php,yml', 'description' => 'suffixes of files to be checked (default: php,yml)')); $optparser->addOption('priority', array('long_name' => '--priority', 'help_name' => 'LEVEL', 'choices' => array('low', 'middle', 'high'), 'default' => 'middle', 'description' => 'specify priority for bug reporting (default: middle)')); $optparser->addOption('recursive', array('action' => 'StoreTrue', 'description' => 'check recursively', 'long_name' => '--recursive', 'short_name' => '-r')); $optparser->addOption('debug', array('action' => 'StoreTrue', 'description' => 'turn on debug mode', 'long_name' => '--debug')); $optparser->addArgument('files', array('multiple' => true)); try { $result = $optparser->parse(); } catch (Exception $e) { $optparser->displayError($e->getMessage()); } $options =& $result->options; $args =& $result->args['files']; if ($options['recursive']) { if (count($args) < 2) { $optparser->displayError('target directory must be specified with -r'); } $target = $args[count($args) - 1]; if (!is_dir($target) && file_exists($target)) { $optparser->displayError('target directory cannot be a regular file'); } } $options['suffixes'] = split(',', $options['suffixes']); return array('options' => $options, 'args' => $args); }
// create the parser $parser = new Console_CommandLine(array('description' => 'Build a phar archive and sign it using a private key from a given file', 'version' => '@package_version@', 'name' => 'phar-build')); $parser->addOption('src', array('short_name' => '-s', 'long_name' => '--src', 'action' => 'StoreString', 'default' => './src', 'description' => "Source files directory\n(./src)")); $parser->addOption('stub', array('short_name' => '-S', 'long_name' => '--stub', 'action' => 'StoreString', 'default' => './stub.php', 'description' => "(optional) stub file for phar \n(./stub.php)\nIf stub file does not exist, default stub will be used.")); $parser->addOption('exclude_files', array('short_name' => '-x', 'long_name' => '--exclude', 'action' => 'StoreString', 'default' => '~$', 'description' => "Space separated regular expressions of filenames that should be excluded\n(\"~\$\" by default)")); $parser->addOption('exclude_dirs', array('short_name' => '-X', 'long_name' => '--exclude-dir', 'action' => 'StoreString', 'default' => '/\\.svn /\\.git', 'description' => "Space separated regular expressions of directories that should be excluded\n(\"/\\.svn /\\.git\" by default)")); $parser->addOption('private', array('short_name' => '-p', 'long_name' => '--private', 'action' => 'StoreString', 'default' => './cert/priv.pem', 'description' => "Private key file (PEM) to generate signature\n(./cert/priv.pem)")); $parser->addOption('public', array('short_name' => '-P', 'long_name' => '--public', 'action' => 'StoreString', 'default' => './cert/pub.pem', 'description' => "Public key file (PEM) to verify signature\n(./cert/pub.pem)")); $parser->addOption('nosign', array('short_name' => '-n', 'long_name' => '--ns', 'action' => 'StoreTrue', 'description' => 'Don\'t sign the Phar archive')); $parser->addOption('quiet', array('short_name' => '-q', 'long_name' => '--quiet', 'action' => 'StoreTrue', 'description' => 'Suppress most of the output statements.')); $parser->addOption('phar', array('long_name' => '--phar', 'action' => 'StoreString', 'default' => './output.phar', 'description' => "Output Phar archive filename\n(./output.phar)")); // run the parser try { $result = $parser->parse(); } catch (Exception $exc) { $parser->displayError($exc->getMessage()); } $options = $result->options; // Use a constant to avoid globals. define('QUIET_MODE', (bool) $options['quiet']); if (!QUIET_MODE) { echo $parser->name . ' ' . $parser->version . PHP_EOL . PHP_EOL; } // validate parameters if (!class_exists('Phar')) { $parser->displayError("No Phar support found, you need to build and enable Phar extension. Exiting...", 10); } if (!Phar::canWrite()) { $parser->displayError("Phar writing support is disabled in this PHP installation, set phar.readonly=0 in php.ini!", 10); } if (substr($options['phar'], -5) !== '.phar') {
/** * コマンドの実行 * * @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()); } }
#!/usr/bin/env php <?php namespace phinde; require_once __DIR__ . '/../src/init.php'; $cc = new \Console_CommandLine(); $cc->description = 'phinde URL processor'; $cc->version = '0.0.1'; $cc->addOption('force', array('short_name' => '-f', 'long_name' => '--force', 'description' => 'Always process URL, even when it did not change', 'action' => 'StoreTrue', 'default' => false)); $cc->addOption('showLinksOnly', array('short_name' => '-s', 'long_name' => '--show-links', 'description' => 'Only show which URLs were found', 'action' => 'StoreTrue', 'default' => false)); $cc->addArgument('url', array('description' => 'URL to process', 'multiple' => false)); $cc->addArgument('actions', array('description' => 'Actions to take', 'multiple' => true, 'optional' => true, 'choices' => array('index', 'crawl'), 'default' => array('index', 'crawl'))); try { $res = $cc->parse(); } catch (\Exception $e) { $cc->displayError($e->getMessage()); } $url = $res->args['url']; $url = Helper::addSchema($url); $urlObj = new \Net_URL2($url); $url = $urlObj->getNormalizedURL(); if (!Helper::isUrlAllowed($url)) { Log::error("Domain is not allowed; not crawling"); exit(2); } try { $actions = array(); foreach ($res->args['actions'] as $action) { if ($action == 'crawl') { $crawler = new Crawler(); $crawler->setShowLinksOnly($res->options['showLinksOnly']);
/** * Let the CLI option parser parse the options. * * @param object $parser Option parser * * @return array Array of file names */ protected function parseParameters(\Console_CommandLine $parser) { try { $result = $parser->parse(); $rendClass = '\\phpsqllint\\Renderer_' . ucfirst($result->options['renderer']); $this->renderer = new $rendClass(); $this->format = $result->options['format']; $this->highlight = $result->options['highlight']; if ($this->highlight == 'auto') { if (php_sapi_name() == 'cli') { //default coloring to enabled, except // when piping | to another tool $this->highlight = 'ansi'; if (function_exists('posix_isatty') && !posix_isatty(STDOUT)) { $this->highlight = 'none'; } } else { //no idea where we are, so do not highlight $this->highlight = 'none'; } } foreach ($result->args['sql_files'] as $filename) { if ($filename == '-') { continue; } if (!file_exists($filename)) { throw new \Exception('File does not exist: ' . $filename); } if (!is_file($filename)) { throw new \Exception('Not a file: ' . $filename); } } return $result->args['sql_files']; } catch (\Exception $exc) { $parser->displayError($exc->getMessage()); } }
* * @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 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()); }
function check($args) { global $argv; // Command line parser $parser = new Console_CommandLine(array('name' => $argv[0] . ' ' . $argv[1], 'description' => 'Check disk usage', 'version' => '0.0.1')); $parser->addOption('rrd_file', array('short_name' => '-f', 'description' => 'RRD file', 'action' => 'StoreString')); // $parser->addOption('datasource', array( // 'short_name' => '-d', // // 'long_name' => '--datasource', // 'description' => 'Disk available RRD datasource', // 'action' => 'StoreString' // )); // $parser->addOption('datasource', array( // 'short_name' => '-u', // // 'long_name' => '--datasource', // 'description' => 'Disk used RRD datasource', // 'action' => 'StoreString' // )); $parser->addOption('warning', array('short_name' => '-w', 'description' => 'Warning value (%, integer value, default: 20)', 'action' => 'StoreFloat', 'default' => 20)); $parser->addOption('critical', array('short_name' => '-c', 'description' => 'Critical value (%, integer value, default: 10)', 'action' => 'StoreFloat', 'default' => 10)); try { $result = $parser->parse(count($args), $args); $rrd_file = $result->options['rrd_file']; if (empty($rrd_file)) { echo 'No rrd_file specified' . "\n"; return NAGIOS_UNKNOWN; } if (!file_exists($rrd_file)) { echo 'File ' . $rrd_file . ' doesn\'t seem to exist' . "\n"; return NAGIOS_UNKNOWN; } $v = new RRDValue($rrd_file); // $datasource = $result->options['datasource']; // if (empty($datasource)) { // echo 'No datasource specified'."\n"; // echo 'Available datasources: '.implode(', ', $v->getDatasources())."\n"; // return NAGIOS_UNKNOWN; // } $disk_available_datasource = 'DISKFREE_available'; $disk_used_datasource = 'DISKFREE_used'; $disk_available_value = $v->get($disk_available_datasource); $disk_used_value = $v->get($disk_used_datasource); if (is_nan($disk_available_value)) { echo 'Can\'t read disk available RRD value' . "\n"; return NAGIOS_UNKNOWN; } if (is_nan($disk_used_value)) { echo 'Can\'t read disk free RRD value' . "\n"; return NAGIOS_UNKNOWN; } $percentage_available = $disk_available_value / ($disk_available_value + $disk_used_value); $percentage_available = round($percentage_available * 100); $disk_available_value_mb = round($disk_available_value / 1024 / 1024 / 1024, 1); if ($percentage_available < $result->options['critical']) { echo "DISK CRITICAL - free space: {$disk_available_value_mb} GB ({$percentage_available}%)"; return NAGIOS_CRITICAL; } else { if ($percentage_available < $result->options['warning']) { echo "DISK WARNING - free space: {$disk_available_value_mb} GB ({$percentage_available}%)"; return NAGIOS_WARNING; } else { echo "DISK OK - free space: {$disk_available_value_mb} GB ({$percentage_available}%)"; return NAGIOS_OK; } } } catch (Exception $exc) { $parser->displayError($exc->getMessage()); return NAGIOS_UNKNOWN; } }
public static function parseArguments() { $main = new \Console_CommandLine(); $main->addOption('out', array('short_name' => '-o', 'long_name' => '--out', 'action' => 'StoreString', 'description' => 'destination directory for generated files', 'default' => './')); $main->addOption('include', array('short_name' => '-i', 'long_name' => '--include', 'action' => 'StoreArray', 'description' => 'define an include path (can be repeated)', 'multiple' => true)); $main->addOption('json', array('short_name' => '-j', 'long_name' => '--json', 'action' => 'StoreTrue', 'description' => 'turn on ProtoJson Javascript file generation')); $main->addOption('protoc', array('long_name' => '--protoc', 'action' => 'StoreString', 'default' => 'protoc', 'description' => 'protoc compiler executable path')); $main->addOption('skipImported', array('long_name' => '--skip-imported', 'action' => 'StoreTrue', 'default' => false, 'description' => 'do not generate imported proto files')); $main->addOption('comments', array('long_name' => '--comments', 'action' => 'StoreTrue', 'description' => 'port .proto comments to generated code')); $main->addOption('insertions', array('long_name' => '--insertions', 'action' => 'StoreTrue', 'description' => 'generate @@protoc insertion points')); $main->addOption('define', array('short_name' => '-D', 'long_name' => '--define', 'action' => 'StoreArray', 'multiple' => true, 'description' => 'define a generator option (ie: -Dmultifile -Dsuffix=pb.php)')); $main->addOption('verbose', array('short_name' => '-v', 'long_name' => '--verbose', 'action' => 'StoreTrue', 'description' => 'turn on verbose output')); $main->addArgument('protos', array('multiple' => true, 'description' => 'proto files')); try { echo 'Protobuf-PHP ' . Protobuf::VERSION . ' by Ivan -StudyDrSlump- Montes' . PHP_EOL . PHP_EOL; $result = $main->parse(); return $result; } catch (\Exception $e) { $main->displayError($e->getMessage()); exit(1); } }
/** * 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); } } }