/** * Execute command * * @param InputInterface $input * @param OutputInterface $output * * @return bool */ protected function execute(InputInterface $input, OutputInterface $output) { $quiet = $output->getVerbosity() == OutputInterface::VERBOSITY_QUIET; $verbose = $output->getVerbosity() == OutputInterface::VERBOSITY_VERBOSE; if (!$quiet) { $output->write('<info>' . $this->getApplication()->getName() . '</info>'); $output->write(' version <comment>' . $this->getApplication()->getVersion() . '</comment> '); $output->writeln("by J.Ginés Hernández G. <*****@*****.**>\n"); } $sourcePath = $input->getArgument('source'); $destPath = $input->getArgument('dest'); $formatType = $input->getOption('format'); $sortImg = new PhotoSort($verbose); $items = $sortImg->copy($sourcePath, $destPath, $formatType); if ($verbose) { if (count($items)) { $table = new Table($output); $table->setHeaders(array('Old File', 'New File')); $table->setRows($items); $table->render(); } $output->writeln("\nCheers!\n"); } return true; }
/** * 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); }
protected function initHandlers(OutputInterface $output) { $this->output = $output; $this->formatter = $this->getHelperSet()->get('formatter'); $this->is_verbose = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL; $this->logger = $this->getContainer()->get('logger'); }
/** * Execute the console command * * @param InputInterface $input * @param OutputInterface $output */ public function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; $logger = $this->logger; Resque_Event::listen('onFailure', function ($exception, $job) use($logger) { $logger->error('Error processing job', ['exception' => $exception]); }); if ($input->getOption('shutdown')) { $this->shutdownWorkers(); return; } $queues = $input->getArgument('queue'); if (!count($queues)) { throw new RuntimeException('Not enough arguments.'); } $count = $input->getOption('count'); $interval = $input->getOption('interval'); if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) { $logLevel = Resque_Worker::LOG_NORMAL; } elseif ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $logLevel = Resque_Worker::LOG_VERBOSE; } else { $logLevel = Resque_Worker::LOG_NONE; } $this->startWorkers($queues, $count, $logLevel, $interval); }
/** * @param array $input * @throws \Exception */ protected function handleError(array $input) { if (OutputInterface::VERBOSITY_VERBOSE <= $this->output->getVerbosity()) { $this->output->writeln(print_r($input, true)); } throw new \Exception($input['message']); }
protected function logVerbose($msg) { if ($this->output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) { return; } $this->output->writeln($msg); }
protected function execute(InputInterface $input, OutputInterface $output) { $confirm = $input->getOption('confirm'); $perms = \Perms::get(); if (!$perms->admin_file_galleries) { throw new \Exception('Tracker Clear: Admin permission required'); } if ($confirm) { if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln('<info>Deleting old filegal files...</info>'); } \TikiLib::lib('filegal')->deleteOldFiles(); if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln('<info>Deleting old filegal files done</info>'); } } else { $query = 'select * from `tiki_files` where `deleteAfter` < ? - `lastModif` and `deleteAfter` is not NULL and `deleteAfter` != \'\' order by galleryId asc'; $now = time(); $files = \TikiDb::get()->query($query, array($now)); if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { if ($files->numrows) { $output->writeln("<comment>Files to delete:</comment>"); foreach ($files->result as $file) { $old = ceil(abs($now - $file['lastModif']) / 86400); $days = $old > 1 ? 'days' : 'day'; $deleteAfter = \TikiLib::lib('tiki')->get_short_datetime($file['deleteAfter']); $output->writeln("<info> \"{$file['name']}\" is {$old} {$days} old in gallery #{$file['galleryId']} (id #{$file['fileId']} deleteAfter {$deleteAfter})</info>"); } } else { $output->writeln("<comment>No files to delete</comment>"); } } } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { /* @var $listener \Hearsay\SuperfeedrBundle\Listening\ListenerInterface */ $listener = $this->getContainer()->get('hearsay_superfeedr.listener'); $listener->addNotificationHandler(new NotificationPrinter($output)); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) { $output->writeln(''); $output->writeln('<info>Listening for messages...</info>'); $output->writeln(''); } try { $listener->listen(); } catch (\Exception $exception) { if ($input->getOption('die')) { // @codeCoverageIgnoreStart die($exception->getMessage() . "\n"); // @codeCoverageIgnoreEnd } else { throw $exception; } } if ($output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) { $output->writeln('<info>Finished listening.</info>'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $sshUrl = $this->getSelectedEnvironment()->getSshUrl($this->selectApp($input)); if ($input->getOption('pipe')) { $output->write($sshUrl); return 0; } $remoteCommand = $input->getArgument('cmd'); if (!$remoteCommand && $this->runningViaMulti) { throw new \InvalidArgumentException('The cmd argument is required when running via "multi"'); } $sshOptions = 't'; // Pass through the verbosity options to SSH. if ($output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) { $sshOptions .= 'vv'; } elseif ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $sshOptions .= 'v'; } elseif ($output->getVerbosity() <= OutputInterface::VERBOSITY_QUIET) { $sshOptions .= 'q'; } $command = "ssh -{$sshOptions} " . escapeshellarg($sshUrl); if ($remoteCommand) { $command .= ' ' . escapeshellarg($remoteCommand); } return $this->getHelper('shell')->executeSimple($command); }
/** * Run a command through the ProcessBuilder. * * @param string|array $command * @param bool $allowFailures * @param \Closure $callback Callback for Process (e.g. for logging output in realtime) * @param bool $cacheMultipleCalls Call multiple calls with this command (to speed-up execution) * * @throws \RuntimeException * @throws \InvalidArgumentException * * @return string */ public function runCommand($command, $allowFailures = false, $callback = null, $cacheMultipleCalls = false) { if (is_string($command)) { $command = $this->parseProcessArguments($command); } $cacheKey = getcwd() . implode(' ', $command); if ($cacheMultipleCalls && isset($this->cache[$cacheKey])) { return $this->cache[$cacheKey]; } $builder = new ProcessBuilder($command); $builder->setWorkingDirectory(getcwd())->setTimeout(3600); $process = $builder->getProcess(); $remover = function ($untrimmed) { return ltrim(rtrim($untrimmed, "'"), "'"); }; if ($this->output instanceof OutputInterface) { if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $commandLine = implode(' ', array_map($remover, explode(' ', $process->getCommandLine()))); $this->output->writeln('<question>CMD</question> ' . $commandLine); } } $process->run($callback); if (!$process->isSuccessful() && !$allowFailures) { throw new \RuntimeException($process->getErrorOutput()); } $result = trim($process->getOutput()); if ($cacheMultipleCalls) { $this->cache[$cacheKey] = $result; } return $result; }
/** * @param Process $process * @param bool $mustRun * @param bool $quiet * * @return int|string * @throws \Exception */ protected function runProcess(Process $process, $mustRun = false, $quiet = true) { if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $this->output->writeln("Running command: <info>" . $process->getCommandLine() . "</info>"); } try { $process->mustRun($quiet ? null : function ($type, $buffer) { $this->output->write(preg_replace('/^/m', ' ', $buffer)); }); } catch (ProcessFailedException $e) { if (!$mustRun) { return $process->getExitCode(); } // The default for ProcessFailedException is to print the entire // STDOUT and STDERR. But if $quiet is disabled, then the user will // have already seen the command's output. So we need to re-throw // the exception with a much shorter message. $message = "The command failed with the exit code: " . $process->getExitCode(); $message .= "\n\nFull command: " . $process->getCommandLine(); if ($quiet) { $message .= "\n\nError output:\n" . $process->getErrorOutput(); } throw new \Exception($message); } $output = $process->getOutput(); return $output ? rtrim($output) : true; }
public function verbose($log) { if ($this->output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $log = preg_replace('/^/m', "\t", $log); $this->output->writeln($log); } }
function it_should_not_handle_log_when_verbosity_set_to_quiet(OutputInterface $output) { $output->getVerbosity()->shouldBeCalled()->willReturn(OutputInterface::VERBOSITY_QUIET); $this->isHandling(array('level' => Logger::NOTICE))->shouldReturn(false); $output->getVerbosity()->shouldBeCalled()->willReturn(OutputInterface::VERBOSITY_DEBUG); $this->isHandling(array('level' => Logger::NOTICE))->shouldReturn(true); }
/** * @param Throwable $exception */ protected function outputExceptionTrace(Throwable $exception) { if ($this->output->getVerbosity() >= $this->options['minTraceVerbosity']) { $this->output->writeln(sprintf($this->options['traceTemplate'], $exception->getTraceAsString())); } return $this; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Start up application with supplied config...'); $config = $input->getArgument('applicationConfig'); $path = stream_resolve_include_path($config); if (!is_readable($path)) { throw new \InvalidArgumentException("Invalid loader path: {$config}"); } // Init the application once using given config // This way the late static binding on the AspectKernel // will be on the goaop-zf2-module kernel \Zend\Mvc\Application::init(include $path); if (!class_exists(AspectKernel::class, false)) { $message = "Kernel was not initialized yet. Maybe missing module Go\\ZF2\\GoAopModule in config {$path}"; throw new \InvalidArgumentException($message); } $kernel = AspectKernel::getInstance(); $options = $kernel->getOptions(); if (empty($options['cacheDir'])) { throw new \InvalidArgumentException('Cache warmer require the `cacheDir` options to be configured'); } $enumerator = new Enumerator($options['appDir'], $options['includePaths'], $options['excludePaths']); $iterator = $enumerator->enumerate(); $totalFiles = iterator_count($iterator); $output->writeln("Total <info>{$totalFiles}</info> files to process."); $iterator->rewind(); set_error_handler(function ($errno, $errstr, $errfile, $errline) { throw new \ErrorException($errstr, $errno, 0, $errfile, $errline); }); $index = 0; $errors = []; foreach ($iterator as $file) { if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln("Processing file <info>{$file->getRealPath()}</info>"); } $isSuccess = null; try { // This will trigger creation of cache file_get_contents(FilterInjectorTransformer::PHP_FILTER_READ . SourceTransformingLoader::FILTER_IDENTIFIER . '/resource=' . $file->getRealPath()); $isSuccess = true; } catch (\Exception $e) { $isSuccess = false; $errors[$file->getRealPath()] = $e; } if ($output->getVerbosity() == OutputInterface::VERBOSITY_NORMAL) { $output->write($isSuccess ? '.' : '<error>E</error>'); if (++$index % 50 == 0) { $output->writeln("({$index}/{$totalFiles})"); } } } restore_error_handler(); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { foreach ($errors as $file => $error) { $message = "File {$file} is not processed correctly due to exception: {$error->getMessage()}"; $output->writeln($message); } } $output->writeln('<info>Done</info>'); }
protected function execute(InputInterface $input, OutputInterface $output) { $time_start = microtime(true); $site = $input->getArgument('site'); $output->writeln('halting homestead...'); // exec('cd ~/Homestead && vagrant halt', $result); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln($result); } $output->writeln('removing ' . $site . ' from Homestead...'); $yaml = new Parser(); $homesteadFile = $yaml->parse(file_get_contents(getenv("HOME") . '/.homestead/Homestead.yaml')); $directory = str_replace($homesteadFile['folders'][0]['map'], $homesteadFile['folders'][0]['to'], $directory); $sites = $this->removeSiteFromArray($site, $homesteadFile['sites']); $homesteadFile['sites'] = $sites; $dumper = new Dumper(); $yaml = $dumper->dump($homesteadFile, 2); file_put_contents(getenv("HOME") . '/.homestead/Homestead.yaml', $yaml); $output->writeln('adding ' . $site . ' to Hosts...'); exec('cd ' . __DIR__ . '/../Scripts && sudo php RemoveHosts.php ' . $site); $output->writeln('restarting homestead...'); exec('cd ~/Homestead && vagrant up --provision', $result); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln($result); } $output->writeln('SSH into vagrant:'); $output->writeln("\n<comment>cd ~/Homestead && vagrant ssh</comment>"); $output->writeln("\n<comment>http://" . $site . ": has been removed</comment>"); $time_end = microtime(true); $time = $time_end - $time_start; $output->writeln("\nCompleted in: " . $time . " seconds"); }
/** * @inheritdoc * * @throws \Exception * If $mustRun is enabled and the command fails. */ public function execute(array $args, $dir = null, $mustRun = false, $quiet = true) { $builder = new ProcessBuilder($args); $process = $builder->getProcess(); // The default timeout is 1 minute. Increase it to 1 hour. $process->setTimeout(3600); if ($dir) { $process->setWorkingDirectory($dir); } if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $this->output->writeln("Running command: <info>" . $process->getCommandLine() . "</info>"); } try { $process->mustRun($quiet ? null : function ($type, $buffer) { $indent = ' '; $this->output->writeln($indent . str_replace("\n", "\n{$indent}", trim($buffer))); }); } catch (ProcessFailedException $e) { if (!$mustRun) { return false; } // The default for ProcessFailedException is to print the entire // STDOUT and STDERR. But if $quiet is disabled, then the user will // have already seen the command's output. So we need to re-throw // the exception with a much shorter message. $message = "The command failed with the exit code: " . $process->getExitCode(); $message .= "\n\nFull command: " . $process->getCommandLine(); if ($quiet) { $message .= "\n\nError output:\n" . $process->getErrorOutput(); } throw new \Exception($message); } $output = $process->getOutput(); return $output ? rtrim($output) : true; }
protected function execute(InputInterface $input, OutputInterface $output) { $appId = $input->getArgument('app-id'); $codeChecker = new \OC\App\CodeChecker(); $codeChecker->listen('CodeChecker', 'analyseFileBegin', function ($params) use($output) { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln("<info>Analysing {$params}</info>"); } }); $codeChecker->listen('CodeChecker', 'analyseFileFinished', function ($filename, $errors) use($output) { $count = count($errors); // show filename if the verbosity is low, but there are errors in a file if ($count > 0 && OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) { $output->writeln("<info>Analysing {$filename}</info>"); } // show error count if there are errros present or the verbosity is high if ($count > 0 || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln(" {$count} errors"); } usort($errors, function ($a, $b) { return $a['line'] > $b['line']; }); foreach ($errors as $p) { $line = sprintf("%' 4d", $p['line']); $output->writeln(" <error>line {$line}: {$p['disallowedToken']} - {$p['reason']}</error>"); } }); $errors = $codeChecker->analyse($appId); if (empty($errors)) { $output->writeln('<info>App is compliant - awesome job!</info>'); } else { $output->writeln('<error>App is not compliant</error>'); return 1; } }
/** * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { // Symfony version check $version = \Symfony\Component\HttpKernel\Kernel::VERSION_ID; $output->writeln('Symfony version: ' . $version); $output->writeln('Environment: ' . $this->container->get('kernel')->getEnvironment()); $output->writeln('Verbosity level set: ' . $output->getVerbosity()); // Check for the version of Symfony: 20803 is the 2.8 if ($version >= 20803) { $output->writeln('Environment: ' . $this->container->get('kernel')->getEnvironment(), OutputInterface::VERBOSITY_NORMAL); // Write a line with OutputInterface::VERBOSITY_NORMAL (also if this level is set by default by Console) $output->writeln('Verbosity level: NORMAL', OutputInterface::VERBOSITY_NORMAL); // Write a line with OutputInterface::VERBOSITY_VERBOSE $output->writeln('Verbosity level: VERBOSE', OutputInterface::VERBOSITY_VERBOSE); // Write a line with OutputInterface::VERBOSITY_VERY_VERBOSE $output->writeln('Verbosity level: VERY_VERBOSE', OutputInterface::VERBOSITY_VERY_VERBOSE); // Write a line with OutputInterface::VERBOSITY_DEBUG $output->writeln('Verbosity level: DEBUG', OutputInterface::VERBOSITY_DEBUG); } else { if ($output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) { $output->writeln('Verbosity level: NORMAL'); } if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln('Verbosity level: VERBOSE'); } if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $output->writeln('Verbosity level: VERY_VERBOSE'); } if ($output->getVerbosity() == OutputInterface::VERBOSITY_DEBUG) { $output->writeln('Verbosity level: DEBUG'); } } }
/** * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { if ($output->getVerbosity() >= OutputInterface::VERBOSITY_QUIET) { switch ($output->getVerbosity()) { default: case OutputInterface::VERBOSITY_NORMAL: $level = Logger::WARNING; break; case OutputInterface::VERBOSITY_VERBOSE: $level = Logger::NOTICE; break; case OutputInterface::VERBOSITY_VERY_VERBOSE: $level = Logger::INFO; break; case OutputInterface::VERBOSITY_DEBUG: $level = Logger::DEBUG; break; } $handler = new StreamHandler('php://stdout', $level); $this->container['monolog'] = $this->container->share($this->container->extend('monolog', function ($logger) use($handler) { $logger->pushHandler($handler); return $logger; })); $this->container['task-manager.logger'] = $this->container->share($this->container->extend('task-manager.logger', function ($logger) use($handler) { $logger->pushHandler($handler); return $logger; })); } return $this->doExecute($input, $output); }
public function execute(InputInterface $input, OutputInterface $output) { /** @var KernelInterface $kernel */ $kernel = $this->getContainer()->get('kernel'); /** @var DialogHelper $dialog */ $dialog = $this->getHelper('dialog'); $fs = new Filesystem(); $rootDir = $kernel->getRootDir(); if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln('Root directory: <info>' . $rootDir . '</info>'); } if (!file_exists($rootDir . '/app/console')) { throw new \RuntimeException('Command must be executed at the root of a Symfony application.'); } $skeletonDir = $kernel->locateResource('@OrbitaleIntegrationBundle/Resources/skeleton'); $newDirectory = $rootDir; $files = array('Int/config.yml' => 'src', 'Int/routing.yml' => 'src', 'Int/Controller.php' => 'src', 'Int/IntKernel.php' => 'src', 'app_int.php' => 'web'); if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln('Processing files:'); } $forceReplace = $input->getOption('replace'); foreach ($files as $fileName => $destDir) { $baseFile = $skeletonDir . '/' . $fileName; $newFile = $newDirectory . '/' . $destDir . '/' . $fileName; $copy = true; if (file_exists($newFile) && !$forceReplace) { $copy = $dialog->askConfirmation($output, 'The file <info>' . $newFile . '</info> already exists. Do you want to overwrite it? [Y/n] ', true); } if ($copy) { $date = new \DateTime(); $fs->copy($baseFile, $newFile); $output->writeln('<comment>' . $date->format('H:i:s') . '</comment> <info>[file+]</info> ' . $newFile); } } }
/** * Create a styled progress bar * * @param integer $max Max value for the progress bar * @return \Symfony\Component\Console\Helper\ProgressBar */ protected function create_progress_bar($max) { $progress = $this->io->createProgressBar($max); if ($this->output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) { $progress->setFormat('<info>[%percent:3s%%]</info> %message%'); $progress->setOverwrite(false); } else { if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $progress->setFormat('<info>[%current:s%/%max:s%]</info><comment>[%elapsed%/%estimated%][%memory%]</comment> %message%'); $progress->setOverwrite(false); } else { $this->io->newLine(2); $progress->setFormat(" %current:s%/%max:s% %bar% %percent:3s%%\n" . " %message% %elapsed:6s%/%estimated:-6s% %memory:6s%\n"); $progress->setBarWidth(60); } } if (!defined('PHP_WINDOWS_VERSION_BUILD')) { $progress->setEmptyBarCharacter('░'); // light shade character \u2591 $progress->setProgressCharacter(''); $progress->setBarCharacter('▓'); // dark shade character \u2593 } return $progress; }
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $sshUrl = $this->getSelectedEnvironment()->getSshUrl($input->getOption('app')); if ($input->getOption('pipe')) { $output->write($sshUrl); return 0; } $remoteCommand = $input->getArgument('cmd'); if ($input instanceof ArgvInput) { $helper = new ArgvHelper(); $remoteCommand = $helper->getPassedCommand($this, $input); } $sshOptions = 't'; // Pass through the verbosity options to SSH. if ($output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) { $sshOptions .= 'vv'; } elseif ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $sshOptions .= 'v'; } elseif ($output->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) { $sshOptions .= 'q'; } $command = "ssh -{$sshOptions} " . escapeshellarg($sshUrl); if ($remoteCommand) { $command .= ' ' . escapeshellarg($remoteCommand); } if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $this->stdErr->writeln("Running command: <info>{$command}</info>"); } passthru($command, $returnVar); return $returnVar; }
/** * Runs the current application. * * @param InputInterface $input * An Input instance. * @param OutputInterface $output * An Output instance. * * @return int * Returns 0 if everything went fine, or an error code. */ public function doRun(InputInterface $input, OutputInterface $output) { $this->kernel->initialize(); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $this->kernel->get('dispatcher')->addSubscriber(new VerboseSubscriber($output)); } if ($output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) { $this->kernel->get('dispatcher')->addSubscriber(new DebugSubscriber($output)); } $this->kernel->setSugarPath($input->getParameterOption(array('--path', '-p'), null)); $this->registerCommands(); if (true === $input->hasParameterOption(array('--shell', '-s'))) { // @codeCoverageIgnoreStart $shell = new Shell($this); $shell->setProcessIsolation($input->hasParameterOption(array('--process-isolation'))); $shell->run(); return 0; // @codeCoverageIgnoreEnd } $result = parent::doRun($input, $output); if ($this->kernel->isDebug()) { $output->writeln(sprintf('<info>Memory usage: %.2fMB (peak: %.2fMB), time: %.2fs</info>', memory_get_usage() / 1024 / 1024, memory_get_peak_usage() / 1024 / 1024, microtime(true) - $this->kernel->getStartTime())); } return $result; }
/** * @inheritDoc */ protected function execute(InputInterface $input, OutputInterface $output) { // Checking the installer configuration if ($this->filesToUninstall == null || $this->package == null || $this->bundleName == null) { throw new \RuntimeException("The uninstaller is bad configured"); } // Checking the destination directory $destinationDirectory = realpath($this->getContainer()->get("kernel")->locateResource("@" . $this->bundleName) . "/Resources/public"); if ($destinationDirectory === false) { throw new IOException("The directory @" . $this->bundleName . "/Resources/public is not a directory or not exists"); } if ($output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) { $output->writeln("Uninstall <comment>" . $this->package . "</comment>."); } // Uninstalling /** @var Filesystem $filesystem */ $filesystem = $this->getContainer()->get("filesystem"); foreach ($this->filesToUninstall as $destinationName) { $destinationPath = $destinationDirectory . DIRECTORY_SEPARATOR . $destinationName; if ($filesystem->exists($destinationPath)) { $filesystem->remove($destinationPath); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln("<info>[OK]</info> " . $destinationPath); } } } }
public function log($level, $message, array $context = array()) { switch ($level) { case LogLevel::WARNING: case LogLevel::NOTICE: if ($this->output->getVerbosity() < OutputInterface::VERBOSITY_NORMAL) { return; } break; case LogLevel::INFO: if ($this->output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) { return; } break; case LogLevel::DEBUG: if ($this->output->getVerbosity() < OutputInterface::VERBOSITY_DEBUG) { return; } break; } $this->output->writeln(sprintf('[%s] %s', $level, $message)); // based on PSR-3 recommendations if an Exception object is passed in the context data, // it MUST be in the 'exception' key. if (isset($context['exception']) && $context['exception'] instanceof \Exception) { $this->output->writeln((string) $context['exception']); } }
/** * @see Command */ protected function execute(InputInterface $input, OutputInterface $output) { $listenerManager = $this->container->get('doctrine_extensions.listener_manager'); $listenerManager->addAllListeners($this->container->get('doctrine.orm.entity_manager')); // Generating groups $output->writeln('Generating groups'); $groupManager = $this->container->get('fos_user.group_manager'); // Admin $adminGroup = $groupManager->findGroupByName('Admin'); if ($adminGroup === null) { $adminGroup = $groupManager->createGroup('Admin'); $adminGroup->addRole('ROLE_ADMIN'); $groupManager->updateGroup($adminGroup); if ($output->getVerbosity() == Output::VERBOSITY_VERBOSE) { $output->writeln(sprintf('Created group <comment>%s</comment>', $adminGroup->getName())); } } // Moderator $moderatorGroup = $groupManager->findGroupByName('Moderator'); if ($moderatorGroup === null) { $moderatorGroup = $groupManager->createGroup('Moderator'); $moderatorGroup->addRole('ROLE_MODERATOR'); $groupManager->updateGroup($moderatorGroup); if ($output->getVerbosity() == Output::VERBOSITY_VERBOSE) { $output->writeln(sprintf('Created group <comment>%s</comment>', $moderatorGroup->getName())); } } // Special user $output->writeln('Generating special user'); $userManager = $this->container->get('fos_user.user_manager'); if (null === $userManager->findUserByUsername($this->container->getParameter('yrch.special_user.username'))) { $specialUser = $userManager->createUser(); $specialUser->setUsername($this->container->getParameter('yrch.special_user.username')); $specialUser->setNick($this->container->getParameter('yrch.special_user.nick')); $specialUser->setEmail($this->container->getParameter('yrch.special_user.email')); $specialUser->setPreferedLocale($this->container->getParameter('session.default_locale')); $specialUser->setPassword(md5(uniqid() . rand(100000, 999999))); $specialUser->setEnabled(true); $specialUser->setLocked(true); $userManager->updateUser($specialUser); if ($output->getVerbosity() == Output::VERBOSITY_VERBOSE) { $output->writeln(sprintf('Created user <comment>%s</comment>', $specialUser->getNick())); } } // Generating root category $output->writeln('Generating the root category'); $em = $this->container->get('doctrine.orm.entity_manager'); $categoryRepo = $em->getRepository('Application\\YrchBundle\\Entity\\Category'); $rootnodes = $categoryRepo->children(null, true); if (!$rootnodes) { $category = new Category(); $category->setName('Yrch!'); $category->setDescription(''); $em->persist($category); $em->flush(); if ($output->getVerbosity() == Output::VERBOSITY_VERBOSE) { $output->writeln(sprintf('Created category <comment>%s</comment>', $category->getName())); } } }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln("Loading aspect kernel for warmup..."); $loader = $input->getArgument('loader'); $path = stream_resolve_include_path($loader); if (!is_readable($path)) { throw new \InvalidArgumentException("Invalid loader path: {$loader}"); } include_once $path; if (!class_exists('Go\\Core\\AspectKernel', false)) { $message = "Kernel was not initialized yet, please configure it in the {$path}"; throw new \InvalidArgumentException($message); } $kernel = AspectKernel::getInstance(); $options = $kernel->getOptions(); if (empty($options['cacheDir'])) { throw new \InvalidArgumentException("Cache warmer require the `cacheDir` options to be configured"); } $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($options['appDir'], \FilesystemIterator::SKIP_DOTS)); /** @var \CallbackFilterIterator|\SplFileInfo[] $iterator */ $iterator = new \CallbackFilterIterator($iterator, $this->getFileFilter($options)); $totalFiles = iterator_count($iterator); $output->writeln("Total <info>{$totalFiles}</info> files to process."); $iterator->rewind(); set_error_handler(function ($errno, $errstr, $errfile, $errline) { throw new \ErrorException($errstr, $errno, 0, $errfile, $errline); }); $index = 0; $errors = array(); foreach ($iterator as $file) { if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln("Processing file <info>{$file->getRealPath()}</info>"); } $isSuccess = null; try { // This will trigger creation of cache file_get_contents(FilterInjectorTransformer::PHP_FILTER_READ . SourceTransformingLoader::FILTER_IDENTIFIER . "/resource=" . $file->getRealPath()); $isSuccess = true; } catch (\Exception $e) { $isSuccess = false; $errors[$file->getRealPath()] = $e; } if ($output->getVerbosity() == OutputInterface::VERBOSITY_NORMAL) { $output->write($isSuccess ? '.' : '<error>E</error>'); if (++$index % 50 == 0) { $output->writeln("({$index}/{$totalFiles})"); } } } restore_error_handler(); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { foreach ($errors as $file => $error) { $message = "File {$file} is not processed correctly due to exception: {$error->getMessage()}"; $output->writeln($message); } } $output->writeln("<info>Done</info>"); }
protected function execute(InputInterface $input, OutputInterface $output) { $bag = $this->container->get('childs_bag'); $builder = $this->container->get('builder'); $runner = $this->container->get('runner'); $childs = $input->getArgument('child'); $envs = $input->getOption('env'); $cascade = $input->getOption('cascade'); $async = $input->getOption('async'); $tmout = $input->getOption('tmout'); if (empty($childs)) { $childs = array_keys($bag->getAll()); } $args = $envs; $namedArgs = array_map(function ($env) { return '--env=' . $env; }, $envs); $namedArgs[] = '-n'; $namedArgs[] = '-c'; $namedArgs[] = sprintf('-t %s', $tmout); foreach ($childs as $child) { if ($bag->has($child)) { $child = $bag->get($child); $builder->setCommand('rollback:env')->setArguments($args)->setHost($child->getHost())->setPath($child->getPath()); if ($async) { $builder->setAsync(); } $cmd = $builder->getCommandLine(); if ($output->getVerbosity() > OutputInterface::VERBOSITY_QUIET) { $output->writeln(sprintf('<info>Attempt to rollback "<fg=cyan>%s</fg=cyan>"...</info>', $child->getName())); $output->writeln(sprintf('<info>Running "<fg=cyan>%s</fg=cyan>"...</info>', $cmd)); } $runner->setCommand($cmd)->setTimeout($tmout)->run(function ($type, $buffer) use($output) { if ($output->getVerbosity() === OutputInterface::VERBOSITY_QUIET) { return; } $output->write($buffer); }); if ($cascade) { $builder->setCommand('rollback')->setArguments($namedArgs)->setHost($child->getHost())->setPath($child->getPath()); if ($async) { $builder->setAsync(); } $cmd = $builder->getCommandLine(); if ($output->getVerbosity() > OutputInterface::VERBOSITY_QUIET) { $output->writeln(sprintf('<info>Running "<fg=cyan>%s</fg=cyan>"...</info>', $cmd)); } $runner->setCommand($cmd)->setTimeout($tmout)->run(function ($type, $buffer) use($output) { if ($output->getVerbosity() === OutputInterface::VERBOSITY_QUIET) { return; } $output->write($buffer); }); } } } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $drushCommand = $input->getArgument('cmd'); $sshOptions = ''; // Pass through options that the CLI shares with Drush and SSH. foreach (['yes', 'no', 'quiet'] as $option) { if ($input->getOption($option)) { $drushCommand .= " --{$option}"; } } if ($output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) { $drushCommand .= " --debug"; $sshOptions .= ' -vv'; } elseif ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $drushCommand .= " --verbose"; $sshOptions .= ' -v'; } elseif ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $drushCommand .= " --verbose"; } elseif ($output->getVerbosity() == OutputInterface::VERBOSITY_QUIET) { $drushCommand .= " --quiet"; $sshOptions .= ' -q'; } $appName = $this->selectApp($input, function (LocalApplication $app) { return Drupal::isDrupal($app->getRoot()); }); $selectedEnvironment = $this->getSelectedEnvironment(); $sshUrl = $selectedEnvironment->getSshUrl($appName); // Get the LocalApplication object for the specified application, if // available. $projectRoot = $this->getProjectRoot(); if ($projectRoot && $this->selectedProjectIsCurrent()) { $app = LocalApplication::getApplication($appName, $projectRoot, self::$config); } // Use the local application configuration (if available) to determine // the correct Drupal root. if (isset($app)) { $drupalRoot = '/app/' . $app->getDocumentRoot(); } else { // Fall back to the PLATFORM_DOCUMENT_ROOT environment variable, // which is usually correct, except where the document_root was // specified as '/'. $documentRootEnvVar = self::$config->get('service.env_prefix') . 'DOCUMENT_ROOT'; $drupalRoot = '${' . $documentRootEnvVar . ':-/app/public}'; $this->debug('<comment>Warning:</comment> using $' . $documentRootEnvVar . ' for the Drupal root. This fails in cases where the document_root is /.'); } $dimensions = $this->getApplication()->getTerminalDimensions(); $columns = $dimensions[0] ?: 80; $sshDrushCommand = "COLUMNS={$columns} drush --root=\"{$drupalRoot}\""; if ($environmentUrl = $selectedEnvironment->getLink('public-url')) { $sshDrushCommand .= " --uri=" . escapeshellarg($environmentUrl); } $sshDrushCommand .= ' ' . $drushCommand . ' 2>&1'; $command = 'ssh' . $sshOptions . ' ' . escapeshellarg($sshUrl) . ' ' . escapeshellarg($sshDrushCommand); return $this->getHelper('shell')->executeSimple($command); }