/** * Executes the application. * * Available options: * * * interactive: Sets the input interactive flag * * decorated: Sets the output decorated flag * * verbosity: Sets the output verbosity flag * * capture_stderr_separately: Make output of stdOut and stdErr separately available * * @param array $input An array of arguments and options * @param array $options An array of options * * @return int The command exit code */ public function run(array $input, $options = array()) { $this->input = new ArrayInput($input); if (isset($options['interactive'])) { $this->input->setInteractive($options['interactive']); } $this->captureStreamsIndependently = array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately']; if (!$this->captureStreamsIndependently) { $this->output = new StreamOutput(fopen('php://memory', 'w', false)); if (isset($options['decorated'])) { $this->output->setDecorated($options['decorated']); } if (isset($options['verbosity'])) { $this->output->setVerbosity($options['verbosity']); } } else { $this->output = new ConsoleOutput(isset($options['verbosity']) ? $options['verbosity'] : ConsoleOutput::VERBOSITY_NORMAL, isset($options['decorated']) ? $options['decorated'] : null); $errorOutput = new StreamOutput(fopen('php://memory', 'w', false)); $errorOutput->setFormatter($this->output->getFormatter()); $errorOutput->setVerbosity($this->output->getVerbosity()); $errorOutput->setDecorated($this->output->isDecorated()); $reflectedOutput = new \ReflectionObject($this->output); $strErrProperty = $reflectedOutput->getProperty('stderr'); $strErrProperty->setAccessible(true); $strErrProperty->setValue($this->output, $errorOutput); $reflectedParent = $reflectedOutput->getParentClass(); $streamProperty = $reflectedParent->getProperty('stream'); $streamProperty->setAccessible(true); $streamProperty->setValue($this->output, fopen('php://memory', 'w', false)); } return $this->statusCode = $this->application->run($this->input, $this->output); }
/** * @return void */ public function onMutationsGenerated() { if ($this->input->getOption('no-progress-bar') || !$this->output->isDecorated()) { return; } $this->moveToLineStart(); }
/** * @phpcsSuppress SlevomatCodingStandard.Typehints.TypeHintDeclaration.missingParameterTypeHint * @param int $step */ public function progressAdvance($step = 1) { if ($this->output->isDecorated() && $step > 0) { $stepTime = (time() - $this->progressBar->getStartTime()) / $step; if ($stepTime > 0 && $stepTime < 1) { $this->progressBar->setRedrawFrequency(1 / $stepTime); } else { $this->progressBar->setRedrawFrequency(1); } } $this->progressBar->setProgress($this->progressBar->getProgress() + $step); }
public function printLegend() { $symbols = array(); foreach (self::$eventStatusMap as $status) { $symbol = $status['symbol']; if ('' === $symbol || isset($symbols[$symbol])) { continue; } $symbols[$symbol] = sprintf('%s-%s', $this->output->isDecorated() ? sprintf($status['format'], $symbol) : $symbol, $status['description']); } $this->output->write(sprintf("\nLegend: %s\n", implode(', ', $symbols))); }
/** * Constructor. * * @param OutputInterface $output An OutputInterface instance * @param int $max Maximum steps (0 if unknown) */ public function __construct(OutputInterface $output, $max = 0) { if ($output instanceof ConsoleOutputInterface) { $output = $output->getErrorOutput(); } $this->output = $output; $this->setMaxSteps($max); if (!$this->output->isDecorated()) { // disable overwrite when output does not support ANSI codes. $this->overwrite = false; // set a reasonable redraw frequency so output isn't flooded $this->setRedrawFrequency($max / 10); } $this->startTime = time(); }
/** * Constructor. * * @param OutputInterface $output An OutputInterface instance * @param int $max Maximum steps (0 if unknown) */ public function __construct(OutputInterface $output, $max = 0) { $this->output = $output; $this->setMaxSteps($max); if (!$this->output->isDecorated()) { // disable overwrite when output does not support ANSI codes. $this->overwrite = false; if ($this->max > 10) { // set a reasonable redraw frequency so output isn't flooded $this->setRedrawFrequency($max / 10); } } $this->setFormat($this->determineBestFormat()); $this->startTime = time(); }
protected function execute(InputInterface $input, OutputInterface $output) { $watch = $input->getOption('watch'); $buffered = new BufferedOutput($output->getVerbosity(), $output->isDecorated()); $service = new StatsService($this->getBeanstalk()); do { $tubes = $service->getAllTubeStats(); if (empty($tubes)) { $output->writeln('No tubes found.'); return; } $table = new Table($buffered); $table->setHeaders($service->getTubeHeaderMapping()); foreach ($tubes as $stats) { if ($stats['current-jobs-buried'] > 0) { $stats['name'] = "<error>{$stats['name']}</error>"; $stats['current-jobs-buried'] = "<error>{$stats['current-jobs-buried']}</error>"; } $table->addRow($stats); } $table->render(); $clearScreen = $watch ? "[H[2J" : ''; $output->write($clearScreen . $buffered->fetch()); $watch && sleep(1); } while ($watch); }
/** * Override run method to internationalize error message. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return int Return code */ public function run(InputInterface $input, OutputInterface $output) { // Set extra colors // The most problem is $output->getFormatter() don't work. // So create new formatter to add extra color. $formatter = new OutputFormatter($output->isDecorated()); $formatter->setStyle('red', new OutputFormatterStyle('red', 'black')); $formatter->setStyle('green', new OutputFormatterStyle('green', 'black')); $formatter->setStyle('yellow', new OutputFormatterStyle('yellow', 'black')); $formatter->setStyle('blue', new OutputFormatterStyle('blue', 'black')); $formatter->setStyle('magenta', new OutputFormatterStyle('magenta', 'black')); $formatter->setStyle('yellow-blue', new OutputFormatterStyle('yellow', 'blue')); $output->setFormatter($formatter); \App::setLocale(\Config::get('syncle::MessageLang')); try { $result = parent::run($input, $output); } catch (\RuntimeException $e) { // All error messages were hard coded in // Symfony/Component/Console/Input/Input.php if ($e->getMessage() == 'Not enough arguments.') { $this->error(\Lang::get('syncle::BaseCommand.ArgumentNotEnough')); } elseif ($e->getMessage() == 'Too many arguments.') { $this->error(\Lang::get('syncle::BaseCommand.TooManyArgument')); } elseif (preg_match('/The "(.+)" option does not exist./', $e->getMessage(), $matches)) { $this->error(\Lang::get('syncle::BaseCommand.OptionNotExist', array('option' => $matches[1]))); } else { $this->error($e->getMessage()); } $result = 1; } return $result; }
public function start(OutputInterface $output, $max = null) { $this->startTime = time(); $this->current = 0; $this->max = (int) $max; $this->output = $output->isDecorated() ? $output : new NullOutput(); $this->lastMessagesLength = 0; $this->barCharOriginal = ''; if (null === $this->format) { switch ($output->getVerbosity()) { case OutputInterface::VERBOSITY_QUIET: $this->format = self::FORMAT_QUIET_NOMAX; if ($this->max > 0) { $this->format = self::FORMAT_QUIET; } break; case OutputInterface::VERBOSITY_VERBOSE: case OutputInterface::VERBOSITY_VERY_VERBOSE: case OutputInterface::VERBOSITY_DEBUG: $this->format = self::FORMAT_VERBOSE_NOMAX; if ($this->max > 0) { $this->format = self::FORMAT_VERBOSE; } break; default: $this->format = self::FORMAT_NORMAL_NOMAX; if ($this->max > 0) { $this->format = self::FORMAT_NORMAL; } break; } } $this->initialize(); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->setFormatter(new Console\Formatter($output->isDecorated())); $this->io = new Console\IO($input, $output, $this->getHelperSet()); $spec = $input->getArgument('spec'); if (!is_dir($specsPath = $input->getOption('spec-path'))) { mkdir($specsPath, 0777, true); } if ($srcPath = $input->getOption('src-path')) { $spec = preg_replace('#^' . preg_quote($srcPath, '#') . '/#', '', $spec); } $spec = preg_replace('#\\.php$#', '', $spec); $spec = str_replace('/', '\\', $spec); $specsPath = realpath($specsPath) . DIRECTORY_SEPARATOR; $subject = str_replace('/', '\\', $spec); $classname = $input->getOption('namespace') . $subject; $filepath = $specsPath . str_replace('\\', DIRECTORY_SEPARATOR, $spec) . '.php'; $namespace = str_replace('/', '\\', dirname(str_replace('\\', DIRECTORY_SEPARATOR, $classname))); $class = basename(str_replace('\\', DIRECTORY_SEPARATOR, $classname)); if (file_exists($filepath)) { $overwrite = $this->io->askConfirmation(sprintf('File "%s" already exists. Overwrite?', basename($filepath)), false); if (!$overwrite) { return 1; } $this->io->writeln(); } $dirpath = dirname($filepath); if (!is_dir($dirpath)) { mkdir($dirpath, 0777, true); } file_put_contents($filepath, $this->getSpecContentFor(array('%classname%' => $classname, '%namespace%' => $namespace, '%filepath%' => $filepath, '%class%' => $class, '%subject%' => $subject))); $output->writeln(sprintf("<info>Specification for <value>%s</value> created in <value>%s</value>.</info>\n", $subject, $this->relativizePath($filepath))); }
/** * Constructor. * * @param OutputInterface $output An OutputInterface instance * @param int $max Maximum steps (0 if unknown) */ public function __construct(OutputInterface $output, $max = 0) { // Disabling output when it does not support ANSI codes as it would result in a broken display anyway. $this->output = $output->isDecorated() ? $output : new NullOutput(); $this->setMaxSteps($max); $this->setFormat($this->determineBestFormat()); $this->startTime = time(); }
/** * Create ProcessSet from given files, optionally filtering by given $groups and $excludeGroups * * @param Finder $files * @param array $groups Groups to be run * @param array $excludeGroups Groups to be excluded * @param string $filter filter test cases by name * @return ProcessSet */ public function createFromFiles(Finder $files, array $groups = null, array $excludeGroups = null, $filter = null) { $files->sortByName(); $processSet = $this->getProcessSet(); if ($groups || $excludeGroups || $filter) { $this->output->writeln('Filtering testcases:'); } if ($groups) { $this->output->writeln(sprintf(' - by group(s): %s', implode(', ', $groups))); } if ($excludeGroups) { $this->output->writeln(sprintf(' - excluding group(s): %s', implode(', ', $excludeGroups))); } if ($filter) { $this->output->writeln(sprintf(' - by testcase/test name: %s', $filter)); } $testCasesNum = 0; foreach ($files as $file) { $fileName = $file->getRealpath(); // Parse classes from the testcase file $classes = AnnotationsParser::parsePhp(\file_get_contents($fileName)); // Get annotations for the first class in testcase (one file = one class) $annotations = AnnotationsParser::getAll(new \ReflectionClass(key($classes))); // Filter out test-cases having any of excluded groups if ($excludeGroups && array_key_exists('group', $annotations) && count($excludingGroups = array_intersect($excludeGroups, $annotations['group']))) { if ($this->output->isDebug()) { $this->output->writeln(sprintf('Excluding testcase file %s with group %s', $fileName, implode(', ', $excludingGroups))); } continue; } // Filter out test-cases without any matching group if ($groups) { if (!array_key_exists('group', $annotations) || !count($matchingGroups = array_intersect($groups, $annotations['group']))) { continue; } if ($this->output->isDebug()) { $this->output->writeln(sprintf('Found testcase file #%d in group %s: %s', ++$testCasesNum, implode(', ', $matchingGroups), $fileName)); } } else { if ($this->output->isDebug()) { $this->output->writeln(sprintf('Found testcase file #%d: %s', ++$testCasesNum, $fileName)); } } $phpunitArgs = ['--log-junit=logs/' . Strings::webalize(key($classes), null, $lower = false) . '.xml', '--configuration=' . realpath(__DIR__ . '/../phpunit.xml')]; if ($filter) { $phpunitArgs[] = '--filter=' . $filter; } // If ANSI output is enabled, turn on colors in PHPUnit if ($this->output->isDecorated()) { $phpunitArgs[] = '--colors=always'; } $processSet->add($this->buildProcess($fileName, $phpunitArgs), key($classes), $delayAfter = !empty($annotations['delayAfter']) ? current($annotations['delayAfter']) : '', $delayMinutes = !empty($annotations['delayMinutes']) ? current($annotations['delayMinutes']) : null); } return $processSet; }
public function autoShowProgressIndicator() { if ($this->autoDisplayInterval < 0 || !isset($this->progressBar) || !$this->output->isDecorated()) { return; } if ($this->autoDisplayInterval <= $this->getExecutionTime()) { $this->autoDisplayInterval = -1; $this->progressBar->start($this->totalSteps); $this->showProgressIndicator(); } }
/** * Returns the task status section based on the context. * * @param array $context * * @return string */ private function getTaskActionStatusSectionFromContext(array $context) { $actionStatusSection = ''; if ($this->output->isDecorated()) { $actionStatusSection = sprintf(self::ANSI_CURSOR_BACKWARD_FORMAT, 1); } if (isset($context['event.task.action']) && isset($this->taskActionStatusToOutputMap[$context['event.task.action']])) { $actionStatusSection = sprintf('[<event-task-action-%1$s>%2$s</event-task-action-%1$s>]', $context['event.task.action'], $this->taskActionStatusToOutputMap[$context['event.task.action']]); } return $actionStatusSection; }
protected function execute(InputInterface $input, OutputInterface $output) { $project = $input->getOption('project'); $multiple = 1 < count($project); $color = $output->isDecorated(); $optList = $input->getOption('list'); $optNull = $input->getOption('null'); $optNoLine = $input->getOption('no-lines'); $dom = new \DOMDocument(); $dom->loadHTML(file_get_contents(rtrim($input->getOption('server'), '/') . '/search?' . '&n=' . $input->getOption('max-count') . '&q=' . rawurlencode($input->getArgument('query')) . '&project=' . implode('&project=', $project) . '&path=' . rawurlencode($input->getOption('path')) . '&sort=fullpath')); $xpath = new \DOMXPath($dom); $results = $xpath->query('//div[@id = "results"]/table/tr/td/tt[@class = "con"]/a[@class = "s"]'); $last = null; for ($i = 0; $i < $results->length; $i++) { $result = $results->item($i); preg_match('@^.*/xref/([^/]+)(/.*)#(\\d+)$@', $result->getAttribute('href'), $file); $out = ''; if ($color) { $out = ($multiple ? "[33m{$file[1]}[36m:" : '') . "[35m{$file[2]}[0m"; } else { $out = ($multiple ? "{$file[1]}:" : '') . $file[2]; } if ($optList) { if ($last == $file[1] . ':' . $file[2]) { continue; } $last = $file[1] . ':' . $file[2]; $out .= $optNull ? chr(0) : "\n"; } else { if ($optNoLine) { $out .= $color ? "[36m:[0m" : ":"; } else { $out .= $color ? "[36m:[32m{$file[3]}[36m:[0m" : ":{$file[3]}:"; } $match = $dom->saveXML($result); if ($color) { $match = preg_replace_callback('@<b>([^<]+)</b>@', function ($match) { return "[31m{$match[1]}[0m"; }, $match); } $match = preg_replace('@^<span class="l">\\d+</span>(.*)$@', '$1', html_entity_decode(strip_tags($match, '<span>'))); $out .= $match . "\n"; } $output->write($out, false, OutputInterface::OUTPUT_RAW); } if (0 == $results->length) { return 1; } elseif (0 < $xpath->query('//div[@id = "results"]/p[@class = "slider"]/a[@class = "more"]')->length) { fwrite(STDERR, 'Results truncated.' . "\n"); } }
/** * Constructor. * * @param OutputInterface $output An OutputInterface instance * @param int $max Maximum steps (0 if unknown) */ public function __construct(OutputInterface $output, $max = 0) { // Disabling output when it does not support ANSI codes as it would result in a broken display anyway. $this->output = $output->isDecorated() ? $output : new NullOutput(); $this->max = (int) $max; $this->stepWidth = $this->max > 0 ? Helper::strlen($this->max) : 4; if (!self::$formatters) { self::$formatters = self::initPlaceholderFormatters(); } if (!self::$formats) { self::$formats = self::initFormats(); } $this->setFormat($this->determineBestFormat()); }
public function __construct(InputInterface $input, OutputInterface $output) { if (!$input->getOption('no-progress-bar')) { $progressBar = new ProgressBar($output); $progressBar->setFormat('verbose'); $progressBar->setBarWidth(58); if (!$output->isDecorated()) { $progressBar->setRedrawFrequency(60); } $this->progressBar = $progressBar; } else { $this->isDisabled = true; } }
public function run(InputInterface $input, OutputInterface $output) { // Set extra colors. // The most problem is $output->getFormatter() don't work... // So create new formatter to add extra color. $formatter = new OutputFormatter($output->isDecorated()); $formatter->setStyle('red', new OutputFormatterStyle('red', 'black')); $formatter->setStyle('green', new OutputFormatterStyle('green', 'black')); $formatter->setStyle('yellow', new OutputFormatterStyle('yellow', 'black')); $formatter->setStyle('blue', new OutputFormatterStyle('blue', 'black')); $formatter->setStyle('magenta', new OutputFormatterStyle('magenta', 'black')); $formatter->setStyle('yellow-blue', new OutputFormatterStyle('yellow', 'blue')); $output->setFormatter($formatter); return parent::run($input, $output); }
/** * {@inheritdoc} */ public function renderException(\Exception $e, OutputInterface $output) { $memory = fopen('php://memory', 'rw'); $errorStream = new StreamOutput($memory, OutputInterface::VERBOSITY_VERY_VERBOSE, $output ? $output->isDecorated() : null, $output ? $output->getFormatter() : null); parent::renderException($e, $errorStream); rewind($memory); $exception = ''; while (!feof($memory)) { $exception .= fread($memory, 8192); } fclose($memory); $console = new ConsoleOutput(); $explode = explode("\n", rtrim($exception)); foreach ($explode as &$line) { $line = $console->prefixWithTimestamp($line); } $output->write(implode("\n", $explode) . "\n"); }
protected function execute(InputInterface $input, OutputInterface $output) { $bot = new Bot($output, self::$config->get('service.name')); if (!$output->isDecorated()) { $bot->render(); return; } // Stay positive: return code 0 when the user quits. if (function_exists('pcntl_signal')) { declare (ticks=1); pcntl_signal(SIGINT, function () { echo "\n"; exit; }); } while (true) { $bot->render(); } }
/** * Execute the "scan" command * * @param InputInterface $input Input object * @param OutputInterface $output Output object * @throws RuntimeException If output format is not valid * @return void */ protected function execute(InputInterface $input, OutputInterface $output) { $dispatcher = new EventDispatcher(); $exitCode = new ExitCodeCatcher(); $dispatcher->addSubscriber($exitCode); $fileIterator = new FileIterator($input->getArgument('path'), $this->parseCsv($input->getOption('ignore-paths')), $this->parseCsv($input->getOption('extensions'))); $format = strtolower($input->getOption('format')); switch ($format) { case 'dots': case 'progress': $output->writeln("<info>Parse: A PHP Security Scanner</info>\n"); if ($output->isVeryVerbose()) { $dispatcher->addSubscriber(new ConsoleDebug($output)); } elseif ($output->isVerbose()) { $dispatcher->addSubscriber(new ConsoleLines($output)); } elseif ('progress' == $format && $output->isDecorated()) { $dispatcher->addSubscriber(new ConsoleProgressBar(new ProgressBar($output, count($fileIterator)))); } else { $dispatcher->addSubscriber(new ConsoleDots($output)); } $dispatcher->addSubscriber(new ConsoleReport($output)); break; case 'xml': $dispatcher->addSubscriber(new Xml($output)); break; default: throw new RuntimeException("Unknown output format '{$input->getOption('format')}'"); } $ruleFactory = new RuleFactory($this->parseCsv($input->getOption('whitelist-rules')), $this->parseCsv($input->getOption('blacklist-rules'))); $ruleCollection = $ruleFactory->createRuleCollection(); $ruleNames = implode(',', array_map(function (RuleInterface $rule) { return $rule->getName(); }, $ruleCollection->toArray())); $dispatcher->dispatch(Events::DEBUG, new MessageEvent("Using ruleset {$ruleNames}")); $docCommentFactory = new DocCommentFactory(); $scanner = new Scanner($dispatcher, new CallbackVisitor($ruleCollection, $docCommentFactory, !$input->getOption('disable-annotations'))); $scanner->scan($fileIterator); return $exitCode->getExitCode(); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->setFormatter(new Console\Formatter($output->isDecorated())); $this->io = new Console\IO($input, $output, $this->getHelperSet()); $presenter = $this->createPresenter(); $mocker = $this->createMocker(); $unwrapper = $this->createArgumentsUnwrapper(); $matchers = $this->createMatchersCollection($presenter, $unwrapper); $collector = $this->createStatisticsCollector(); $formatter = $this->createFormatter($input->getOption('format'), $presenter, $collector); $specifications = $this->createLocator()->getSpecifications($input->getArgument('spec')); $runner = $this->createRunner($matchers, $mocker, $unwrapper); $this->configureAdditionalListeners($input->getOption('src-path')); $this->dispatcher->dispatch('beforeSuite', new Event\SuiteEvent($collector)); $result = 0; $startTime = microtime(true); foreach ($specifications as $spec) { $result = max($result, $runner->runSpecification($spec)); } $this->dispatcher->dispatch('afterSuite', new Event\SuiteEvent(microtime(true) - $startTime, $result)); return intval(Event\ExampleEvent::PASSED !== $result); }
/** * Wait for a single activity to complete, and display the log continuously. * * @param Activity $activity * @param OutputInterface $output * @param string $success * @param string $failure * * @return bool * True if the activity succeeded, false otherwise. */ public static function waitAndLog(Activity $activity, OutputInterface $output, $success = null, $failure = null) { $output->writeln('Waiting for the activity <info>' . $activity->id . '</info> (' . $activity->getDescription() . "):"); // Initialize a progress bar which will show elapsed time and the // activity's state. $bar = new ProgressBar($output); $bar->setPlaceholderFormatterDefinition('state', function () use($activity) { return self::formatState($activity->state); }); $bar->setFormat(" [%bar%] %elapsed:6s% (%state%)"); $bar->start(); // Wait for the activity to complete. $activity->wait(function () use($bar) { $bar->advance(); }, function ($log) use($output, $bar) { // Clear the progress bar and ensure the current line is flushed. $bar->clear(); $output->write($output->isDecorated() ? "\n[1A" : "\n"); // Display the new log output, with an indent. $output->write(preg_replace('/^/m', ' ', $log)); // Display the progress bar again. $bar->advance(); }); $bar->finish(); $output->writeln(''); // Display the success or failure messages. switch ($activity['result']) { case Activity::RESULT_SUCCESS: $output->writeln($success ?: "Activity <info>{$activity->id}</info> succeeded"); return true; case Activity::RESULT_FAILURE: $output->writeln($failure ?: "Activity <error>{$activity->id}</error> failed"); return false; } return false; }
/** * {@inheritdoc} */ public function isDecorated() { return $this->output->isDecorated(); }
/** * @see Command */ protected function execute(InputInterface $input, OutputInterface $output) { $verbosity = $output->getVerbosity(); $resolver = new ConfigurationResolver($this->defaultConfig, array('allow-risky' => $input->getOption('allow-risky'), 'config' => $input->getOption('config'), 'dry-run' => $input->getOption('dry-run'), 'rules' => $input->getOption('rules'), 'path' => $input->getArgument('path'), 'path-mode' => $input->getOption('path-mode'), 'progress' => OutputInterface::VERBOSITY_VERBOSE <= $verbosity && 'txt' === $input->getOption('format'), 'using-cache' => $input->getOption('using-cache'), 'cache-file' => $input->getOption('cache-file'), 'format' => $input->getOption('format'), 'diff' => $input->getOption('diff')), getcwd()); $reporter = $resolver->getReporter(); $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : ('txt' === $reporter->getFormat() ? $output : null); if (null !== $stdErr && extension_loaded('xdebug')) { $stdErr->writeln(sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'You are running php-cs-fixer with xdebug enabled. This has a major impact on runtime performance.')); } $configFile = $resolver->getConfigFile(); if (null !== $stdErr) { $stdErr->writeln(sprintf('Loaded config <comment>%s</comment>%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "' . $configFile . '"')); } if (null !== $stdErr && $resolver->getUsingCache()) { $cacheFile = $resolver->getCacheFile(); if (is_file($cacheFile)) { $stdErr->writeln(sprintf('Using cache file "%s".', $cacheFile)); } } $showProgress = $resolver->getProgress(); $runner = new Runner($resolver->getFinder(), $resolver->getFixers(), $input->getOption('diff') ? new SebastianBergmannDiffer() : new NullDiffer(), $showProgress ? $this->eventDispatcher : null, $this->errorsManager, $resolver->getLinter(), $resolver->isDryRun(), $resolver->getCacheManager()); $progressOutput = $showProgress && $stdErr ? new ProcessOutput($stdErr, $this->eventDispatcher) : new NullOutput(); $this->stopwatch->start('fixFiles'); $changed = $runner->fix(); $this->stopwatch->stop('fixFiles'); $progressOutput->printLegend(); $fixEvent = $this->stopwatch->getEvent('fixFiles'); $reportSummary = new ReportSummary($changed, $fixEvent->getDuration(), $fixEvent->getMemory(), OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity(), $resolver->isDryRun(), $output->isDecorated()); if ($output->isDecorated()) { $output->write($reporter->generate($reportSummary)); } else { $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW); } $invalidErrors = $this->errorsManager->getInvalidErrors(); $exceptionErrors = $this->errorsManager->getExceptionErrors(); $lintErrors = $this->errorsManager->getLintErrors(); if (null !== $stdErr) { if (count($invalidErrors) > 0) { $this->listErrors($stdErr, 'linting before fixing', $invalidErrors); } if (count($exceptionErrors) > 0) { $this->listErrors($stdErr, 'fixing', $exceptionErrors); } if (count($lintErrors) > 0) { $this->listErrors($stdErr, 'linting after fixing', $lintErrors); } } return $this->calculateExitStatus($resolver->isDryRun(), count($changed) > 0, count($invalidErrors) > 0, count($exceptionErrors) > 0); }
function it_should_know_if_the_output_is_decorated(OutputInterface $output) { $output->isDecorated()->willReturn(true); $this->isDecorated()->shouldBe(true); }
private function initializeOutputStub(OutputInterface $output) { $output->isDecorated()->willReturn(true); $output->writeln(Argument::type('string'), Argument::any())->willReturn(null); }
protected function execute(InputInterface $input, OutputInterface $output) { $projectId = $input->getArgument('id'); $environmentOption = $input->getOption('environment'); $hostOption = $input->getOption('host'); if (empty($projectId)) { if ($input->isInteractive() && ($projects = $this->api()->getProjects(true))) { $projectId = $this->offerProjectChoice($projects, $input); } else { $this->stdErr->writeln("<error>You must specify a project.</error>"); return 1; } } else { $result = $this->parseProjectId($projectId); $projectId = $result['projectId']; $hostOption = $hostOption ?: $result['host']; $environmentOption = $environmentOption ?: $result['environmentId']; } $project = $this->api()->getProject($projectId, $hostOption, true); if (!$project) { $this->stdErr->writeln("<error>Project not found: {$projectId}</error>"); return 1; } $environments = $this->api()->getEnvironments($project); if ($environmentOption) { if (!isset($environments[$environmentOption])) { // Reload the environments list. $environments = $this->api()->getEnvironments($project, true); if (!isset($environments[$environmentOption])) { $this->stdErr->writeln("Environment not found: <error>{$environmentOption}</error>"); } return 1; } $environmentId = $environmentOption; } elseif (count($environments) === 1) { $environmentId = key($environments); } else { $environmentId = 'master'; } $directory = $input->getArgument('directory'); if (empty($directory)) { $slugify = new Slugify(); $directory = $project->title ? $slugify->slugify($project->title) : $project->id; /** @var \Platformsh\Cli\Helper\QuestionHelper $questionHelper */ $questionHelper = $this->getHelper('question'); $directory = $questionHelper->askInput('Directory', $directory); } if ($projectRoot = $this->getProjectRoot()) { if (strpos(realpath(dirname($directory)), $projectRoot) === 0) { $this->stdErr->writeln("<error>A project cannot be cloned inside another project.</error>"); return 1; } } // Create the directory structure. if (file_exists($directory)) { $this->stdErr->writeln("The directory <error>{$directory}</error> already exists"); return 1; } if (!($parent = realpath(dirname($directory)))) { throw new \Exception("Not a directory: " . dirname($directory)); } $projectRoot = $parent . '/' . basename($directory); // Prepare to talk to the remote repository. $gitUrl = $project->getGitUrl(); $gitHelper = new GitHelper(new ShellHelper($this->stdErr)); $gitHelper->ensureInstalled(); // First check if the repo actually exists. try { $exists = $gitHelper->remoteRepoExists($gitUrl); } catch (\Exception $e) { // The ls-remote command failed. $this->stdErr->writeln('<error>Failed to connect to the ' . self::$config->get('service.name') . ' Git server</error>'); // Suggest SSH key commands. $sshKeys = []; try { $sshKeys = $this->api()->getClient(false)->getSshKeys(); } catch (\Exception $e) { // Ignore exceptions. } if (!empty($sshKeys)) { $this->stdErr->writeln(''); $this->stdErr->writeln('Please check your SSH credentials'); $this->stdErr->writeln('You can list your keys with: <comment>' . self::$config->get('application.executable') . ' ssh-keys</comment>'); } else { $this->stdErr->writeln('You probably need to add an SSH key, with: <comment>' . self::$config->get('application.executable') . ' ssh-key:add</comment>'); } return 1; } $projectConfig = ['id' => $projectId]; $host = parse_url($project->getUri(), PHP_URL_HOST); if ($host) { $projectConfig['host'] = $host; } // If the remote repository exists, then locally we need to create the // folder, run git init, and attach the remote. if (!$exists) { $this->stdErr->writeln('Creating project directory: <info>' . $directory . '</info>'); if (mkdir($projectRoot) === false) { $this->stdErr->writeln('Failed to create the project directory.'); return 1; } // Initialize the repo and attach our remotes. $this->debug('Initializing the repository'); $gitHelper->init($projectRoot, true); // As soon as there is a Git repo present, add the project config file. $this->localProject->writeCurrentProjectConfig($projectConfig, $projectRoot); $this->debug('Adding Git remote(s)'); $this->localProject->ensureGitRemote($projectRoot, $gitUrl); $this->stdErr->writeln(''); $this->stdErr->writeln('Your project has been initialized and connected to <info>' . self::$config->get('service.name') . '</info>!'); $this->stdErr->writeln(''); $this->stdErr->writeln('Commit and push to the <info>master</info> branch of the <info>' . self::$config->get('detection.git_remote_name') . '</info> Git remote, and ' . self::$config->get('service.name') . ' will build your project automatically.'); return 0; } // We have a repo! Yay. Clone it. $projectLabel = $this->api()->getProjectLabel($project); $this->stdErr->writeln('Downloading project ' . $projectLabel); $cloneArgs = ['--branch', $environmentId, '--origin', self::$config->get('detection.git_remote_name')]; if ($output->isDecorated()) { $cloneArgs[] = '--progress'; } $cloned = $gitHelper->cloneRepo($gitUrl, $projectRoot, $cloneArgs); if ($cloned === false) { // The clone wasn't successful. Clean up the folders we created // and then bow out with a message. $this->stdErr->writeln('<error>Failed to clone Git repository</error>'); $this->stdErr->writeln('Please check your SSH credentials or contact ' . self::$config->get('service.name') . ' support'); return 1; } $this->setProjectRoot($projectRoot); $this->localProject->writeCurrentProjectConfig($projectConfig, $projectRoot); $this->localProject->ensureGitRemote($projectRoot, $gitUrl); $gitHelper->updateSubmodules(true, $projectRoot); $this->stdErr->writeln("\nThe project <info>{$projectLabel}</info> was successfully downloaded to: <info>{$directory}</info>"); // Return early if there is no code in the repository. if (!glob($projectRoot . '/*', GLOB_NOSORT)) { return 0; } // Ensure that Drush aliases are created. if (Drupal::isDrupal($projectRoot)) { $this->stdErr->writeln(''); $this->runOtherCommand('local:drush-aliases', ['--group' => basename($directory)]); } // Launch the first build. $success = true; if ($input->getOption('build')) { // Launch the first build. $this->stdErr->writeln(''); $this->stdErr->writeln('Building the project locally for the first time. Run <info>' . self::$config->get('application.executable') . ' build</info> to repeat this.'); $options = ['no-clean' => true]; $builder = new LocalBuild($options, self::$config, $output); $success = $builder->build($projectRoot); } else { $this->stdErr->writeln("\nYou can build the project with: " . "\n cd {$directory}" . "\n " . self::$config->get('application.executable') . " build"); } return $success ? 0 : 1; }
/** * @return bool */ public function shouldColor() { return $this->output->isDecorated(); }
/** * Processes data from container and console input. * * @param InputInterface $input * @param OutputInterface $output */ public function process(InputInterface $input, OutputInterface $output) { $translator = $this->container->get('behat.translator'); $manager = $this->container->get('behat.formatter.manager'); $formats = array_map('trim', explode(',', $input->getOption('format') ?: $this->container->getParameter('behat.formatter.name'))); // load formatters translations foreach (require $this->container->getParameter('behat.paths.i18n') as $lang => $messages) { $translator->addResource('array', $messages, $lang, 'behat'); } // add user-defined formatter classes to manager foreach ($this->container->getParameter('behat.formatter.classes') as $name => $class) { $manager->addDispatcher(new FormatterDispatcher($name, $class)); } // init specified for run formatters foreach ($formats as $format) { $manager->initFormatter($format); } // set formatter options from behat.yml foreach ($parameters = $this->container->getParameter('behat.formatter.parameters') as $name => $value) { if ('output_path' === $name) { continue; } $manager->setFormattersParameter($name, $value); } $manager->setFormattersParameter('base_path', $this->container->getParameter('behat.paths.base')); $manager->setFormattersParameter('support_path', $this->container->getParameter('behat.paths.bootstrap')); $manager->setFormattersParameter('decorated', $output->isDecorated()); if ($input->getOption('verbose')) { $manager->setFormattersParameter('verbose', true); } if ($input->getOption('lang')) { $manager->setFormattersParameter('language', $input->getOption('lang')); } if (null !== ($ansi = $this->getSwitchValue($input, 'ansi'))) { $output->setDecorated($ansi); $manager->setFormattersParameter('decorated', $ansi); } if (null !== ($time = $this->getSwitchValue($input, 'time'))) { $manager->setFormattersParameter('time', $time); } if (null !== ($snippets = $this->getSwitchValue($input, 'snippets'))) { $manager->setFormattersParameter('snippets', $snippets); } if (null !== ($snippetsPaths = $this->getSwitchValue($input, 'snippets-paths'))) { $manager->setFormattersParameter('snippets_paths', $snippetsPaths); } if (null !== ($paths = $this->getSwitchValue($input, 'paths'))) { $manager->setFormattersParameter('paths', $paths); } if (null !== ($expand = $this->getSwitchValue($input, 'expand'))) { $manager->setFormattersParameter('expand', $expand); } if (null !== ($multiline = $this->getSwitchValue($input, 'multiline'))) { $manager->setFormattersParameter('multiline_arguments', $multiline); } if ($input->getOption('out')) { $outputs = $input->getOption('out'); } elseif (isset($parameters['output_path'])) { $outputs = $parameters['output_path']; } else { return; } if (false === strpos($outputs, ',')) { $out = $this->container->getParameter('behat.paths.base') . DIRECTORY_SEPARATOR . $outputs; // get realpath if (!file_exists($out)) { touch($out); $out = realpath($out); unlink($out); } else { $out = realpath($out); } $manager->setFormattersParameter('output_path', $out); $manager->setFormattersParameter('decorated', (bool) $this->getSwitchValue($input, 'ansi')); } else { foreach (array_map('trim', explode(',', $outputs)) as $i => $out) { if (!$out || 'null' === $out || 'false' === $out) { continue; } $out = $this->container->getParameter('behat.paths.base') . DIRECTORY_SEPARATOR . $out; // get realpath if (!file_exists($out)) { touch($out); $out = realpath($out); unlink($out); } else { $out = realpath($out); } $formatters = $manager->getFormatters(); if (isset($formatters[$i])) { $formatters[$i]->setParameter('output_path', $out); $formatters[$i]->setParameter('decorated', (bool) $this->getSwitchValue($input, 'ansi')); } } } }