Executes all available commands
@param Arguments $args The command arguments
@param ConsoleIo $io The console io
@return null|int The exit code or null for success
@uses $questions
14301
public function execute(Arguments $args, ConsoleIo $io)
    {
        $questions = $args->getOption('force') ? Hash::extract($this->questions, '{n}[default=Y]') : $this->questions;

        foreach ($questions as $question) {
            is_true_or_fail(['question', 'default', 'command'] === array_keys($question), __d('me_tools', 'Invalid question keys'));
            list($question, $default, $command) = array_values($question);

            //The method must be executed if the `force` mode is set or if the
            //  user answers yes to the question
            $toBeExecuted = true;
            if (!$args->getOption('force')) {
                $ask = $io->askChoice($question, $default === 'Y' ? ['Y', 'n'] : ['y', 'N'], $default);
                $toBeExecuted = in_array($ask, ['Y', 'y']);
            }

            if ($toBeExecuted) {
                $command = is_string($command) ? new $command : $command;
                $command->run($args->getOption('verbose') ? ['--verbose'] : [], $io);
            }
        }

        return null;
    }
967208
public function doRun(InputInterface $input, OutputInterface $output)
	{
		$this->io = new ConsoleIO($input, $output, $this->getHelperSet());
		ErrorHandler::register($this->io);

		return parent::doRun($input, $output);
	}
502469
public function execute(array $args, array $options = [])
    {
        $this->writeln("CmlPHP Console " . Cml::VERSION . "\n", ['foregroundColors' => [Colour::GREEN, Colour::HIGHLIGHT]]);
        $format = new Format(['indent' => 2]);

        if (empty($args)) {
            $this->writeln("Usage:");
            $this->writeln($format->format("input 'command [options] [args]' to run command or input 'help command ' to display command help info"));
            $this->writeln('');

            $options = $this->formatOptions();
            $cmdList = $this->formatCommand();

            $this->writeln("Options:");
            $this->formatEcho($format, $options);
            $this->writeln('');

            $this->writeln('Available commands:');
            $this->formatEcho($format, $cmdList[0]);
            $this->formatEcho($format, $cmdList[1]);
        } else {
            $class = new \ReflectionClass($this->console->getCommand($args[0]));
            $property = $class->getDefaultProperties();
            $description = isset($property['description']) ? $property['description'] : '';
            $help = isset($property['help']) ? $property['help'] : false;
            $arguments = isset($property['arguments']) ? $property['arguments'] : [];
            $options = isset($property['options']) ? $property['options'] : [];

            $this->writeln("Usage:");
            $this->writeln($format->format("{$args[0]} [options] [args]"));
            $this->writeln('');

            count($arguments) > 0 && $arguments = $this->formatArguments($arguments);
            $options = $this->formatOptions($options, 'this');

            $this->writeln("Options:");
            $this->formatEcho($format, $options);
            $this->writeln('');

            if (count($arguments)) {
                $this->writeln("Arguments");
                $this->formatEcho($format, $arguments);
                $this->writeln('');
            }

            $this->writeln("Help:");
            $this->writeln($format->format($help ? $help : $description));
        }
        $this->write("\n");
    }
1228645
@SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            List<String> metaKeys = null;
            String url = null;
            List<Integer> nodeIds = null;
            Boolean allNodes = true;
            List<String> storeNames = null;

            // parse command-line input
            args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET_RO);
            OptionSet options = parser.parse(args);
            if(options.has(AdminParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);
            AdminParserUtils.checkOptional(options,
                                           AdminParserUtils.OPT_NODE,
                                           AdminParserUtils.OPT_ALL_NODES);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE);

            // load parameters
            metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO);
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);
            if(options.has(AdminParserUtils.OPT_NODE)) {
                nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE);
                allNodes = false;
            }
            storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE);

            // execute command
            AdminClient adminClient = AdminToolUtils.getAdminClient(url);

            if(allNodes) {
                nodeIds = AdminToolUtils.getAllNodeIds(adminClient);
            }

            if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) {
                metaKeys = Lists.newArrayList();
                metaKeys.add(KEY_MAX_VERSION);
                metaKeys.add(KEY_CURRENT_VERSION);
                metaKeys.add(KEY_STORAGE_FORMAT);
            }

            doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys);
        }
1040150
public function cli(InputInterface $input = null, OutputInterface $output = null)
  {
    $input = $input ?? new ArgvInput();
    $output = $output ?? new ConsoleOutput();

    $console = $this->getConsole();
    $this->_eventChannel->trigger(ConsolePrepareEvent::i($this->getContext(), $console, $input, $output));

    try
    {
      $exitCode = $console->run($input, $output);
    }
    catch(\Throwable $e)
    {
      $output->writeln("GENERIC EXCEPTION : " . $e->getCode());
      $output->writeln($e->getMessage());
      $exitCode = 1;
    }

    return $exitCode > 255 ? 255 : $exitCode;
  }
809752
public static function exec($args, $context)
    {
        $argc = count($args);
        $first = array_shift($args);
        $first = $context->resolve($first);
        switch ($argc) {
            case 1 :
                return $first;
            case 2 :
                if (is_array($first) && isset($first['operator']) && $first['operator'] == 'not') {
                    $operant = array_shift($args);
                    $operant = $context->resolve($operant);

                    return !($operant);
                }
            case 3 :
                list($op, $right) = $args;
                $right = $context->resolve($right);

                return call_user_func(array('Evaluator', $op['operator']), $first, $right);
            default:
                return false;
        }
    }
709827
public function executeByPath($arguments, array $options = [], IOInterface $io = null)
    {
        $io = $io ?: clone $this->io;

        // Path
        if (is_string($arguments)) {
            $arguments = str_replace('/', ' ', $arguments);
            $arguments = array_filter(explode(' ', $arguments), 'strlen');
        }

        $io->setArguments($arguments);

        // Options
        foreach ($options as $key => $value) {
            $io->setOption($key, $value);
        }

        return $this->getRootCommand()->setIO($io)->execute();
    }
704307
@SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            List<String> metaKeys = null;
            String url = null;

            // parse command-line input
            args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_CHECK);
            OptionSet options = parser.parse(args);
            if(options.has(AdminParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            AdminParserUtils.checkRequired(options, OPT_HEAD_META_CHECK);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);

            // load parameters
            metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_CHECK);
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);


            // execute command
            if(metaKeys.size() == 0
               || (metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL))) {
                metaKeys = Lists.newArrayList();
                metaKeys.add(MetadataStore.CLUSTER_KEY);
                metaKeys.add(MetadataStore.STORES_KEY);
                metaKeys.add(MetadataStore.SERVER_STATE_KEY);
            }

            AdminClient adminClient = AdminToolUtils.getAdminClient(url);

            doMetaCheck(adminClient, metaKeys);
        }
1250075
public static function main(array $argv = [], $command = null)
    {
        $code = 0;

        $output = new ConsoleOutput();
        $input  = new ArgvInput();

        try {
            $c = static::createCli();

            array_shift($argv);

            if (null !== $command) {
                array_unshift($argv, $command);
            }

            $c->run($input, $output, $argv);
        } catch (\Exception $e) {
            if ('true' !== getenv('DEV_QUIET')) {
                $output->writeln(sprintf('<error>Error #%d: %s</error>', $e->getCode(), $e->getMessage()));
            }

            $code = ($e->getCode() > 0 && $e->getCode() < 255) ? $e->getCode() : 255;
        }

        return $code;
    }
682285
public function run(InputInterface $input, OutputInterface $output, array $args)
    {
        $arguments = [];
        $options   = [];

        foreach ($args as $arg) {
            $matches = [];
            if (0 < preg_match('/^\-{1,2}(?<key>[^\=]+)(\=(?<value>.*))?$/', $arg, $matches)) {
                $options[$matches['key']] = isset($matches['value']) ? $matches['value'] : true;
            } else {
                $arguments[] = $arg;
            }
        }

        if (!count($arguments)) {
            array_unshift($arguments, 'help');
        }

        $config = new Config(
            [
                'uses' => [
                    'core'     => null,
                    'git'      => null,
                    'php'      => null,
                    'composer' => null,
                    'phpunit'  => null,
                    'phpcs'    => null,
                    'travis'   => null,
                    'npm'      => null,
                    'gulp'     => null,
                    'itiqiti'  => null,
                ],
            ]
        );

        $el = new ExpressionLanguage();

        $expressionService = new ExpressionService($el);
        $s                 = new Service\ConfigService($expressionService);

        $s->load($config);

        $commandNames = array_shift($arguments);

        return $this->executeCommandFromName($input, $output, $commandNames, $arguments, $options, $config, $s);
    }
634350
public function execute(array $args, array $options = [])
    {
        $this->bootstrap($args, $options);

        $format = isset($options['format']) ? $options['format'] : $options['f'];

        if (null !== $format) {
            Output::writeln('using format ' . $format);
        }

        $this->getManager()->printStatus($format);
    }
841911
public function execute($args)
    {
        self::$definedProps = new Properties();
        $this->searchForThis = null;

        // 1) First handle any options which should always
        // Note: The order in which these are executed is important (if multiple of these options are specified)

        if (in_array('-help', $args) || in_array('-h', $args)) {
            static::printUsage();

            return;
        }

        if (in_array('-version', $args) || in_array('-v', $args)) {
            static::printVersion();

            return;
        }

        if (in_array('-init', $args) || in_array('-i', $args)) {
            $key = array_search('-init', $args) ?: array_search('-i', $args);
            $path = isset($args[$key + 1]) ? $args[$key + 1] : null;

            self::init($path);

            return;
        }

        if (in_array('-diagnostics', $args)) {
            Diagnostics::doReport(new PrintStream(self::$out));

            return;
        }

        // 2) Next pull out stand-alone args.
        // Note: The order in which these are executed is important (if multiple of these options are specified)

        if (false !== ($key = array_search('-quiet', $args, true)) || false !== ($key = array_search(
            '-q',
            $args,
            true
        ))
        ) {
            self::$msgOutputLevel = Project::MSG_WARN;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-emacs', $args, true))
            || false !== ($key = array_search('-e', $args, true))
        ) {
            $this->emacsMode = true;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-verbose', $args, true))) {
            self::$msgOutputLevel = Project::MSG_VERBOSE;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-debug', $args, true))) {
            self::$msgOutputLevel = Project::MSG_DEBUG;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-silent', $args, true))
            || false !== ($key = array_search('-S', $args, true))
        ) {
            $this->silent = true;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-propertyfileoverride', $args, true))) {
            $this->propertyFileOverride = true;
            unset($args[$key]);
        }

        // 3) Finally, cycle through to parse remaining args
        //
        $keys = array_keys($args); // Use keys and iterate to max(keys) since there may be some gaps
        $max = $keys ? max($keys) : -1;
        for ($i = 0; $i <= $max; $i++) {
            if (!array_key_exists($i, $args)) {
                // skip this argument, since it must have been removed above.
                continue;
            }

            $arg = $args[$i];

            if ($arg == "-logfile") {
                try {
                    // see: http://phing.info/trac/ticket/65
                    if (!isset($args[$i + 1])) {
                        $msg = "You must specify a log file when using the -logfile argument\n";
                        throw new ConfigurationException($msg);
                    }

                    $logFile = new PhingFile($args[++$i]);
                    $out = new FileOutputStream($logFile); // overwrite
                    self::setOutputStream($out);
                    self::setErrorStream($out);
                    self::$isLogFileUsed = true;
                } catch (IOException $ioe) {
                    $msg = "Cannot write on the specified log file. Make sure the path exists and you have write permissions.";
                    throw new ConfigurationException($msg, $ioe);
                }
            } elseif ($arg == "-buildfile" || $arg == "-file" || $arg == "-f") {
                if (!isset($args[$i + 1])) {
                    $msg = "You must specify a buildfile when using the -buildfile argument.";
                    throw new ConfigurationException($msg);
                }

                $this->buildFile = new PhingFile($args[++$i]);
            } elseif ($arg == "-listener") {
                if (!isset($args[$i + 1])) {
                    $msg = "You must specify a listener class when using the -listener argument";
                    throw new ConfigurationException($msg);
                }

                $this->listeners[] = $args[++$i];
            } elseif (StringHelper::startsWith("-D", $arg)) {
                // Evaluating the property information //
                // Checking whether arg. is not just a switch, and next arg. does not starts with switch identifier
                if (('-D' == $arg) && (!StringHelper::startsWith('-', $args[$i + 1]))) {
                    $name = $args[++$i];
                } else {
                    $name = substr($arg, 2);
                }

                $value = null;
                $posEq = strpos($name, "=");
                if ($posEq !== false) {
                    $value = substr($name, $posEq + 1);
                    $name = substr($name, 0, $posEq);
                } elseif ($i < count($args) - 1 && !StringHelper::startsWith("-D", $args[$i + 1])) {
                    $value = $args[++$i];
                }
                self::$definedProps->setProperty($name, $value);
            } elseif ($arg == "-logger") {
                if (!isset($args[$i + 1])) {
                    $msg = "You must specify a classname when using the -logger argument";
                    throw new ConfigurationException($msg);
                }

                $this->loggerClassname = $args[++$i];
            } elseif ($arg == "-no-strict") {
                $this->strictMode = false;
            } elseif ($arg == "-strict") {
                $this->strictMode = true;
            } elseif ($arg == "-inputhandler") {
                if ($this->inputHandlerClassname !== null) {
                    throw new ConfigurationException("Only one input handler class may be specified.");
                }
                if (!isset($args[$i + 1])) {
                    $msg = "You must specify a classname when using the -inputhandler argument";
                    throw new ConfigurationException($msg);
                }

                $this->inputHandlerClassname = $args[++$i];
            } elseif ($arg === "-propertyfile") {
                $i = $this->handleArgPropertyFile($args, $i);
            } elseif ($arg === "-keep-going" || $arg === "-k") {
                $this->keepGoingMode = true;
            } elseif ($arg == "-longtargets") {
                self::$definedProps->setProperty('phing.showlongtargets', 1);
            } elseif ($arg == "-projecthelp" || $arg == "-targets" || $arg == "-list" || $arg == "-l" || $arg == "-p") {
                // set the flag to display the targets and quit
                $this->projectHelp = true;
            } elseif ($arg == "-find") {
                // eat up next arg if present, default to build.xml
                if ($i < count($args) - 1) {
                    $this->searchForThis = $args[++$i];
                } else {
                    $this->searchForThis = self::DEFAULT_BUILD_FILENAME;
                }
            } elseif (substr($arg, 0, 1) == "-") {
                // we don't have any more args
                self::printUsage();
                self::$err->write(PHP_EOL);
                throw new ConfigurationException("Unknown argument: " . $arg);
            } else {
                // if it's no other arg, it may be the target
                $this->targets[] = $arg;
            }
        }

        // if buildFile was not specified on the command line,
        if ($this->buildFile === null) {
            // but -find then search for it
            if ($this->searchForThis !== null) {
                $this->buildFile = $this->_findBuildFile(self::getProperty("user.dir"), $this->searchForThis);
            } else {
                $this->buildFile = new PhingFile(self::DEFAULT_BUILD_FILENAME);
            }
        }

        try {
            // make sure buildfile (or buildfile.dist) exists
            if (!$this->buildFile->exists()) {
                $distFile = new PhingFile($this->buildFile->getAbsolutePath() . ".dist");
                if (!$distFile->exists()) {
                    throw new ConfigurationException(
                        "Buildfile: " . $this->buildFile->__toString() . " does not exist!"
                    );
                }
                $this->buildFile = $distFile;
            }

            // make sure it's not a directory
            if ($this->buildFile->isDirectory()) {
                throw new ConfigurationException("Buildfile: " . $this->buildFile->__toString() . " is a dir!");
            }
        } catch (IOException $e) {
            // something else happened, buildfile probably not readable
            throw new ConfigurationException("Buildfile: " . $this->buildFile->__toString() . " is not readable!");
        }

        $this->loadPropertyFiles();

        $this->readyToRun = true;
    }
667043
public function execute(Arguments $args, ConsoleIo $io)
    {
        $path = $args->getOption('path') ?: Folder::slashTerm(ROOT) . 'composer.json';

        try {
            is_writable_or_fail($path);
        } catch (Exception $e) {
            $io->err($e->getMessage());
            $this->abort();
        }

        //Gets and decodes the file
        $contents = json_decode(file_get_contents($path), true);

        if (empty($contents)) {
            $io->err(__d('me_tools', 'The file {0} does not seem a valid {1} file', rtr($path), 'composer.json'));
            $this->abort();
        }

        //Checks if the file has been fixed
        if (empty($contents['config']['component-dir']) || $contents['config']['component-dir'] !== 'vendor/components') {
            $contents += ['config' => ['component-dir' => 'vendor/components']];
            create_file($path, json_encode($contents, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
            $io->verbose(__d('me_tools', 'The file {0} has been fixed', rtr($path)));
        } else {
            $io->verbose(__d('me_tools', 'The file {0} doesn\'t need to be fixed', rtr($path)));
        }

        return null;
    }
1330461
public function handle(Args $args, IO $io)
    {
        foreach ($args->getArgument('path') as $path) {
            if (!Glob::isDynamic($path)) {
                $this->printUrl($path, $io);

                continue;
            }

            foreach ($this->repo->find($path) as $resource) {
                $this->printUrl($resource->getPath(), $io);
            }
        }

        return 0;
    }
245447
public function handleList(Args $args, IO $io)
    {
        $moduleNames = ArgsUtil::getModuleNames($args, $this->modules);
        $states = $this->getBindingTypeStates($args);

        $printStates = count($states) > 1;
        $printModuleName = count($moduleNames) > 1;
        $printHeaders = $printStates || $printModuleName;
        $printTypeAdvice = true;
        $printBindAdvice = false;
        $indentation = $printStates && $printModuleName ? 8
            : ($printStates || $printModuleName ? 4 : 0);

        foreach ($states as $state) {
            $statePrinted = !$printStates;

            foreach ($moduleNames as $moduleName) {
                $expr = Expr::method('getContainingModule', Expr::method('getName', Expr::same($moduleName)))
                    ->andMethod('getState', Expr::same($state));

                $bindingTypes = $this->discoveryManager->findTypeDescriptors($expr);

                if (!$bindingTypes) {
                    continue;
                }

                $printTypeAdvice = false;

                if (!$statePrinted) {
                    $this->printBindingTypeState($io, $state);
                    $statePrinted = true;

                    // Only print the advice if at least one type was printed
                    $printBindAdvice = true;
                }

                if ($printModuleName) {
                    $prefix = $printStates ? '    ' : '';
                    $io->writeLine("{$prefix}Module: $moduleName");
                    $io->writeLine('');
                }

                $styleTag = BindingTypeState::ENABLED === $state ? null : 'bad';

                $this->printTypeTable($io, $bindingTypes, $styleTag, $indentation);

                if ($printHeaders) {
                    $io->writeLine('');
                }
            }
        }

        if ($printTypeAdvice) {
            $io->writeLine('No types defined. Use "puli type --define <name>" to define a type.');
        }
        if ($printBindAdvice) {
            $io->writeLine('Use "puli bind <resource> <type>" to bind a resource to a type.');
        }

        return 0;
    }
148463
public function execute(array $args, array $options = [])
    {
        if (!isset($args[0])) {
            throw new \InvalidArgumentException('arg action must be input');
        }
        $action = explode('::', $args[0]);
        if (!class_exists($action[0])) {
            throw new \InvalidArgumentException('action not not found!');
        }

        ProcessManage::rmTask($action);
    }
223427
public function executeCommand(array $args, OutputInterface $output, $message)
    {
        $name = $args[0];
        $cmd = $this->getCmd($args);

        $output->writeln('');
        $output->writeln(
            sprintf(
                '<info>Running %s</info>',
                $name
            )
        );

        $output->writeln(
            sprintf(
                '<comment>%s</comment>',
                $cmd
            )
        );

        $this->process->setCommandLine($cmd);
        $this->process->run(
            function ($type, $buffer) use ($output, $cmd) {
                if (Process::ERR === $type) {
                    $output->writeln(
                        sprintf(
                            '<error>%s</error>',
                            $buffer
                        )
                    );
                } else {
                    $output->writeln(
                        sprintf(
                            '<comment>%s</comment>',
                            $buffer
                        )
                    );
                }
            }
        );

        if (!$this->process->isSuccessful()) {
            throw new \RuntimeException($message . '<error>' . $this->process->getErrorOutput() . '</error>');
        }
    }