Beispiel #1
0
	/**
	 * Set up parser and common parser options
	 */
	private function setUpCommonParser() {
		// Create the parser
		$this->parser = new Console_CommandLine(array(
		    'description' => static::DESCRIPTION,
		    'version'     => static::VERSION
		));

		// Add an option to make the program verbose
		$this->parser->addOption('verbose', array(
		    'short_name'  => '-v',
		    'long_name'   => '--verbose',
		    'action'      => 'StoreTrue',
		    'description' => 'turn on verbose output'
		));
	}
 protected function _readCommandLineRequest()
 {
     $parser = new Console_CommandLine();
     $parser->description = "Lion Framework " . LION_VERSION_NUMBER . ' (built: ' . LION_VERSION_BUILD_DATE . ")\n" . "An open source PHP Framework for rapid development of PHP web applications";
     $parser->version = LION_VERSION_NUMBER;
     $parser->addOption('clearcache', array('short_name' => '-c', 'long_name' => '--clearcache', 'description' => 'clear the cache', 'action' => 'StoreTrue'));
     // Adding an option that will store a string
     $parser->addOption('info', array('short_name' => '-i', 'long_name' => '--info', 'description' => 'show the runtime directives', 'action' => 'StoreTrue'));
     // Adding an option that will store a string
     $parser->addOption('bootstrap', array('short_name' => '-b', 'long_name' => '--bootstrap', 'description' => 'bootstrap a new application', 'action' => 'StoreTrue'));
     // Adding an option that will store a string
     $parser->addOption('controller', array('long_name' => '--controller', 'description' => 'executes the given controller', 'action' => 'StoreString'));
     // Adding an option that will store a string
     $parser->addOption('action', array('long_name' => '--action', 'description' => 'executes the given action', 'action' => 'StoreString'));
     return $parser;
 }
Beispiel #3
0
 /**
  * Loads and parses command line parameters.
  * Also takes care of the --help switch.
  *
  * @return void
  *
  * @throws Exception When the rST file does not exist
  */
 protected function loadParams()
 {
     $parser = new \Console_CommandLine();
     $parser->description = 'Deploy reStructuredText documents into a wiki';
     $parser->version = '@version@';
     $parser->addArgument('file', array('description' => 'rST file path'));
     $parser->addOption('driver', array('long_name' => '--driver', 'optional' => true, 'action' => 'StoreString', 'description' => 'Wiki driver to use'));
     //No -D options: https://pear.php.net/bugs/bug.php?id=19163
     //yep, that does not automatically work with new drivers
     Driver_Confluence::loadHelp($parser);
     try {
         $result = $parser->parse();
         foreach (array_keys($result->options) as $key) {
             if ($result->options[$key] === null) {
                 unset($result->options[$key]);
             }
         }
         $this->options = array_merge($this->options, $result->options);
     } catch (\Console_CommandLine_Exception $e) {
         $parser->displayError($e->getMessage());
     }
     $this->file = $result->args['file'];
     if (!file_exists($this->file)) {
         throw new Exception('File does not exist', 2);
     }
 }
Beispiel #4
0
 /**
  * Creates the command line parser and populates it with all allowed
  * options and parameters.
  *
  * @return Console_CommandLine CommandLine object
  */
 protected function createParser()
 {
     $parser = new Console_CommandLine();
     $parser->description = 'CLI interface to GeSHi, the generic syntax highlighter';
     $parser->version = '0.1.0';
     /*
     $parser->addOption('outfile', array(
         'short_name'  => '-o',
         'long_name'   => '--outfile',
         'description' => 'File to save output to',
         'help_name'   => 'FILE',
         'action'      => 'StoreString'
     ));
     */
     $parser->addOption('format', array('short_name' => '-f', 'long_name' => '--format', 'description' => 'Format of file to highlight (e.g. php).', 'help_name' => 'FORMAT', 'action' => 'StoreString', 'default' => false));
     $parser->addOption('renderer', array('short_name' => '-r', 'long_name' => '--renderer', 'description' => 'Renderer to use', 'help_name' => 'RENDERER', 'action' => 'StoreString', 'default' => 'html', 'choices' => array_keys(self::$arRenderers), 'list' => array_keys(self::$arRenderers), 'add_list_option' => true));
     $parser->addArgument('infile', array('help_name' => 'source file'));
     return $parser;
 }
Beispiel #5
0
 /**
  * Loads confluence-specific options into the command line parser
  *
  * @param object $parser Command line parser object
  *
  * @return void
  */
 public static function loadHelp(\Console_CommandLine $parser)
 {
     $parser->addOption('user', array('long_name' => '--user', 'optional' => true, 'action' => 'StoreString', 'description' => 'Confluence user name'));
     $parser->addOption('password', array('long_name' => '--password', 'optional' => true, 'action' => 'StoreString', 'description' => 'Confluence user password'));
     $parser->addOption('no_deploy', array('long_name' => '--no-deploy', 'optional' => true, 'action' => 'StoreTrue', 'description' => 'Do not deploy, echo output only'));
     $parser->addOption('filter', array('long_name' => '--filter', 'optional' => true, 'action' => 'StoreString', 'description' => 'rST filter name (e.g. "aida")'));
     $parser->addOption('confluence_host', array('long_name' => '--confluence-host', 'optional' => true, 'action' => 'StoreString', 'description' => 'Confluence host name (with http://)', 'help_name' => 'host'));
     $parser->addOption('confluence_space', array('long_name' => '--confluence-space', 'optional' => true, 'action' => 'StoreString', 'description' => 'Confluence space name', 'help_name' => 'space'));
     $parser->addOption('confluence_page', array('long_name' => '--confluence-page', 'optional' => true, 'action' => 'StoreString', 'description' => 'Confluence page name', 'help_name' => 'page'));
 }
 /**
  * econtrol constructor
  *
  */
 public function __construct()
 {
     // check if econtrol is running from cli
     if (Checks::cli() === false) {
         echo "Econtrol runs only in php-cli, exiting";
         self::end(1);
     }
     if (defined('EXTENDER_TIMEZONE')) {
         date_default_timezone_set(EXTENDER_TIMEZONE);
     }
     $this->color = new Console_Color2();
     $this->parser = new Console_CommandLine(array('description' => Version::getDescription(), 'version' => Version::getVersion()));
     // add verbose option
     $this->parser->addOption('verbose', array('short_name' => '-v', 'long_name' => '--verbose', 'description' => 'turn on verbose output', 'action' => 'StoreTrue'));
     // add debug option
     $this->parser->addOption('debug', array('short_name' => '-V', 'long_name' => '--debug', 'description' => 'turn on debug output', 'action' => 'StoreTrue'));
     try {
         $check_constants = Checks::constants();
         if ($check_constants !== true) {
             throw new ShellException($check_constants);
         }
         if (array_key_exists('V', getopt("V"))) {
             $verbose = 'DEBUG';
             echo $this->color->convert("\n%r(> Debug mode on <)%n\n");
         } else {
             if (array_key_exists('v', getopt("v"))) {
                 $verbose = 'NOTICE';
                 echo $this->color->convert("\n%y(> Verbose mode on <)%n\n");
             } else {
                 $verbose = false;
             }
         }
         $this->logger = EcontrolLogger::create($verbose);
         $this->tasks = TasksTable::load($this->logger);
         $this->controller = Controller::load($this->parser, $this->logger);
     } catch (Console_CommandLine_Exception $ce) {
         $this->parser->displayError($this->color->convert("\n\n%y" . $ce->getMessage() . "%n\n"));
         self::end(1);
     } 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);
     }
 }
Beispiel #7
0
 /**
  * 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;
 }
Beispiel #8
0
 /**
  * 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);
 }
Beispiel #9
0
    if ($color) {
        if ($medianDiff > 0) {
            $medianDiffStr = $color->convert("%r" . $color->escape($medianDiffStr) . "%n");
        } else {
            $medianDiffStr = $color->convert("%g" . $color->escape($medianDiffStr) . "%n");
        }
    }
    echo $newTime['name'] . ' : ' . $medianDiffStr . PHP_EOL;
    echo sprintf('  median  : %01.2fms -> %01.2fms', $oldMedian, $newMedian) . PHP_EOL;
    echo sprintf('  average : %01.2fms -> %01.2fms', $oldAverage, $newAverage) . PHP_EOL;
    echo sprintf('  max     : %01.2fms -> %01.2fms', $oldMax, $newMax) . PHP_EOL;
    echo PHP_EOL;
}
// Set up the command line parser.
$parser = new Console_CommandLine(array('name' => 'run_benchmarks', 'description' => 'The PieCrust benchmarks suite', 'version' => PieCrust\PieCrustDefaults::VERSION));
$parser->addOption('hostname', array('long_name' => '--hostname', 'description' => "The hostname to use to store the benchmark results.", 'default' => php_uname("n"), 'help_name' => 'HOSTNAME'));
// Parse user arguments.
try {
    $result = $parser->parse();
} catch (Exception $ex) {
    $parser->displayError($ex->getMessage());
    return 1;
}
// Run!
$b = new ApplicationBenchmark();
$newTimes = $b->runAllBenchmarks();
// Get the results and save them.
$hostname = $result->options['hostname'];
if (is_file('benchmarks.yml')) {
    $oldTimes = Yaml::parse('benchmarks.yml');
    if (isset($oldTimes[$hostname])) {
<?php 
/**
 * @since 2015-10-15
 * @author Alban
 * @license GPL v2
 */
// Load bootstrap for autoload and logger
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);
<?php

require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
$parser->description = 'ImageMagick Helper';
$parser->version = '0.1';
$parser->addOption('files', array('short_name' => '-f', 'long_name' => '--files', 'description' => 'target file pattern', 'help_name' => 'PATTERN', 'action' => 'StoreString'));
try {
    $result = $parser->parse();
    // do something with the result object
    if (isset($result->options['files'])) {
        $pattern = $result->options['files'];
        $files = glob($pattern);
        $convert = "C:/Program Files/ImageMagick-6.5.6-Q16-windows/ImageMagick-6.5.6-6/convert.exe";
        $postfix = '_faded';
        if (count($files)) {
            foreach ($files as $file) {
                $ext = substr($file, -4);
                $dirname = dirname($file);
                $basename = basename($file, $ext);
                $cmd = "\"{$convert}\" {$file} -fill white -colorize 80% {$dirname}/{$basename}{$postfix}{$ext}";
                echo $cmd . PHP_EOL;
                system($cmd);
            }
        }
    }
} catch (Exception $exc) {
    $parser->displayError($exc->getMessage());
}
Beispiel #12
0
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;
    }
}
Beispiel #13
0
 *
 * @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());
}
Beispiel #14
0
 * @author Edward Rudd <urkle at outoforder.cc>
 */
if (!defined('__DIR__')) {
    define('__DIR__', dirname(__FILE__));
}
// Pull in the configuration file.. (Yes this actually works)
$config = (include __DIR__ . "/config.php");
// Set debugging if enabled
define('DEBUG', !empty($config->debug));
// Load up the class auto loader
require_once __DIR__ . "/../classes/Init.php";
include "common.php";
$parser = new Console_CommandLine();
$parser->description = "Convers the raw spell icons into strips for the trainer";
$parser->version = "0.0.1";
$parser->addOption('newsize', array('long_name' => '--size', 'description' => 'Size of new icons', 'default' => 64, 'help_name' => 'SIZE', 'action' => 'StoreInt'));
$parser->addOption('prefix', array('long_name' => '--prefix', 'description' => 'The output filename prefix', 'default' => 'trainer-icon-', 'help_name' => 'PREFIX'));
$parser->addArgument('mapfile', array('description' => 'The input JSON map file process', 'help_name' => 'INPUTFILE'));
$parser->addArgument('outputdir', array('description' => 'The output dir for images', 'help_name' => 'OUTPUTDIR'));
try {
    $args = $parser->parse();
} catch (Exception $ex) {
    $parser->displayError($ex->getMessage());
}
$map = json_decode(file_get_contents($args->args['mapfile']));
$size = $args->options['newsize'];
$imagedir = dirname($args->args['mapfile']);
$imageunused = $imagedir . DIRECTORY_SEPARATOR . 'unused';
if (!is_dir($imageunused)) {
    mkdir($imageunused);
}
<?php

// Load vendor lib paths from Composer
require_once 'vendor/autoload.php';
// Actual required libs
require_once 'Console/CommandLine.php';
$cmdline_parser = new Console_CommandLine();
$cmdline_parser->addArgument('inputFile', array('description' => 'Clover XML file'));
$cmdline_parser->addArgument('minPercentage', array('description' => 'Minimum percentage required to pass'));
$cmdline_parser->addOption('print_uncovered', array('short_name' => '-u', 'long_name' => '--uncovered', 'description' => 'Output uncovered lines', 'action' => 'StoreTrue'));
$cmdline_parser->addOption('print_uncovered_verbose', array('short_name' => '-v', 'long_name' => '--uncovered-verbose', 'description' => 'Output uncovered lines - more verbosely', 'action' => 'StoreTrue'));
$cmdline_parser->addOption('print_uncovered_verbose_whitespace', array('short_name' => '-w', 'long_name' => '--uncovered-verbose-whitespace', 'description' => 'Output uncovered lines - even if they contain only whitespace', 'action' => 'StoreTrue'));
$cmdline_result = $cmdline_parser->parse();
$inputFile = $cmdline_result->args['inputFile'];
$percentage = min(100, max(0, (int) $cmdline_result->args['minPercentage']));
if (!file_exists($inputFile)) {
    throw new InvalidArgumentException('Invalid input file provided');
}
if (!$percentage) {
    throw new InvalidArgumentException('An integer checked percentage must be given as second parameter');
}
$xml = new SimpleXMLElement(file_get_contents($inputFile));
$metrics = $xml->xpath('//metrics');
$totalElements = 0;
$checkedElements = 0;
foreach ($metrics as $metric) {
    $totalElements += (int) $metric['elements'];
    $checkedElements += (int) $metric['coveredelements'];
}
$coverage = $checkedElements / $totalElements * 100;
$exit_code = 0;
 /**
  * Creates a Console_CommandLine object to parse options.
  *
  * @return Console_CommandLine
  */
 private static function createCommandLineParser()
 {
     $parser = new Console_CommandLine(array('description' => 'A Code browser for PHP files with syntax ' . 'highlighting and colored error-sections ' . 'found by quality assurance tools like ' . 'PHPUnit or PHP_CodeSniffer.', 'version' => strpos('@package_version@', '@') === false ? '@package_version@' : 'from Git'));
     $parser->addOption('log', array('description' => 'The path to the xml log files, e.g. generated' . ' from PHPUnit. Either this or --source ' . 'must be given', 'short_name' => '-l', 'long_name' => '--log', 'help_name' => '<directory>'));
     $parser->addOption('phpSuffixes', array('description' => 'A comma separated list of php file extensions' . ' to include.', 'short_name' => '-S', 'long_name' => '--extensions', 'help_name' => '<extensions>'));
     $parser->addOption('output', array('description' => 'Path to the output folder where generated ' . 'files should be stored.', 'short_name' => '-o', 'long_name' => '--output', 'help_name' => '<directory>'));
     $parser->addOption('source', array('description' => 'Path to the project source code. Can either ' . 'be a directory or a single file. Parse ' . 'complete source directory if set, else ' . 'only files found in logs. Either this or' . ' --log must be given. Can be given ' . 'multiple times', 'short_name' => '-s', 'long_name' => '--source', 'action' => 'StoreArray', 'help_name' => '<dir|file>'));
     $parser->addOption('ignore', array('description' => 'Comma separated string of files or ' . 'directories that will be ignored during' . 'the parsing process.', 'short_name' => '-i', 'long_name' => '--ignore', 'help_name' => '<files>'));
     $parser->addOption('excludePattern', array('description' => 'Excludes all files matching the given glob ' . 'pattern. This is done after pulling the ' . 'files in the source dir in if one is ' . 'given. Can be given multiple times. Note' . ' that the match is run against ' . 'absolute filenames.', 'short_name' => '-e', 'long_name' => '--exclude', 'action' => 'StoreArray', 'help_name' => '<pattern>'));
     $parser->addOption('excludePCRE', array('description' => 'Works like -e but takes PCRE instead of ' . 'glob patterns.', 'short_name' => '-E', 'long_name' => '--excludePCRE', 'action' => 'StoreArray', 'help_name' => '<expression>'));
     $parser->addOption('debugExcludes', array('description' => 'Print which files are excluded by which ' . 'expressions and patterns.', 'long_name' => '--debugExcludes', 'action' => 'StoreTrue'));
     $parser->addOption('excludeOK', array('description' => 'Exclude files with no issues from the report', 'long_name' => '--excludeOK', 'action' => 'StoreTrue'));
     $plugins = array_map(array(__CLASS__, 'arrayMapCallback'), self::getAvailablePlugins());
     $parser->addOption('disablePlugin', array('description' => 'Disable single Plugins. Can be one of ' . implode(', ', $plugins), 'choices' => $plugins, 'long_name' => '--disablePlugin', 'action' => 'StoreArray', 'help_name' => '<plugin>'));
     $parser->addOption('crapThreshold', array('description' => 'The minimum value for CRAP errors to be ' . 'recognized. Defaults to 0. Regardless ' . 'of this setting, values below 30 will ' . 'be considered notices, those above ' . 'warnings.', 'long_name' => '--crapThreshold', 'action' => 'StoreInt', 'help_name' => '<threshold>'));
     return $parser;
 }
Beispiel #17
0
 *
 * @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' => '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";
 /**
  * Vcdeploy parser
  *
  * This method starts vcdeploy to run a plugin
  *
  * @return int
  */
 public function parser()
 {
     // create the parser
     $parser = new Console_CommandLine(array('description' => 'vcdeploy - version controlled deployment script powered by http://www.alphanodes.com', 'version' => $this->version));
     // 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 a global option to make the program verbose
     $parser->addOption('debug', array('short_name' => '-d', 'long_name' => '--debug', 'action' => 'StoreTrue', 'description' => 'turn on debug output'));
     // add a global option to make the program verbose
     $parser->addOption('quit', array('short_name' => '-q', 'long_name' => '--quit', 'action' => 'StoreTrue', 'description' => 'suppress messages (expect error message)'));
     $parser->addOption('projects', array('short_name' => '-p', 'long_name' => '--projects', 'action' => 'StoreTrue', 'description' => 'show list of all active projects'));
     $parser->addOption('allprojects', array('short_name' => '-P', 'long_name' => '--allprojects', 'action' => 'StoreTrue', 'description' => 'show list of all projects (active, inactive and subprojects)'));
     $this->_setPlugins();
     $this->_buildSubCommands($parser);
     // run the parser
     try {
         $result = $parser->parse();
         if ($result->options['projects']) {
             // show projects
             $vcdeploy = new Vcdeploy($this->conf, NULL, $result, $this->version);
             $projects = $vcdeploy->get_projects(true);
             ksort($projects);
             foreach ($projects as $project_name => $project_settings) {
                 print $project_name . "\n";
             }
         } elseif ($result->options['allprojects']) {
             // show all projects
             $vcdeploy = new Vcdeploy($this->conf, NULL, $result, $this->version);
             $projects = $vcdeploy->get_all_projects();
             asort($projects);
             foreach ($projects as $project_name) {
                 print $project_name . "\n";
             }
         } elseif ($result->command_name) {
             $plugin_info = $this->plugin_infos[$result->command_name];
             // 1. batch_before commands
             if (isset($plugin_info['batch_before']) && is_array($plugin_info['batch_before'])) {
                 foreach ($plugin_info['batch_before'] as $batch_before) {
                     $this->plugin_name = $batch_before;
                     $this->run_plugin($result, true);
                 }
             }
             // 2. plugin (run) command
             $this->plugin_name = $result->command_name;
             $rc = $this->run_plugin($result);
             // 3. batch_before commands
             if (isset($plugin_info['batch_after']) && is_array($plugin_info['batch_after'])) {
                 foreach ($plugin_info['batch_after'] as $batch_after) {
                     $this->plugin_name = $batch_after;
                     $rc = $this->run_plugin($result);
                 }
             }
             return $rc;
         } else {
             $parser->displayUsage();
         }
     } catch (Exception $exc) {
         $parser->displayError($exc->getMessage());
     }
 }
#!/usr/bin/env php
<?php 
/**
 * Build a phar archive and sign it using a private key from a given file
 *
 * You need to have some keys generated first - phar-generate-cert
 *
 * This file is part of the PharUtil library.
 * @author Krzysztof Kotowicz <kkotowicz at gmail dot com>
 * @package PharUtil
 */
// Include the Console_CommandLine package.
require_once 'Console/CommandLine.php';
// 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;
Beispiel #20
0
 /**
  * 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;
 }
/**
 * @since 2015-10-15
 * @author Alban
 * @license GPL v2
 */
// Load bootstrap for autoload and logger
set_include_path(".:" . get_include_path());
require_once "bootstrap.php";
// Instanciate export service
$service = new Alternc_Tools_Domains_Import(array("db" => $db));
// Instanciate command line parser
$consoleParser = new Console_CommandLine(array("description" => "Imports Alternc domains from a file for import and gets ready for sync."));
// Configure command line parser
$consoleParser->add_version_option = false;
$consoleParser->addOption("input_file", array("help_name" => "/tmp/out.json", "short_name" => "-i", "long_name" => "--input-file", "description" => "Input file name and path", 'default' => $service->default_input));
$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"])) {
<?php 
/* EXTERNAL DEPENDENCIES *****************************************************/
set_include_path(get_include_path() . PATH_SEPARATOR . realpath('./Console_CommandLine/'));
require_once 'Console/CommandLine.php';
/* BACKWARDS COMPATIBILITY ***************************************************/
if (PHP_VERSION_ID < 50400) {
    // Define these constants, so that they are not undefined
    define('JSON_PRETTY_PRINT', 0);
    define('JSON_UNESCAPED_SLASHES', 0);
}
define('VERSION', '0.32.5');
/* CONSOLE INTERFACE *********************************************************/
$parser = new Console_CommandLine();
$parser->description = "The module reads LaTaLa files for all languages from '101results/101repo/" . FindLanguages::ROOT_LANG_DIR_NAME . "' " . "(In this manner, geshi ids and file extensions are looked up for all languages.) " . "The module writes '" . FindLanguages::OUTPUT_FILE . "' files for all contributions to '101results/" . FindLanguages::ROOT_CONTR_DIR_NAME . "/' " . "The generated json files associate language names as keys with file names and additional metadata as values.";
$parser->version = VERSION;
$parser->addOption('empty', array('short_name' => '-e', 'long_name' => '--empty', 'description' => 'determines how to behave with empty output files', 'action' => 'StoreString', 'choices' => array('NO_NEW', 'CREATE', 'DELETE'), 'add_list_option' => true));
$parser->addOption('stats', array('short_name' => '-s', 'long_name' => '--stats', 'description' => "create a statistics file in actual directory with all languages", 'action' => 'StoreTrue'));
$parser->addOption('quiet', array('short_name' => '-q', 'long_name' => '--quiet', 'description' => "don't print status messages to stdout", 'action' => 'StoreTrue'));
try {
    $result = $parser->parse();
    switch ($result->options['empty']) {
        case 'NO_NEW':
            FindLanguages::$emptyFileBehaviour = FindLanguages::NO_NEW_EMPTY_FILES;
            break;
        case 'CREATE':
            FindLanguages::$emptyFileBehaviour = FindLanguages::CREATE_EMPTY_FILES;
            break;
        case 'DELETE':
            FindLanguages::$emptyFileBehaviour = FindLanguages::DELETE_EMPTY_FILES;
            break;
    }
Beispiel #23
0
/**
 * Build a parser instance and return it.
 *
 * @return object Console_CommandLine instance
 */
function buildParser3()
{
    $parser = new Console_CommandLine();
    $parser->name = 'some_program';
    $parser->version = '0.1.0';
    $parser->description = 'Description of our parser goes here...';
    // we force options default values
    $parser->force_options_defaults = true;
    // add options
    $parser->addOption('true', array('short_name' => '-t', 'long_name' => '--true', 'action' => 'StoreTrue', 'description' => 'test the StoreTrue action'));
    $parser->addOption('false', array('short_name' => '-f', 'long_name' => '--false', 'action' => 'StoreFalse', 'description' => 'test the StoreFalse action'));
    $parser->addOption('int', array('long_name' => '--int', 'action' => 'StoreInt', 'description' => 'test the StoreInt action', 'help_name' => 'INT'));
    $parser->addOption('float', array('long_name' => '--float', 'action' => 'StoreFloat', 'description' => 'test the StoreFloat action', 'help_name' => 'FLOAT'));
    $parser->addOption('string', array('short_name' => '-s', 'long_name' => '--string', 'action' => 'StoreString', 'description' => 'test the StoreString action', 'help_name' => 'STRING', 'choices' => array('foo', 'bar', 'baz')));
    $parser->addOption('counter', array('short_name' => '-c', 'long_name' => '--counter', 'action' => 'Counter', 'description' => 'test the Counter action'));
    $parser->addOption('callback', array('long_name' => '--callback', 'action' => 'Callback', 'description' => 'test the Callback action', 'callback' => 'rot13Callback', 'action_params' => array('prefix' => 'foo', 'suffix' => 'bar')));
    $parser->addOption('array', array('short_name' => '-a', 'long_name' => '--array', 'action' => 'StoreArray', 'help_name' => 'ARRAY', 'description' => 'test the StoreArray action'));
    $parser->addOption('password', array('short_name' => '-p', 'long_name' => '--password', 'action' => 'Password', 'description' => 'test the Password action'));
    return $parser;
}
Beispiel #24
0
 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);
 }
Beispiel #25
0
#!/usr/bin/env php
<?php 
/**
 * Verify Phar archive signature using a public key file
 *
 * This file is part of the PharUtil library.
 * @author Krzysztof Kotowicz <kkotowicz at gmail dot com>
 * @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);
}
Beispiel #26
0
<?php

//Using Console_CommandLine method to add options to the parser.
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
$parser->description = 'Your guide to use command line options:';
//--file [fileName]. this will take csv file name from user.
$parser->addOption('FileName', array('long_name' => '--file', 'description' => 'Use this option to specify users csv finename. How to use: user_upload.php --file FILENAME.csv', 'action' => 'StoreString'));
//--create_table. this will build the MySQL user table.
$parser->addOption('CreateTable', array('long_name' => '--create_table', 'description' => 'Use this option to create User Table in DB. How to use: user_upload.php --create_table', 'action' => 'StoreTrue'));
//--dry_run. this is used to run the script but no insert into the DB. All parts are executed without altering the database.
$parser->addOption('DryRun', array('long_name' => '--dry_run', 'description' => 'Use this option to run the script but no insert into the DB. How to use: user_upload.php --dry_run', 'action' => 'StoreTrue'));
//--insert_data. this is used to insert data into user table. it also creates the table if it is not already created.
$parser->addOption('InsertData', array('long_name' => '--insert_data', 'description' => 'Use this option to insert data into the users table. How to use: user_upload.php --insert_data', 'action' => 'StoreTrue'));
//-u. to get MySQL username from command line.
$parser->addOption('MySQLUsername', array('short_name' => '-u', 'description' => 'Use this option to input DB username. How to use: user_upload.php -u USERNAME - default username is "root"', 'action' => 'StoreString'));
//-p. to get MySQL password from command line.
$parser->addOption('MySQLPassword', array('short_name' => '-p', 'description' => 'Use this option to input DB password. How to use: user_upload.php -p PASSWORD - there is no password by default.', 'action' => 'StoreString'));
//-h. to get MySQL host address from command line.
$parser->addOption('MySQLHost', array('short_name' => '-h', 'description' => 'Use this option to input DB host address. How to use: user_upload.php -h HOSTADDRESS - default host address is "localhost"', 'action' => 'StoreString'));
$result = $parser->parse();
//print_r($result->options);
///////////////////
//this function is used to connect to the database.
function connectToDB($DBuname, $DBpass, $DBhost)
{
    //creating connection to mysql
    $con = mysql_connect($DBhost, $DBuname, $DBpass);
    if (!$con) {
        die("cannot connect: " . msql_error);
    }
#! /usr/bin/env php
<?php 
/**
 * Build a list of checksums, to see if we want to rebuild a phar archive
 *
 * This file is part of the PharUtil library.
 * @author Damian Bushong <stratosphere dot programming at gmail dot com>
 * @package PharUtil
 */
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;
Beispiel #28
0
require_once 'Console/CommandLine.php';
require_once 'sai/org/sai/file/bowtie/BowtieStat.php';
require_once 'sai/org/sai/file/bowtie/Bowtie2Stat.php';
/*
 * Create command line parser object.
 */
$parser = new Console_CommandLine();
$parser->description = <<<DESC
A postprocess tool for compound metagenome suite.
It aggregates logs and result files into one set of files.
DESC;
$parser->version = '1.1';
/*
 * Describe command line options and arguments.
 */
$parser->addOption('pattern', array('long_name' => '--pattern', 'short_name' => '-p', 'description' => 'directory pattern to search within', 'action' => 'StoreString'));
$parser->addOption('name', array('long_name' => '--output-name', 'short_name' => '-o', 'description' => 'output files set name prefix', 'action' => 'StoreString'));
/*
 * Set evironment variables.
 */
$workDir = getcwd();
try {
    $cli = $parser->parse();
    /*
     * Create iterator for traverse through picked directories.
     */
    if ($cli->options['pattern'] === null) {
        $dirIterator = new DirectoryIterator($workDir);
    } else {
        $regexp = '/' . $cli->options['pattern'] . '/';
        $dirIterator = new RegexIterator(new DirectoryIterator($workDir), $regexp);
Beispiel #29
0
 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);
     }
 }
Beispiel #30
0
require_once 'Log.php';
require_once 'Net/URL2.php';
$blacklist = get_domain_blacklist();
global $logger;
$logger = Log::singleton('console', '', 'ident', NULL, PEAR_LOG_INFO);
function print_log($message, $priority = PEAR_LOG_INFO)
{
    global $logger;
    $logger->log($message, $priority);
}
// Start parsing options
$parser = new Console_CommandLine();
$parser->description = 'Lists files in the current directory and creates a full size PDF or HTML page listing them with any available metadata.';
$parser->version = '1.1';
$parser->addArgument('url', array('multiple' => true, 'required' => TRUE));
$parser->addOption('quiet', array('short_name' => '-q', 'long_name' => '--quiet', 'description' => "Don't print status messages to stdout", 'action' => 'StoreTrue'));
$parser->addOption('verbose', array('short_name' => '-v', 'long_name' => '--verbose', 'description' => "Display extra log messages", 'action' => 'StoreTrue'));
$parser->addOption('rename', array('short_name' => '-r', 'long_name' => '--rename', 'description' => "Rename downloaded files to an autogenerated style.", 'action' => 'StoreTrue'));
global $commandline_input;
try {
    $commandline_input = $parser->parse();
} catch (Exception $exc) {
    $parser->displayError($exc->getMessage());
}
$options = $commandline_input->options;
if ($options['verbose']) {
    $logger->setMask(PEAR_LOG_ALL);
}
if ($options['quiet']) {
    $logger->setMask(PEAR_LOG_NONE);
}