Detect app and environment from current path.

@param InputInterface  $input  An InputInterface instance
@param OutputInterface $output An OutputInterface instance
16688
protected function initialize(InputInterface $input, OutputInterface $output)
    {
        // Determine app and environment from path.
        $cwd = getcwd();
        $config = $this->getApplication()->getTerra()->getConfig();

        foreach ($config->get('apps') as $app) {
            if (!isset($app['environments'])) {
              $app['environments'] = array();
            }
            foreach ($app['environments'] as $environment) {
                if (strpos($cwd, $environment['path']) === 0) {
                  
                    if ($input->hasArgument('app_name')) {
                      $input->setArgument('app_name', $app['name']);
                    }
                    
                    if ($input->hasArgument('environment_name')) {
                      $input->setArgument('environment_name', $environment['name']);
                    }

                    $environment_string = $app['name'] . ':' . $environment['name'];

                    $output->writeln("Using environment <question>$environment_string</question>");
                }
            }
        }
    }
1244787
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = $this->targetDirectory($input);

        $processName = $input->getArgument('process');

        if ($input->hasParameterOption(['--list', '-l']) || empty($processName)) {
            return $this->showProcesses($input, $output);
        }

        $processes = config()->get('processes', []);

        if (!isset($processes[$processName])) {
            throw new \RuntimeException(sprintf('Process %s cannot found', $processName));
        }

        $config = $processes[$processName];
        if (!class_exists($config['process'])) {
            throw new \RuntimeException(sprintf('Process class "%s" is not found.', $processName));
        }

        $name = $input->getOption('name');
        if (empty($name)) {
            $name = $processName;
        }
        $process = $config['process'];
        $options = isset($config['options']) ? (array) $config['options'] : [];
        $process = new $process($name);
        $process->configure($options);

        if (!($process instanceof Process)) {
            throw new \RuntimeException('Process must be instance of \FastD\Swoole\Process');
        }
        if ($input->hasParameterOption(['--daemon', '-d'])) {
            $process->daemon();
        }

        $pidFile = $path.'/'.$processName.'.pid';

        switch ($input->getArgument('action')) {
            case 'start':
                $pid = $process->start();
                file_put_contents($pidFile, $pid);
                $output->writeln(sprintf('process <info>%s</info> pid: <info>%s</info>', $process->getName(), $pid));
                $output->writeln(sprintf('pid: <info>%s</info>', $pidFile));

                $process->wait(function ($ret) use ($name) {
                    return $this->finish($name, $ret['pid'], $ret['code'], $ret['signal']);
                });

                break;
            case 'stop':
                $pid = (int) file_get_contents($pidFile);
                if ($process->kill($pid, SIGTERM)) {
                    $output->writeln(sprintf('process %s pid %s is killed', $process->getName(), $pid));
                }

                break;
            case 'status':
            default:
                $table = new Table($output);
                $info = $this->getProcessInfo($name);
                $table->setColumnWidth(0, 15);
                $rows = [
                    ['name', sprintf('<info>%s</info>', $process->getName())],
                    ['class', sprintf('<info>%s</info>', get_class($process))],
                    ['status', sprintf('<info>%s</info>', $info[2])],
                    ['pid', sprintf('<info>%s</info>', $info[1])],
                ];
                foreach ($options as $key => $value) {
                    $rows[] = ['options.'.$key, sprintf('<info>%s</info>', $value)];
                }
                $table->setRows($rows);
                $table->setStyle('compact');
                $table->render();
        }

        return 0;
    }
1242561
protected function runCommand(InputInterface $input, OutputInterface $output)
    {
        $appName = $input->getArgument('app-name');
        $indices = $this
            ->repositoryBucket
            ->findRepository($appName)
            ->getIndices();

        self::printIndices(
            $input,
            $output,
            $indices
        );
    }
741689
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->bootstrap($input, $output);

        $environment = $input->getOption('environment');
        $version = $input->getOption('target');
        $date = $input->getOption('date');
        $force = (bool)$input->getOption('force');
        $fake = (bool)$input->getOption('fake');

        $config = $this->getConfig();

        if ($environment === null) {
            $environment = $config->getDefaultEnvironment();
            $output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment);
        } else {
            $output->writeln('<info>using environment</info> ' . $environment);
        }

        $envOptions = $config->getEnvironment($environment);
        if (isset($envOptions['adapter'])) {
            $output->writeln('<info>using adapter</info> ' . $envOptions['adapter']);
        }

        if (isset($envOptions['wrapper'])) {
            $output->writeln('<info>using wrapper</info> ' . $envOptions['wrapper']);
        }

        if (isset($envOptions['name'])) {
            $output->writeln('<info>using database</info> ' . $envOptions['name']);
        }

        $versionOrder = $this->getConfig()->getVersionOrder();
        $output->writeln('<info>ordering by </info>' . $versionOrder . " time");

        if ($fake) {
            $output->writeln('<comment>warning</comment> performing fake rollbacks');
        }

        // rollback the specified environment
        if ($date === null) {
            $targetMustMatchVersion = true;
            $target = $version;
        } else {
            $targetMustMatchVersion = false;
            $target = $this->getTargetFromDate($date);
        }

        $start = microtime(true);
        $this->getManager()->rollback($environment, $target, $force, $targetMustMatchVersion, $fake);
        $end = microtime(true);

        $output->writeln('');
        $output->writeln('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>');
    }
285035
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $paths = $input->getArgument('paths');
        foreach ($paths as $path) {
            if (!file_exists($path)) {
                self::error($output, "One or more of the specified paths are missing");
                return;
            }
        }

        if (!FileUtils::deleteDirectory('./lib')) {
            self::error($output, "Unable to remove the output directory");
        };

        if (!file_exists('./lib') || !is_dir('./lib')) {
            mkdir('./lib', 0755, true);
        }

        $magentofier = new Pearify($paths, $output);
        $magentofier->process();
    }
1014081
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $start = microtime(true);

        $this->setOutput($output);
        $this->setVerbosity($output->getVerbosity());

        if ($input->getOption('child') && $output->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) {
            $this->setVerbosity(self::VERBOSITY_CHILD);
        }

        $this->getContainer()->get('ez_migration_bundle.step_executed_listener.tracing')->setOutput($output);

        $migrationService = $this->getMigrationService();

        $force = $input->getOption('force');

        $toExecute = $this->buildMigrationsList($input->getOption('path'), $migrationService, $force);

        if (!count($toExecute)) {
            $output->writeln('<info>No migrations to execute</info>');
            return 0;
        }

        $this->printMigrationsList($toExecute, $input, $output);

        if (!$input->getOption('child')) {
            // ask user for confirmation to make changes
            if (!$this->askForConfirmation($input, $output)) {
                return 0;
            }
        }

        if ($input->getOption('separate-process')) {
            $builder = new ProcessBuilder();
            $executableFinder = new PhpExecutableFinder();
            if (false !== $php = $executableFinder->find()) {
                $builder->setPrefix($php);
            }
            $builderArgs = $this->createChildProcessArgs($input);
        }

        // For cli scripts, this means: do not die if anyone yanks out our stdout.
        if ($input->getOption('survive-disconnected-tty')) {
            ignore_user_abort(true);
        }

        // allow forcing handling of sigchild. Useful on eg. Debian and Ubuntu
        if ($input->getOption('force-sigchild-enabled')) {
            Process::forceSigchildEnabled(true);
        }

        $aborted = false;
        $executed = 0;
        $failed = 0;
        $skipped = 0;
        $total = count($toExecute);

        /** @var MigrationDefinition $migrationDefinition */
        foreach ($toExecute as $name => $migrationDefinition) {

            // let's skip migrations that we know are invalid - user was warned and he decided to proceed anyway
            if ($migrationDefinition->status == MigrationDefinition::STATUS_INVALID) {
                $output->writeln("<comment>Skipping $name</comment>");
                $skipped++;
                continue;
            }

            $this->writeln("<info>Processing $name</info>");

            if ($input->getOption('separate-process')) {

                try {
                    $this->executeMigrationInSeparateProcess($migrationDefinition, $migrationService, $builder, $builderArgs);

                    $executed++;
                } catch (\Exception $e) {
                    $failed++;


                    $errorMessage = $e->getMessage();
                    // we probably have already echoed the error message while the subprocess was executing, avoid repeating it
                    if ($errorMessage != $this->subProcessErrorString) {
                        if ($e instanceof AfterMigrationExecutionException) {
                            $errorMessage = "Failure after migration end! Reason: " . $errorMessage;
                        } else {
                            $errorMessage = "Migration failed! Reason: " . $errorMessage;
                        }

                        $this->writeErrorln("\n<error>$errorMessage</error>");
                    }

                    if (!$input->getOption('ignore-failures')) {
                        $aborted = true;
                        break;
                    }
                }

            } else {

                try {
                    $this->executeMigrationInProcess($migrationDefinition, $force, $migrationService, $input);

                    $executed++;
                } catch (\Exception $e) {
                    $failed++;

                    $this->writeErrorln("\n<error>Migration failed! Reason: " . $e->getMessage() . "</error>");

                    if (!$input->getOption('ignore-failures')) {
                        $aborted = true;
                        break;
                    }
                }

            }
        }

        $missed = $total - $executed - $failed - $skipped;

        if ($aborted) {
            if ($missed > 0) {
                $this->writeErrorln("\n<error>Migration execution aborted</error>");
            }
        } else {
            // NB: as per the Sf doc at https://symfony.com/doc/2.7/console/calling_commands.html, the 'cache:clear'
            // command should be run 'at the end', as they change some class definitions
            if ($input->getOption('clear-cache')) {
                $command = $this->getApplication()->find('cache:clear');
                $inputArray = new ArrayInput(array('command' => 'cache:clear'));
                $command->run($inputArray, $output);
            }
        }

        $this->writeln("\nExecuted $executed migrations, failed $failed, skipped $skipped" . ($missed ? ", missed $missed" : ''));

        $time = microtime(true) - $start;
        if ($input->getOption('separate-process')) {
            // in case of using subprocesses, we can not measure max memory used
            $this->writeln("<info>Time taken: ".sprintf('%.2f', $time)." secs</info>");
        } else {
            $this->writeln("<info>Time taken: ".sprintf('%.2f', $time)." secs, memory: ".sprintf('%.2f', (memory_get_peak_usage(true) / 1000000)). ' MB</info>');
        }

        return $failed;
    }
744607
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->bootstrap($input, $output);

        $seedSet = $input->getOption('seed');
        $environment = $input->getOption('environment');

        if ($environment === null) {
            $environment = $this->getConfig()->getDefaultEnvironment();
            $output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment);
        } else {
            $output->writeln('<info>using environment</info> ' . $environment);
        }

        $envOptions = $this->getConfig()->getEnvironment($environment);
        if (isset($envOptions['adapter'])) {
            $output->writeln('<info>using adapter</info> ' . $envOptions['adapter']);
        }

        if (isset($envOptions['wrapper'])) {
            $output->writeln('<info>using wrapper</info> ' . $envOptions['wrapper']);
        }

        if (isset($envOptions['name'])) {
            $output->writeln('<info>using database</info> ' . $envOptions['name']);
        } else {
            $output->writeln('<error>Could not determine database name! Please specify a database name in your config file.</error>');

            return;
        }

        if (isset($envOptions['table_prefix'])) {
            $output->writeln('<info>using table prefix</info> ' . $envOptions['table_prefix']);
        }
        if (isset($envOptions['table_suffix'])) {
            $output->writeln('<info>using table suffix</info> ' . $envOptions['table_suffix']);
        }

        $start = microtime(true);

        if (empty($seedSet)) {
            // run all the seed(ers)
            $this->getManager()->seed($environment);
        } else {
            // run seed(ers) specified in a comma-separated list of classes
            foreach ($seedSet as $seed) {
                $this->getManager()->seed($environment, trim($seed));
            }
        }

        $end = microtime(true);

        $output->writeln('');
        $output->writeln('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>');
    }
572527
protected function selectApp(InputInterface $input)
    {
        $appName = $input->getOption('app');
        if ($appName) {
            return $appName;
        }

        try {
            $apps = array_map(function (WebApp $app) {
                return $app->name;
            }, $this->api()->getCurrentDeployment($this->getSelectedEnvironment())->webapps);
            if (!count($apps)) {
                return null;
            }
        } catch (EnvironmentStateException $e) {
            if (!$e->getEnvironment()->isActive()) {
                throw new EnvironmentStateException(
                    sprintf('Could not find applications: the environment "%s" is not currently active.', $e->getEnvironment()->id),
                    $e->getEnvironment()
                );
            }
            throw $e;
        }

        $this->debug('Found app(s): ' . implode(',', $apps));
        if (count($apps) === 1) {
            $appName = reset($apps);
        } elseif ($input->isInteractive()) {
            /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
            $questionHelper = $this->getService('question_helper');
            $choices = array_combine($apps, $apps);
            $appName = $questionHelper->choose($choices, 'Enter a number to choose an app:');
        }

        $input->setOption('app', $appName);

        return $appName;
    }
946925
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
        $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
        $errOutput->setVerbosity(OutputInterface::VERBOSITY_NORMAL);

        $context = json_decode($input->getOption('context') ?: '{}', true);
        $context['tenant_id'] = (string)$input->getOption('tenant-id');

        $nodeRef = NodeRef::fromString($input->getArgument('node-ref'));
        $consistent = $input->getOption('consistent') ? true : false;

        try {
            $node = $this->ncr->getNode($nodeRef, $consistent, $context);
            echo json_encode($node, $input->getOption('pretty') ? JSON_PRETTY_PRINT : 0) . PHP_EOL;
        } catch (\Throwable $e) {
            $errOutput->writeln($e->getMessage());
        }
    }
1209975
public function process(InputInterface $input, OutputInterface $output)
    {
        $featuresPath = $input->getArgument('features');
        
        // Can't use 'behat.paths.base' since that's locked at this point to base folder (not module)
        $pathSuffix   = $this->container->getParameter('behat.silverstripe_extension.context.path_suffix');

        $currentModuleName = null;
        $modules = \SS_ClassLoader::instance()->getManifest()->getModules();

        // get module specified in behat.yml
        $currentModuleName = $this->container->getParameter('behat.silverstripe_extension.module');

        // get module from short notation if path starts from @
        if ($featuresPath && preg_match('/^\@([^\/\\\\]+)(.*)$/', $featuresPath, $matches)) {
            $currentModuleName = $matches[1];
            // TODO Replace with proper module loader once AJShort's changes are merged into core
            $currentModulePath = $modules[$currentModuleName];
            $featuresPath = str_replace(
                '@'.$currentModuleName,
                $currentModulePath.DIRECTORY_SEPARATOR.$pathSuffix,
                $featuresPath
            );
        // get module from provided features path
        } elseif (!$currentModuleName && $featuresPath) {
            $path = realpath(preg_replace('/\.feature\:.*$/', '.feature', $featuresPath));
            foreach ($modules as $moduleName => $modulePath) {
                if (false !== strpos($path, realpath($modulePath))) {
                    $currentModuleName = $moduleName;
                    $currentModulePath = realpath($modulePath);
                    break;
                }
            }
            $featuresPath = $currentModulePath.DIRECTORY_SEPARATOR.$pathSuffix.DIRECTORY_SEPARATOR.$featuresPath;
        // if module is configured for profile and feature provided
        } elseif ($currentModuleName && $featuresPath) {
            $currentModulePath = $modules[$currentModuleName];
            $featuresPath = $currentModulePath.DIRECTORY_SEPARATOR.$pathSuffix.DIRECTORY_SEPARATOR.$featuresPath;
        }

        if($input->getOption('namespace')) {
            $namespace = $input->getOption('namespace');
        } else {
            $namespace = ucfirst($currentModuleName);
        }

        if ($currentModuleName) {
            $this->container
                ->get('behat.silverstripe_extension.context.class_guesser')
                // TODO Improve once modules can declare their own namespaces consistently
                ->setNamespaceBase($namespace);
        }

        $this->container
            ->get('behat.console.command')
            ->setFeaturesPaths($featuresPath ? array($featuresPath) : array());
    }
960025
public function handle(Input $input, Output $output)
    {
        $mode = "UP";
        $path = base_path('.env');

        try {
            if (!file_exists($path)) throw new \Exception(".env file is not exist.", 1);

            $old_mode = app_env('APP_MODE');
            if ($mode == $old_mode) throw new \Exception("Web mode is already {$mode}.", 1);

            file_put_contents($path, str_replace("APP_MODE={$old_mode}", "APP_MODE={$mode}", file_get_contents($path)));
            $output->writeln("Application Mode is now up!");

            return true;
        } catch (\Exception $e) {
            $output->writeln($e->getMessage());

            return $e->getMessage();
        }
    }
632971
private function setInputAndOutput(InputInterface $input, OutputInterface $output)
    {
        if (is_null($this->assistant)) {
            $this->assistant = new CommandAssistant();
            $this->assistant->setQuestionHelper($this->getQuestionHelper());
            $this->assistant->setKernel($this->getApplication()->getKernel());
        }
        $this->assistant->setOutput($output);
        $this->assistant->setInput($input);
    }
442127
protected function runCommand(InputInterface $input, OutputInterface $output)
    {
        $appName = $input->getArgument('app-name');
        list($_, $indexUUID) = $this->getRepositoryAndIndex($input, $output);

        $this
            ->repositoryBucket
            ->findRepository($appName)
            ->resetIndex($indexUUID);
    }
613250
protected function createEnvironmentsDir(InputInterface $input, OutputInterface $output)
    {
        $targetDir = getcwd() . '/' . $this->envDir;
        $tmplDir = $this->tmplDir . '/environments';

        $output->writeln('  - Environment settings');

        if (file_exists($targetDir)) {
            $question = new ConfirmationQuestion(
                '    <error>Directory ' . $targetDir . ' already exists</error>' . PHP_EOL
                . '    <info>Overwrite? [Y/n]</info> ',
                true,
                '/^(y|j)/i'
            );

            if (!$this->questionHelper->ask($input, $output, $question)) {
                return;
            }
        }

        $fs = new Filesystem();
        $tmplIterator = new \RecursiveDirectoryIterator($tmplDir, \RecursiveDirectoryIterator::SKIP_DOTS);
        $iterator = new \RecursiveIteratorIterator($tmplIterator, \RecursiveIteratorIterator::SELF_FIRST);

        foreach ($iterator as $item) {
            $itemPath = $targetDir . '/' . $iterator->getSubPathName();

            if ($item->isDir()) {
                $fs->mkdir($itemPath);
            } else {
                $fs->copy($item, $itemPath, true);
            }
        }

        $output->writeln('    Created directory settings of environments: <comment>' . $targetDir . '</comment>');
    }
341644
public function boot(Application $application, InputInterface $input, $output)
    {
        if (true === $this->booted) {
            return;
        }

        $this->application = $application;
        $this->input       = $input;
        $this->output      = $output;

        $this->initializeContainer();
        $this->booted = true;
    }
199112
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $ssl = new OpenSslHasher();
        $key = $ssl->createiv();
        $envset = env_set('APP_TOKEN', $key);

        if ($envset) {
            $output->writeln('<info>App key generated: '.$key.'</>');
        } else {
            $output->writeln('<error>Error generating key!</>');
        }
    }
248127
public function handle(Input $input, Output $output)
    {
        $new_env = strtolower($input->getArgument('environment'));

        $env_path = base_path(".env");

        try {
            if (!file_exists($env_path)) throw new \Exception(".env file is not exist.", 1);

            if (!in_array($new_env, ["development", "production"])) throw new \Exception("Invalid environment. It must be \"development\" or \"production\".", 1);

            $old_env = app_env('APP_ENV');
            file_put_contents($env_path, str_replace("APP_ENV={$old_env}", "APP_ENV={$new_env}", file_get_contents($env_path)));
            $output->writeln("APP_ENV is now {$new_env}");
        } catch (\Exception $e) {
            $output->writeln($e->getMessage());
        }
    }