Returns the exit code returned by the process.
public getExitCode ( ) : null | integer | ||
return | null | integer | The exit status code, null if the Process is not terminated |
/** * {@inheritdoc} */ public function check() { if (!$this->isSuccessful()) { // on some systems stderr is used, but on others, it's not throw new LintingException($this->process->getErrorOutput() ?: $this->process->getOutput(), $this->process->getExitCode()); } }
/** * @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; }
/** * Validate that a run process was successful. * * @throws \RuntimeException * @return void */ protected function validateRun() { $status = $this->process->getExitCode(); $error = $this->process->getErrorOutput(); if ($status !== 0 and $error !== '') { throw new \RuntimeException(sprintf("The exit status code %s says something went wrong:\n stderr: %s\n stdout: %s\ncommand: %s.", $status, $error, $this->process->getOutput(), $this->command)); } }
/** * @When I run the tenanted command :command * @When I run the tenanted command :command with options :options * @param $command * @param $options */ public function iRunTheCommand($command, $options = null) { $this->actualCommand = $command; $tenantedCommand = 'bin/tenant ' . $options . ' ' . PHP_BINARY . ' test/Vivait/TenantBundle/app/console --no-ansi ' . $command; $this->process = new Process($tenantedCommand); $this->process->run(); PHPUnit_Framework_Assert::assertSame(0, $this->process->getExitCode(), 'Non zero return code received from command'); }
/** * @param Process $composer * @param int|null $error */ protected function assertExitCodeError(Process $composer, $error = null) { if ($error !== null) { $this->assertEquals($error, $composer->getExitCode(), 'Expected ' . $error . ' error code'); } else { $this->assertNotEquals(0, $composer->getExitCode(), 'Expected not success error code'); } }
function getStatus() { if ($this->process->isRunning()) { return TestInterface::STATUS_RUNNING; } elseif ($this->process->getExitCode() > 0) { return TestInterface::STATUS_FAIL; } else { return TestInterface::STATUS_OK; } }
protected function handleProcessResult(Process $process) { $this->processObjectList[] = $process; if ($process->getExitCode() !== 0) { $message = $messageEnd = 'process for <code>' . $process->getCommandLine() . '</code> exited with ' . $process->getExitCode() . ': ' . $process->getExitCodeText(); $message .= PHP_EOL . 'Error Message:' . PHP_EOL . $process->getErrorOutput(); $message .= PHP_EOL . 'Output:' . PHP_EOL . $process->getOutput(); $message .= PHP_EOL . $messageEnd; throw new \Exception($message, $process->getExitCode()); } }
public function exec($cmd) { $preparedCmd = $this->prepareCommand($cmd); if ($this->logger) { $this->logger->debug('preparedCmd: ' . $preparedCmd); } $process = new Process($preparedCmd, null, null, null, $this->timeout); $process->run(); $this->lastOutput = $process->getOutput(); $this->lastError = $process->getErrorOutput(); $process->getExitCode(); return $process->getExitCode(); }
/** * @param string $commandline * @param bool $allowFailure * @param string $cwd * @throws \RuntimeException * @return int|null */ public function execute($commandline, $cwd = null, $allowFailure = false) { $process = new Process($commandline, $cwd); $process->setTimeout(self::DEFAULT_TIMEOUT); $output = $this->output; // tmp var needed for php < 5.4 $process->run(function ($type, $buffer) use($output) { $output->write($buffer); }); if (!$allowFailure && !$process->isSuccessful()) { throw new \RuntimeException("Command failed. Error Output:\n\n" . $process->getErrorOutput(), $process->getExitCode()); } return $process->getExitCode(); }
/** * Run the given command. * * @param string $command * @param callable $onError * @return string */ function runCommand($command, callable $onError = null) { $onError = $onError ?: function () { }; $process = new Process($command); $processOutput = ''; $process->setTimeout(null)->run(function ($type, $line) use(&$processOutput) { $processOutput .= $line; }); if ($process->getExitCode() > 0) { $onError($process->getExitCode(), $processOutput); } return $processOutput; }
public function prepareView(\Nethgui\View\ViewInterface $view) { parent::prepareView($view); if (!isset($this->process)) { return; } if ($this->getRequest()->isMutation()) { if ($this->process->getExitCode() === 0) { $view->getCommandList()->shutdown($view->getModuleUrl() . '?wait=0', $this->parameters['Action'], array($view->translate('shutdown_' . $this->parameters['Action']), $view->translate('test'))); } else { $view->getCommandList('/Notification')->showMessage("error " . $this->process->getOutput(), \Nethgui\Module\Notification\AbstractNotification::NOTIFY_ERROR); } } }
/** * runs a process on the commandline * * @param string $command the command to execute * @param mixed $output the output will be written into this var if passed by ref * if a callable is passed it will be used as output handler * @param string $cwd the working directory * @return int statuscode */ public function execute($command, &$output = null, $cwd = null) { if ($this->io && $this->io->isDebug()) { $safeCommand = preg_replace_callback('{://(?P<user>[^:/\\s]+):(?P<password>[^@\\s/]+)@}i', function ($m) { if (preg_match('{^[a-f0-9]{12,}$}', $m['user'])) { return '://***:***@'; } return '://' . $m['user'] . ':***@'; }, $command); $this->io->writeError('Executing command (' . ($cwd ?: 'CWD') . '): ' . $safeCommand); } // make sure that null translate to the proper directory in case the dir is a symlink // and we call a git command, because msysgit does not handle symlinks properly if (null === $cwd && Platform::isWindows() && false !== strpos($command, 'git') && getcwd()) { $cwd = realpath(getcwd()); } $this->captureOutput = count(func_get_args()) > 1; $this->errorOutput = null; $process = new Process($command, $cwd, null, null, static::getTimeout()); $callback = is_callable($output) ? $output : array($this, 'outputHandler'); $process->run($callback); if ($this->captureOutput && !is_callable($output)) { $output = $process->getOutput(); } $this->errorOutput = $process->getErrorOutput(); return $process->getExitCode(); }
/** * {@inheritdoc} */ public function run() { $this->printAction(); $this->process = new Process($this->getCommand()); $this->process->setTimeout($this->timeout); $this->process->setIdleTimeout($this->idleTimeout); $this->process->setWorkingDirectory($this->workingDirectory); if (isset($this->env)) { $this->process->setEnv($this->env); } if (!$this->background and !$this->isPrinted) { $this->startTimer(); $this->process->run(); $this->stopTimer(); return new Result($this, $this->process->getExitCode(), $this->process->getOutput(), ['time' => $this->getExecutionTime()]); } if (!$this->background and $this->isPrinted) { $this->startTimer(); $this->process->run(function ($type, $buffer) { $progressWasVisible = $this->hideTaskProgress(); print $buffer; $this->showTaskProgress($progressWasVisible); }); $this->stopTimer(); return new Result($this, $this->process->getExitCode(), $this->process->getOutput(), ['time' => $this->getExecutionTime()]); } try { $this->process->start(); } catch (\Exception $e) { return Result::fromException($this, $e); } return Result::success($this); }
/** * @group console */ public function testSleeperCommand() { // init $sleeperCommand = new SleeperCommand(); $sleeperCommandLockFilePath = sprintf('%s/lock_command_%s', $this->getClient()->getKernel()->getCacheDir(), str_replace(':', '_', $sleeperCommand->getName())); $commandline = sprintf('env bin/console --env=%s %s', $this->getClient()->getKernel()->getEnvironment(), $sleeperCommand->getName()); // the first run of this command with the locking mechanism: the lock is created $firstProcess = new Process($commandline); $firstProcess->start(); sleep(SleeperCommand::SLEEPING_TIME / 2); // the second run of this command is invalid $secondProcess = new Process($commandline); $secondProcess->run(); $this->assertSame(2, $secondProcess->getExitCode(), 'Invalid exit code'); $secondProcessOutput = $secondProcess->getOutput(); $this->assertSame(2, substr_count($secondProcessOutput, PHP_EOL), 'There is more than two lines'); $this->assertContains('locking is activated', $secondProcessOutput, 'Incorrect line 1'); $this->assertContains('will not be started', $secondProcessOutput, 'Incorrect line 2'); // check the first process is still running $this->assertTrue($firstProcess->isRunning(), sprintf('The command %s does not work', $firstProcess->getCommandLine())); // after the sleeping, the lock is released sleep(1 + SleeperCommand::SLEEPING_TIME / 2); $this->assertSame(0, $firstProcess->getExitCode()); $firstProcessOutput = $firstProcess->getOutput(); $this->assertSame(3, substr_count($firstProcessOutput, PHP_EOL), 'There is more than three lines'); $this->assertContains('starting', $firstProcessOutput); $this->assertContains('processing', $firstProcessOutput); $this->assertContains('ending', $firstProcessOutput); // the third run of this command, after the sleeping, is valid $thirdProcess = new Process($commandline); $thirdProcess->run(); $this->assertSame(0, $thirdProcess->getExitCode()); }
/** * Check if the given database already exists * * @param \ClickRain\Breeze\Model\Database $database * @return boolean */ public function databaseExists(Database $database) { $script = sprintf('mysql --user="******" --password="******" -e "use %s"', $database->local_name); $process = new Process($script); $process->run(); return !$process->getExitCode(); }
/** * @Given I have started describing the :class class */ public function iHaveStartedDescribingTheClass($class) { $command = sprintf('%s %s %s', $this->buildPhpSpecCmd(), 'describe', escapeshellarg($class)); $process = new Process($command); $process->run(); expect($process->getExitCode())->toBe(0); }
/** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { // Check if vagrant is available if (!$this->isVagrantInstalled()) { $output->writeln('<error>Couldn\'t find `vagrant` in PATH. Are you sure Vagrant is installed?</error>'); return 1; } // load .env $this->getDotenv(getcwd())->load(); // run vagrant putenv("WP_HOME={$this->getWordPressHome()}"); putenv("VAGRANT_HOSTNAME={$this->getHostname()}"); $vagrant = new Process('vagrant up', null, null, null, null); $vagrant->run(function ($type, $buffer) use($output) { if (Process::ERR === $type) { $buffer = "<error>{$buffer}</error>"; } return $output->write($buffer, false, OutputInterface::VERBOSITY_VERBOSE); }); // vagrant failed if (!$vagrant->isSuccessful()) { return $vagrant->getExitCode(); } // start browser $browser = new Process($this->getBrowserCommand($this->getWordPressHome())); $browser->run(); return 0; }
/** * @param $command * @param $silent * @param \Closure $callback * @param $env * @return bool|string * @throws \Kunstmaan\Skylab\Exceptions\SkylabException */ private function performCommand($command, $silent = false, \Closure $callback = null, $env = array()) { $startTime = microtime(true); if (!$silent) { $this->dialogProvider->logCommand($command); } $env = array_replace($_ENV, $_SERVER, $env); $process = new Process($command, null, $env); $process->setTimeout(3600); $process->run($callback); if (!$silent) { $this->dialogProvider->logCommandTime($startTime); } if (!$process->isSuccessful()) { if ($process->getExitCode() == 23) { return $process->getOutput(); } else { if (!$silent) { $this->dialogProvider->logError($process->getErrorOutput()); } return false; } } return $process->getOutput(); }
/** * Check if linting process was successful and raise LintingException if not. * * @param Process $process */ private function checkProcess(Process $process) { if (!$process->isSuccessful()) { // on some systems stderr is used, but on others, it's not throw new LintingException($process->getErrorOutput() ?: $process->getOutput(), $process->getExitCode()); } }
/** * Assert not the exit status * * @param int $expected */ public function assertNotExitStatus($expected) { $actual = $this->process->getExitCode(); if ($actual === $expected) { throw new ExpectationException("{$actual} matched unexpected {$expected}"); } }
/** * Checkout the given branch. * * @param string $branch * @return void */ public function checkoutNew($branch) { with($process = new Process('git checkout -b ' . $branch, getcwd()))->run(); if ($process->getExitCode() > 0) { throw new \Exception($process->getErrorOutput()); } }
public function run() { $command = $this->getCommand(); $dir = $this->workingDirectory ? " in " . $this->workingDirectory : ""; $this->printTaskInfo("running <info>{$command}</info>{$dir}"); $this->process = new Process($command); $this->process->setTimeout($this->timeout); $this->process->setIdleTimeout($this->idleTimeout); $this->process->setWorkingDirectory($this->workingDirectory); if (!$this->background and !$this->isPrinted) { $this->process->run(); return new Result($this, $this->process->getExitCode(), $this->process->getOutput()); } if (!$this->background and $this->isPrinted) { $this->process->run(function ($type, $buffer) { Process::ERR === $type ? print 'ER» ' . $buffer : (print '» ' . $buffer); }); return new Result($this, $this->process->getExitCode(), $this->process->getOutput()); } try { $this->process->start(); } catch (\Exception $e) { return Result::error($this, $e->getMessage()); } return Result::success($this); }
/** * Generates a DIFF. * * @param string $before * @param string $after * @return string */ public static function generate($before, $after) { if ($before === $after) { return ''; } $beforeTmpFile = tempnam(sys_get_temp_dir(), 'diff'); file_put_contents($beforeTmpFile, $before); $afterTmpFile = tempnam(sys_get_temp_dir(), 'diff'); file_put_contents($afterTmpFile, $after); $proc = new Process('git diff --no-index --exit-code -- ' . escapeshellarg($beforeTmpFile) . ' ' . escapeshellarg($afterTmpFile)); $proc->run(); @unlink($beforeTmpFile); @unlink($afterTmpFile); switch ($proc->getExitCode()) { // $before and $after were deemed identical. Should normally never // be reached as we already check for this above. case 0: return ''; // The first four lines contain information about the files which were being compared. // We can savely trim them as we only generate the diff for one file. // The first four lines contain information about the files which were being compared. // We can savely trim them as we only generate the diff for one file. case 1: $output = explode("\n", $proc->getOutput()); return implode("\n", array_slice($output, 4)); default: throw new ProcessFailedException($proc); } }
public function run() { $command = $this->getCommand(); $dir = $this->workingDirectory ? " in " . $this->workingDirectory : ""; $this->printTaskInfo("Running <info>{$command}</info>{$dir}"); $this->process = new Process($command); $this->process->setTimeout($this->timeout); $this->process->setIdleTimeout($this->idleTimeout); $this->process->setWorkingDirectory($this->workingDirectory); if (isset($this->env)) { $this->process->setEnv($this->env); } if (!$this->background and !$this->isPrinted) { $this->startTimer(); $this->process->run(); $this->stopTimer(); return new Result($this, $this->process->getExitCode(), $this->process->getOutput(), ['time' => $this->getExecutionTime()]); } if (!$this->background and $this->isPrinted) { $this->startTimer(); $this->process->run(function ($type, $buffer) { print $buffer; }); $this->stopTimer(); return new Result($this, $this->process->getExitCode(), $this->process->getOutput(), ['time' => $this->getExecutionTime()]); } try { $this->process->start(); } catch (\Exception $e) { return Result::error($this, $e->getMessage()); } return Result::success($this); }
/** * @return SystemData Process output. */ public function execute() { $process = new Process($this->command); isset($this->input) && $process->setInput($this->input); $process->run(); return new SystemData($process->getOutput(), $process->getErrorOutput(), $process->getExitCode()); }
/** * @param InputInterface $input * @param OutputInterface $output * @return int * @throws \Exception */ protected function execute(InputInterface $input, OutputInterface $output) { $maxJobs = $input->getOption('max-jobs'); $maxTimeouts = $input->getOption('max-timeouts'); $workerId = $input->getOption('worker'); if (is_null($workerId)) { throw new \InvalidArgumentException(sprintf('Queue name is not specified')); } $debugMode = $this->getContainer()->getParameter('kernel.debug'); $environment = $this->getContainer()->getParameter('kernel.environment'); $phpExecFinder = new PhpExecutableFinder(); $phpExecutablePath = $phpExecFinder->find(); $consoleRelativePath = $_SERVER['SCRIPT_FILENAME']; /** @var AbstractWorker $worker */ $worker = $this->getContainer()->get(TFoxBeanstalkdBundle::DI_WORKER_PREFIX . $workerId); $jobsExecuted = 0; $timeouts = 0; while (!($this->maxJobsExecuted($jobsExecuted, $maxJobs) || $this->maxTimeoutsReached($timeouts, $maxTimeouts))) { /** @var Job $job */ $job = $worker->listen(); if ($job instanceof Job) { $worker->bury($job); $commandLine = sprintf('%s %s %s --worker=%s --job=%s --env=%s%s', $phpExecutablePath, $consoleRelativePath, WorkerRunChildCommand::COMMAND_NAME, $workerId, $job->getId(), $environment, $debugMode ? '' : ' --no-debug'); $this->logger->debug('Running a child process'); $process = new Process($commandLine); $process->setWorkingDirectory(getcwd()); $process->run(); $this->logger->debug('Executed a job'); $this->logger->debug("Job STDOUT: " . $process->getOutput()); try { if (TFoxBeanstalkdBundle::COMMAND_EXIT_CODE_SUCCESS != $process->getExitCode()) { $this->logger->error("Job failed. STDERR: " . $process->getErrorOutput()); if (TFoxBeanstalkdBundle::COMMAND_EXIT_CODE_ABORT != $process->getExitCode()) { $worker->handleProcessError($process, $job); } } } catch (\Exception $e) { $this->logger->critical(sprintf('An exception thrown: %s', $e->getMessage())); } $worker->getConnection()->delete($job); $jobsExecuted++; } else { $this->logger->debug('Timeout is reached'); $timeouts++; } } }
/** * @return bool returns true if command was successfully executed */ public function isSuccess() { if (isset($this->process)) { return $this->process->getExitCode() === 0; } else { return false; } }
protected function assertExitCode($expected, Process $process) { $exitCode = $process->getExitCode(); if ($exitCode !== $expected) { $this->fail(sprintf('Expected exit code "%s" but got "%s": STDOUT: %s ERR: %s', $expected, $exitCode, $process->getOutput(), $process->getErrorOutput())); } $this->assertEquals($expected, $exitCode); }
public function __construct(Process $process) { if ($process->isSuccessful()) { throw new InvalidArgumentException('Expected a failed process, but the given process was successful.'); } parent::__construct(sprintf('The command "%s" failed.' . "\nExit Code: %s(%s)\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s", $process->getCommandLine(), $process->getExitCode(), $process->getExitCodeText(), $process->getOutput(), $process->getErrorOutput())); $this->process = $process; }
protected function ensureKeyExists($storage_path) { if (!file_exists($storage_path)) { $cmd = sprintf('ssh-keygen -b 2048 -t rsa -f %s -q -N ""', escapeshellarg($storage_path)); $process = new Process($cmd); $process->setTimeout(5000); $process->run(); if ($process->getExitCode() !== 0) { $text = 'Exit code: ' . $process->getExitCode(); $text .= ' while executing: "' . $cmd; $text .= '" with reason: ' . $process->getErrorOutput(); $text .= "\n" . $process->getOutput(); throw new \RuntimeException($text); } } return $storage_path; }