@param ComposerApplication $application
@param string              $namespace
@param InputInterface      $input
@param OutputInterface     $output

@return int Exit code
196007
private function executeInNamespace(ComposerApplication $application, $namespace, InputInterface $input, OutputInterface $output)
    {
        if (!file_exists($namespace)) {
            mkdir($namespace, 0777, true);
        }

        $this->chdir($namespace);

        // some plugins require access to composer file e.g. Symfony Flex
        if (!file_exists(Factory::getComposerFile())) {
            file_put_contents(Factory::getComposerFile(), '{}');
        }
        
        $input = new StringInput((string) $input . ' --working-dir=.');

        $this->getIO()->writeError('<info>Run with <comment>' . $input->__toString() . '</comment></info>', true, IOInterface::VERBOSE);
        
        return $application->doRun($input, $output);
    }
1305178
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $start = microtime(true);
        $style = new SymfonyStyle($input, $output);
        $style->setDecorated(true);
        $style->title($this->description);

        $util = new Util();
        $csf = $util->checkBinary('php-cs-fixer');
        $output->writeln($util->checkVersion($csf));
        $source = $util->checkSource($input);
        if ($input->getOption('diff')) {
            $source = $util->getDiffSource();
        }

        $option = ' --dry-run --diff';
        if ($input->getOption('fix')) {
            $option = '';
        }

        $standard = strtolower($input->getOption('standard'));
        $standards = '--level='.str_replace(',', ' --level=', $standard);
        $sources = explode(' ', $source);
        $exitCode = 0;
        foreach ($sources as $source) {
            $cmd = $csf.' fix '.$source.' --ansi '.$standards.$option;
            $output->writeln('<info>Command: '.$cmd.'</>');
            $style->newLine();
            $process = new Process($cmd);
            $process->setTimeout(3600)->run();
            $output->writeln($process->getOutput());

            if (!$exitCode) {
                $exitCode = $process->getExitCode();
            }
        }

        $end = microtime(true);
        $time = round($end - $start);

        $style->section('Results');
        $output->writeln('<info>Time: '.$time.' seconds</>');
        $style->newLine();

        return $exitCode;
    }
1302368
protected function execute(InputInterface $oInput, OutputInterface $oOutput): int
    {
        parent::execute($oInput, $oOutput);

        $oOutput->writeln('');
        $oOutput->writeln('<info>-----------------------------</info>');
        $oOutput->writeln('<info>Nails Database Migration Tool</info>');
        $oOutput->writeln('<info>-----------------------------</info>');

        // --------------------------------------------------------------------------

        //  Check environment
        if (Environment::is(Environment::ENV_PROD)) {

            $oOutput->writeln('');
            $oOutput->writeln('--------------------------------------');
            $oOutput->writeln('| <info>WARNING: The app is in PRODUCTION.</info> |');
            $oOutput->writeln('--------------------------------------');
            $oOutput->writeln('');

            if (!$this->confirm('Continue with migration?', true)) {
                return $this->abort();
            }
        }

        // --------------------------------------------------------------------------

        //  Work out the DB credentials to use
        $sDbHost = $oInput->getOption('dbHost') ?: (defined('DEPLOY_DB_HOST') ? DEPLOY_DB_HOST : '');
        $sDbUser = $oInput->getOption('dbUser') ?: (defined('DEPLOY_DB_USERNAME') ? DEPLOY_DB_USERNAME : '');
        $sDbPass = $oInput->getOption('dbPass') ?: (defined('DEPLOY_DB_PASSWORD') ? DEPLOY_DB_PASSWORD : '');
        $sDbName = $oInput->getOption('dbName') ?: (defined('DEPLOY_DB_DATABASE') ? DEPLOY_DB_DATABASE : '');

        //  Check we have a database to connect to
        if (empty($sDbName)) {
            return $this->abort(static::EXIT_CODE_NO_DB);
        }

        //  Get the DB object
        $this->oDb = Factory::service('PDODatabase');
        $this->oDb->connect($sDbHost, $sDbUser, $sDbPass, $sDbName);

        if (!defined('NAILS_DB_PREFIX')) {
            define('NAILS_DB_PREFIX', 'nails_');
        }

        //  Test the db
        $iResult = $this->oDb->query('SHOW Tables LIKE \'' . NAILS_DB_PREFIX . 'migration\'')->rowCount();
        if (!$iResult) {

            //  Create the migrations table
            $sSql = "CREATE TABLE `" . NAILS_DB_PREFIX . "migration` (
              `module` VARCHAR(100) NOT NULL DEFAULT '',
              `version` INT(11) UNSIGNED DEFAULT NULL,
              PRIMARY KEY (`module`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";

            if (!(bool) $this->oDb->query($sSql)) {

                $oOutput->writeln('');
                $oOutput->writeln('Database isn\'t ready for migrations.');

                return $this->abort(static::EXIT_CODE_DB_NOT_READY);
            }
        }

        // --------------------------------------------------------------------------

        //  Backwards compatability - ensure that the vendor prefix is correct
        $this->oDb->query(
            'UPDATE `' . NAILS_DB_PREFIX . 'migration` SET `module` = REPLACE(`module`, "nailsapp/", "nails/");'
        );

        // --------------------------------------------------------------------------

        $oOutput->writeln('');

        // --------------------------------------------------------------------------

        $aEnabledModules = $this->findEnabledModules();
        $oApp            = $this->determineModuleState('APP', 'application/migrations/');

        // --------------------------------------------------------------------------

        //  Anything to migrate?
        if (!$aEnabledModules && !$oApp) {
            $oOutput->writeln('');
            $oOutput->writeln('Nothing to migrate');
            $oOutput->writeln('');

            return self::EXIT_CODE_SUCCESS;
        }

        // --------------------------------------------------------------------------

        //  Confirm what's going to happen
        $oOutput->writeln('');
        $oOutput->writeln('OK, here\'s what\'s going to happen:');

        if ($aEnabledModules || $oApp) {

            $oOutput->writeln('');

            foreach ($aEnabledModules as $oModule) {

                $sStart = is_null($oModule->start) ? 'The beginning of time' : $oModule->start;
                $sLine  = ' - <comment>' . $oModule->name . '</comment> from ';
                $sLine  .= '<info>#' . $sStart . '</info> to <info>#' . $oModule->end . '</info>';

                $oOutput->writeln($sLine);
            }

            if ($oApp) {
                $sStart = is_null($oApp->start) ? 'The beginning of time' : $oApp->start;
                $sLine  = ' - <comment>app</comment> from ';
                $sLine  .= '<info>#' . $sStart . '</info> to <info>#' . $oApp->end . '</info>';
                $oOutput->writeln($sLine);
            }
        }

        $oOutput->writeln('');
        $oOutput->writeln('Routes will be rewritten');
        $oOutput->writeln('');

        if (!$this->confirm('Continue?', true)) {
            return $this->abort(static::EXIT_CODE_SUCCESS);
        }

        // --------------------------------------------------------------------------

        $oOutput->writeln('');
        $oOutput->writeln('<comment>Starting migration...</comment>');

        // --------------------------------------------------------------------------

        //  Start migrating
        $iCurStep       = 1;
        $iNumMigrations = 0;
        $iNumMigrations += !empty($aEnabledModules) ? count($aEnabledModules) : 0;
        $iNumMigrations += !empty($oApp) ? 1 : 0;

        //  Disable foreign key checks
        $oResult              = $this->oDb->query('SHOW Variables WHERE Variable_name=\'FOREIGN_KEY_CHECKS\'')->fetch(\PDO::FETCH_OBJ);
        $sOldForeignKeyChecks = $oResult->Value;

        $this->oDb->query('SET FOREIGN_KEY_CHECKS = 0;');

        //  Migrate the modules
        if (!empty($aEnabledModules)) {
            foreach ($aEnabledModules as $oModule) {

                $oOutput->write('[' . $iCurStep . '/' . $iNumMigrations . '] Migrating <info>' . $oModule->name . '</info>... ');
                if ($this->doMigration($oModule)) {
                    $oOutput->writeln('done!');
                } else {
                    return $this->abort(static::EXIT_CODE_MODULE_MIGRATION_FAILED);
                }

                $iCurStep++;
            }
        }

        //  Migrate the app
        if (!empty($oApp)) {
            $oOutput->write('[' . $iCurStep . '/' . $iNumMigrations . '] Migrating <info>app</info>... ');
            if ($this->doMigration($oApp)) {
                $oOutput->writeln('done!');
            } else {
                return $this->abort(static::EXIT_CODE_APP_MIGRATION_FAILED);
            }
        }

        // --------------------------------------------------------------------------

        //  Rewrite Routes
        $oOutput->writeln('<comment>Rewriting routes...</comment>');
        $this->callCommand('routes:rewrite', [], false, true);

        // --------------------------------------------------------------------------

        //  Cleaning up
        $oOutput->writeln('<comment>Cleaning up...</comment>');

        //  Restore previous foreign key checks
        $this->oDb->query('SET FOREIGN_KEY_CHECKS = \'' . $sOldForeignKeyChecks . '\';');

        // --------------------------------------------------------------------------

        //  And we're done
        $oOutput->writeln('');
        $oOutput->writeln('Complete!');

        return self::EXIT_CODE_SUCCESS;
    }
365939
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        try {
            $options = $this->configureOptions($options);
        } catch (ExceptionInterface $e) {
            return;
        }

        if (empty($options['directories'])) {
            return;
        }

        $baseDirectory = $options['baseDirectory'] ?: $deployment->getApplicationReleasePath($application);

        $commands = array_map(function ($directory) {
            return sprintf('mkdir -p %s', $directory);
        }, $options['directories']);

        array_unshift($commands, sprintf('cd %s', $baseDirectory));

        $this->shell->executeOrSimulate($commands, $node, $deployment);
    }
55634
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $start = microtime(true);
        $commands = array('qa:cbf', 'qa:csf');
        $style = new SymfonyStyle($input, $output);
        $style->setDecorated(true);
        $output->write(sprintf("\033\143"));

        foreach ($commands as $command) {
            $returnCode = $this->getApplication()->find($command)->run($input, $output);
            if ($returnCode) {
                $output->writeln('<error>Exit code '.$returnCode.'</>');
            }
        }

        $end = microtime(true);
        $time = round($end - $start);
        $style->newLine();
        $style->section('Results');
        $output->writeln('<info>Time: '.$time.' seconds</>');
    }
239355
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->requireConfig();

        $output->writeln('Starting <fg=blue>Magallanes</>');
        $output->writeln('');

        $output->writeln(sprintf('<comment>%s</comment>', var_export($this->runtime->getConfiguration(), true)));

        $output->writeln('');
        $output->writeln('Finished <fg=blue>Magallanes</>');

        return 0;
    }
324683
protected function execute(InputInterface $input, OutputInterface $output)
    {
        if ($root = $input->getArgument('root-dir')) {
            chdir(realpath($root));
        }

        $rootDir = realpath(getcwd());
        $logger  = new ConsoleLogger($output);

        $composerJson = $rootDir . '/composer.json';
        if (!file_exists($composerJson)) {
            $logger->error(
                '<error>File not found, can not analyze: {file}</error> ',
                array('file' => $composerJson)
            );

            return 1;
        }

        $destinations   = array();
        $destinations[] = new PsrLogDestination($logger);

        $report   = $this->prepareReport($input, $logger);
        $composer = json_decode(file_get_contents($composerJson), true);
        $ignore   = $this->getIgnoredFiles($composer, $input->getOption('ignore-files'));
        $factory  = new AutoloadValidatorFactory($rootDir, new ClassMapGenerator($ignore), $report);
        $test     = new AutoloadValidator($factory->createFromComposerJson($composer), $report);
        $test->validate();
        if ($report->hasError()) {
            $logger->error('<error>Testing loaders found errors</error> ');
        }

        $enumLoader = new EnumeratingClassLoader();
        $this->prepareLoader($enumLoader, $test);

        $hacker = new HackPreparator($enumLoader, $logger);
        if ($custom = $input->getOption('add-autoloader')) {
            $hacker->prepareHacks(
                $custom,
                array(
                    $rootDir,
                    dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'hacks'
                )
            );
        }
        $this->prepareComposerFallbackLoader($enumLoader, $rootDir, $composer);
        if (!($input->getOption('disable-legacy-hacks') || $input->getOption('add-autoloader'))) {
            $hacker->prepareLegacyHack();
        }

        $loadCycle = new AllLoadingAutoLoader($enumLoader, $test->getClassMap(), $logger);

        return static::$exitCodes[$loadCycle->run() && !$report->hasError()];
    }
1225427
protected function execute(InputInterface $input, OutputInterface $output) : int
    {
        return !is_null($this->exitCode) ? $this->exitCode : 0;
    }
1214656
protected function describeCommands(Application $application, OutputInterface $output): DescriberContract
    {
        $this->width = 0;

        $namespaces = collect($application->all())->filter(function ($command) {
            return ! $command->isHidden();
        })->groupBy(function ($command) {
            $nameParts = explode(':', $name = $command->getName());
            $this->width = max($this->width, mb_strlen($name));

            return isset($nameParts[1]) ? $nameParts[0] : '';
        })->sortKeys()->each(function ($commands) use ($output) {
            $output->write("\n");

            $commands = $commands->toArray();

            usort($commands, function ($a, $b) {
                return $a->getName() > $b->getName();
            });

            foreach ($commands as $command) {
                $output->write(sprintf(
                    "  <fg=green>%s</>%s%s\n",
                    $command->getName(),
                    str_repeat(' ', $this->width - mb_strlen($command->getName()) + 1),
                    $command->getDescription()
                ));
            }
        });

        return $this;
    }
810489
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $context = Context::createDefaultContext();
        $plugins = $this->prepareExecution(self::LIFECYCLE_METHOD, $io, $input, $context);

        $keepUserData = (bool) $input->getOption('keep-user-data');

        $uninstalledPluginCount = 0;
        /** @var PluginEntity $plugin */
        foreach ($plugins as $plugin) {
            if ($plugin->getInstalledAt() === null) {
                $io->note(sprintf('Plugin "%s" is not installed. Skipping.', $plugin->getName()));

                continue;
            }

            $this->pluginLifecycleService->uninstallPlugin($plugin, $context, $keepUserData);
            ++$uninstalledPluginCount;

            $io->text(sprintf('Plugin "%s" has been uninstalled successfully.', $plugin->getName()));
        }

        if ($uninstalledPluginCount !== 0) {
            $io->success(sprintf('Uninstalled %d plugins.', $uninstalledPluginCount));
        }
    }
1066134
public function execute(InputInterface $input, OutputInterface $output)
    {
        $this->createAppMigrationsTable();

        $migrations = $this->migrationsToRun();

        usort($migrations, function ($a, $b) {
            return strcmp($a->getTimestamp(), $b->getTimestamp());
        });

        $count     = 0;
        $totalTime = 0;
        foreach ($migrations as $migration) {
            $output->writeln(sprintf(
                '  * STARTING *  %s (%s)',
                $migration->getDescription(),
                $migration->getTimestamp()
            ));
            $start = microtime(true);

            $migration->execute($this->db);

            $time = microtime(true) - $start;
            $totalTime += $time;
            $output->writeln(sprintf(
                '  * DONE *  %s (%s) - Took %.2fs',
                $migration->getDescription(),
                $migration->getTimestamp(),
                $time
            ));

            $this->recordMigration($migration);

            $count++;
        }

        if ($count === 0) {
            $message = '  No new migrations to run';
        } else {
            $message = sprintf('  Executed %d migrations in %.2fs', $count, $totalTime);
        }

        $output->writeln([$message, ''], true);
    }
998775
protected function execute(InputInterface $oInput, OutputInterface $oOutput)
    {
        parent::execute($oInput, $oOutput);

        $oOutput->writeln('');
        $oOutput->writeln('<info>----------------------</info>');
        $oOutput->writeln('<info>Nails Database Rebuild </info>');
        $oOutput->writeln('<info>----------------------</info>');
        $oOutput->writeln('');

        // --------------------------------------------------------------------------

        //  Check environment
        if (Environment::is(Environment::ENV_PROD)) {

            $oOutput->writeln('--------------------------------------');
            $oOutput->writeln('| <info>WARNING: The app is in PRODUCTION.</info> |');
            $oOutput->writeln('--------------------------------------');
            $oOutput->writeln('');
            $oOutput->writeln('Aborting rebuild.');

            return static::EXIT_CODE_FAILURE;
        }

        // --------------------------------------------------------------------------

        //  Work out the DB credentials to use
        $sDbHost = $oInput->getOption('dbHost') ?: (defined('DEPLOY_DB_HOST') ? DEPLOY_DB_HOST : '');
        $sDbUser = $oInput->getOption('dbUser') ?: (defined('DEPLOY_DB_USERNAME') ? DEPLOY_DB_USERNAME : '');
        $sDbPass = $oInput->getOption('dbPass') ?: (defined('DEPLOY_DB_PASSWORD') ? DEPLOY_DB_PASSWORD : '');
        $sDbName = $oInput->getOption('dbName') ?: (defined('DEPLOY_DB_DATABASE') ? DEPLOY_DB_DATABASE : '');

        //  Check we have a database to connect to
        if (empty($sDbName)) {
            return $this->abort(static::EXIT_CODE_NO_DB);
        }

        //  Get the DB object
        $oDb = Factory::service('PDODatabase');
        $oDb->connect($sDbHost, $sDbUser, $sDbPass, $sDbName);

        // --------------------------------------------------------------------------

        //  Which tables are we going to drop; all those which match our prefixes
        $oDb      = Factory::service('PDODatabase');
        $oResult  = $oDb->query('SHOW TABLES');
        $aResults = $oResult->fetchAll(\PDO::FETCH_OBJ);
        $aTables  = [];
        foreach ($aResults as $aResult) {
            $sTable = reset($aResult);
            if (preg_match('/^(' . NAILS_DB_PREFIX . '|' . APP_DB_PREFIX . ')/', $sTable)) {
                $aTables[] = $sTable;
            }
        }

        // --------------------------------------------------------------------------

        $oOutput->writeln('The following database tables will be dropped, and migrations run.');
        $oOutput->writeln('');
        foreach ($aTables as $sTable) {
            $oOutput->writeln(' - <comment>' . $sTable . '</comment>');
        }
        $oOutput->writeln('');

        if ($this->confirm('Continue?', true)) {
            $oOutput->writeln('');
            $oOutput->write('Dropping tables... ');
            $oDb->query('SET FOREIGN_KEY_CHECKS = 0;');
            foreach ($aTables as $sTable) {
                $oDb->query('DROP TABLE IF EXISTS `' . $sTable . '`;');
            }
            $oDb->query('SET FOREIGN_KEY_CHECKS = 1;');
            $oOutput->writeln('<info>done!</info>');
            $oOutput->write('Migrating database... ');
            $iExitCode = $this->callCommand(
                'db:migrate',
                [
                    '--dbHost' => $sDbHost,
                    '--dbUser' => $sDbUser,
                    '--dbPass' => $sDbPass,
                    '--dbName' => $sDbName,
                ],
                false,
                true
            );

            if ($iExitCode == static::EXIT_CODE_SUCCESS) {
                $oOutput->writeln('<info>done!</info>');
            } else {
                $oOutput->writeln('<error>fail!</error>');
                return $this->abort(
                    self::EXIT_CODE_FAILURE,
                    [
                        'The Migration tool encountered issues and aborted the migration.',
                        'You should run it manually and investigate any issues.',
                        'The exit code was ' . $iExitCode,
                    ]
                );
            }
        }

        // --------------------------------------------------------------------------

        //  Cleaning up
        $oOutput->writeln('');
        $oOutput->writeln('<comment>Cleaning up...</comment>');

        // --------------------------------------------------------------------------

        //  And we're done
        $oOutput->writeln('');
        $oOutput->writeln('Complete!');

        return static::EXIT_CODE_SUCCESS;
    }
806196
private function validateComposerFile(Console\Output\OutputInterface $output): int
    {
        return $this->getApplication()->run(
            new Console\Input\ArrayInput([
                'command' => 'validate',
                '--no-check-all' => true,
                '--no-check-lock' => true,
                '--no-check-publish' => true,
                '--strict' => true,
            ]),
            $output
        );
    }
253827
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        Assert::isInstanceOf($application, Flow::class, sprintf('Flow application needed for RunCommandTask, got "%s"', get_class($application)));

        $options = $this->configureOptions($options);

        $targetPath = $deployment->getApplicationReleasePath($application);

        $command = sprintf('cd %s && FLOW_CONTEXT=%s ./%s %s', $targetPath, $application->getContext(), $application->getFlowScriptName(), $options['command']);

        $this->shell->executeOrSimulate($command, $node, $deployment, $options['ignoreErrors'], $options['logOutput']);
    }
619399
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $sourceNode = $this->nodeFactory->getNodeByArray($options['sourceNode']);
        $credentials = $this->getCredentials($sourceNode, $deployment, $options['sourceNodeOptions'], $application);
        $dumpFile = $this->getDumpFile($options['sourceNodeOptions'], $credentials);
        $this->shell->executeOrSimulate('rm '.$dumpFile, $sourceNode, $deployment);

        $credentials = $this->getCredentials($node, $deployment, $options, $application);
        $dumpFile = $this->getDumpFile($options, $credentials);
        $this->shell->executeOrSimulate('rm '.$dumpFile, $node, $deployment);
    }
234966
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $replacePaths = [];
        $replacePaths['{workspacePath}'] = escapeshellarg($deployment->getWorkspacePath($application));

        if (!isset($options['command'])) {
            throw new InvalidConfigurationException('Missing "command" option for LocalShellTask', 1311168045);
        }
        $command = $options['command'];
        $command = str_replace(array_keys($replacePaths), $replacePaths, $command);

        $ignoreErrors = isset($options['ignoreErrors']) && $options['ignoreErrors'] === true;
        $logOutput = !(isset($options['logOutput']) && $options['logOutput'] === false);

        $localhost = new Node('localhost');
        $localhost->onLocalhost();

        $this->shell->executeOrSimulate($command, $localhost, $deployment, $ignoreErrors, $logOutput);
    }
6994
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $context = Context::createDefaultContext();
        $plugins = $this->prepareExecution(self::LIFECYCLE_METHOD, $io, $input, $context);

        $deactivatedPluginCount = 0;
        /** @var PluginEntity $plugin */
        foreach ($plugins as $plugin) {
            if ($plugin->getInstalledAt() === null) {
                $io->note(sprintf('Plugin "%s" must be installed. Skipping.', $plugin->getName()));

                continue;
            }

            if ($plugin->getActive() === false) {
                $io->note(sprintf('Plugin "%s" must be activated. Skipping.', $plugin->getName()));

                continue;
            }

            $this->pluginLifecycleService->deactivatePlugin($plugin, $context);
            ++$deactivatedPluginCount;

            $io->text(sprintf('Plugin "%s" has been deactivated successfully.', $plugin->getName()));
        }

        if ($deactivatedPluginCount !== 0) {
            $io->success(sprintf('Deactivated %d plugin(s).', $deactivatedPluginCount));
        }
    }