/** * Prepare a command to run in the repo's directory * * @param $command * @return \Symfony\Component\Process\Process */ public function cmd($command) { $process = new \Symfony\Component\Process\Process($command); $process->setWorkingDirectory($this->getPrjDir()); $process->setTimeout(self::TIMEOUT); return $process; }
/** * @param $commands * @param \Symfony\Component\Console\Output\ConsoleOutput $output * * @return boolean */ function execute_commands($commands, $output) { foreach ($commands as $command) { list($command, $message, $allowFailure) = $command; $output->write(sprintf(' - %\'.-70s', $message)); $return = array(); if (is_callable($command)) { $success = $command($output); } else { $p = new \Symfony\Component\Process\Process($command); $p->setTimeout(null); $p->run(function ($type, $data) use(&$return) { $return[] = $data; }); $success = $p->isSuccessful(); } if (!$success && !$allowFailure) { $output->writeln('<error>KO</error>'); $output->writeln(sprintf('<error>Fail to run: %s</error>', is_callable($command) ? '[closure]' : $command)); foreach ($return as $data) { $output->write($data, false, OutputInterface::OUTPUT_RAW); } $output->writeln("If the error is coming from the sandbox,"); $output->writeln("please report the issue to https://github.com/sonata-project/sandbox/issues"); return false; } else { if (!$success) { $output->writeln("<info>!!</info>"); } else { $output->writeln("<info>OK</info>"); } } } return true; }
public static function pack($data) { $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . __DIR__ . "/BrowserPack.js"; $process = new Symfony\Component\Process\Process($cmd); $process->setInput(json_encode($data)); $process->mustRun(); return $process->getOutput(); }
public static function setUpBeforeClass() { parent::setUpBeforeClass(); $tmpDir = __DIR__ . '/tmp'; if (defined('PHP_WINDOWS_VERSION_BUILD')) { $command = 'rmdir /q /s ' . escapeshellarg($tmpDir); } else { $command = 'rmdir -Rf ' . escapeshellarg($tmpDir); } $process = new \Symfony\Component\Process\Process($command); $process->run(); if (!is_dir($tmpDir)) { mkdir($tmpDir); } self::$tmpDir = $tmpDir . '/exiftool_reader'; if (!is_dir(self::$tmpDir)) { mkdir(self::$tmpDir); } file_put_contents(self::$tmpDir . '/hello.world', 'Hello'); file_put_contents(self::$tmpDir . '/hello.exiftool', 'Hello'); if (!is_dir(self::$tmpDir . '/dir')) { mkdir(self::$tmpDir . '/dir'); } if (!is_dir(self::$tmpDir . '/usr')) { mkdir(self::$tmpDir . '/usr'); } $tmpDir2 = $tmpDir . '/exiftool_reader2'; if (!is_dir($tmpDir2)) { mkdir($tmpDir2); } file_put_contents($tmpDir2 . '/hello2.world', 'Hello'); if (defined('PHP_WINDOWS_VERSION_BUILD')) { self::$disableSymLinkTest = true; } elseif (!is_link(self::$tmpDir . '/symlink')) { if (!@symlink($tmpDir2, self::$tmpDir . '/symlink')) { self::$disableSymLinkTest = true; } } file_put_contents(self::$tmpDir . '/dir/newfile.txt', 'Hello'); $tmpDir3 = $tmpDir . '/exiftool_reader3'; if (!is_dir($tmpDir3)) { mkdir($tmpDir3); } if (!is_dir($tmpDir3 . '/.svn')) { mkdir($tmpDir3 . '/.svn'); } if (!is_dir($tmpDir3 . '/.roro')) { mkdir($tmpDir3 . '/.roro'); } if (!is_dir($tmpDir3 . '/.git')) { mkdir($tmpDir3 . '/.git'); } touch($tmpDir3 . '/.git/config'); touch($tmpDir3 . '/.roro/.roro.tmp'); touch($tmpDir3 . '/.phrasea.xml'); }
public static function setUpBeforeClass() { parent::setUpBeforeClass(); $tmpDir = __DIR__ . '/tmp'; if (defined('PHP_WINDOWS_VERSION_BUILD')) { $command = 'rmdir /q /s ' . escapeshellarg($tmpDir); } else { $command = 'rmdir -Rf ' . escapeshellarg($tmpDir); } $process = new \Symfony\Component\Process\Process($command); $process->run(); if (!is_dir($tmpDir)) { mkdir($tmpDir); } self::$tmpDir = $tmpDir . '/exiftool_reader'; if (!is_dir(self::$tmpDir)) { mkdir(self::$tmpDir); } copy(__DIR__ . '/../../../files/ExifTool.jpg', self::$tmpDir . '/test2.jpg'); copy(__DIR__ . '/../../../files/ExifTool.jpg', self::$tmpDir . '/test.jpg'); if (!is_dir(self::$tmpDir . '/dir')) { mkdir(self::$tmpDir . '/dir'); } if (!is_dir(self::$tmpDir . '/usr')) { mkdir(self::$tmpDir . '/usr'); } $tmpDir2 = $tmpDir . '/exiftool_reader2'; if (!is_dir($tmpDir2)) { mkdir($tmpDir2); } copy(__DIR__ . '/../../../files/ExifTool.jpg', $tmpDir2 . '/test2.jpg'); if (defined('PHP_WINDOWS_VERSION_BUILD')) { self::$disableSymLinkTest = true; } elseif (!is_link(self::$tmpDir . '/symlink')) { if (!@symlink($tmpDir2, self::$tmpDir . '/symlink')) { self::$disableSymLinkTest = true; } } copy(__DIR__ . '/../../../files/plop/CanonRaw.cr2', self::$tmpDir . '/dir/CanonRaw.cr2'); $tmpDir3 = $tmpDir . '/exiftool_reader3'; if (!is_dir($tmpDir3)) { mkdir($tmpDir3); } if (!is_dir($tmpDir3 . '/.svn')) { mkdir($tmpDir3 . '/.svn'); } if (!is_dir($tmpDir3 . '/.roro')) { mkdir($tmpDir3 . '/.roro'); } if (!is_dir($tmpDir3 . '/.git')) { mkdir($tmpDir3 . '/.git'); } touch($tmpDir3 . '/.git/config'); touch($tmpDir3 . '/.roro/.roro.tmp'); copy(__DIR__ . '/../../../files/ExifTool.jpg', $tmpDir3 . '/.exiftool.jpg'); }
/** * @param $commands * @param \Symfony\Component\Console\Output\ConsoleOutput $output * @return void */ function execute_commands($commands, $output) { foreach ($commands as $command) { $output->writeln(sprintf('<info>Executing : </info> %s', $command)); $p = new \Symfony\Component\Process\Process($command); $exit = $p->run(function ($type, $data) use($output) { $output->write($data); }); $output->writeln(""); } }
public static function count($contents) { $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . KWF_PATH . "/Kwf/Assets/Util/CssSelectorCount.js"; $cmd .= " 2>&1"; $process = new Symfony\Component\Process\Process($cmd); $process->setEnv(array('NODE_PATH' => getcwd() . '/node_modules')); $process->setInput($contents); $process->mustRun(); $out = json_decode($process->getOutput(), true); return $out['selectors']; }
public static function parse($filename) { $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . __DIR__ . "/ModuleDepsParser.js " . $filename; $process = new Symfony\Component\Process\Process($cmd); $process->mustRun(); $out = json_decode($process->getOutput(), true); $ret = array('source' => $out[0]['source'], 'deps' => array()); foreach (array_keys($out[0]['deps']) as $i) { $ret['deps'][] = $i; } return $ret; }
protected function execute(InputInterface $input, OutputInterface $output) { if (!$input->getOption('command')) { $output->writeln("<error>Missing required option: --command</error>"); return 1; } $statusCode = 0; if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln("<info>[[ Finding repositories ]]</info>"); } $scanner = new \GitScan\GitRepoScanner(); $gitRepos = $scanner->scan($input->getArgument('path')); foreach ($gitRepos as $gitRepo) { /** @var \GitScan\GitRepo $gitRepo */ if (!$gitRepo->matchesStatus($input->getOption('status'))) { continue; } $topLevel = $this->fs->findFirstParent($gitRepo->getPath(), $input->getArgument('path')); if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln("<info>[[ {$gitRepo->getPath()} ]]</info>"); } $process = new \Symfony\Component\Process\Process($input->getOption('command')); $process->setWorkingDirectory($gitRepo->getPath()); // $process->setEnv(...); sucks in Debian/Ubuntu putenv("path=" . $this->fs->makePathRelative($gitRepo->getPath(), $topLevel)); putenv("toplevel=" . $topLevel); $errorOutput = $output; if (is_callable($output, 'getErrorOutput') && $output->getErrorOutput()) { $errorOutput = $output->getErrorOutput(); } $process->run(function ($type, $buffer) use($output, $errorOutput) { if (\Symfony\Component\Process\Process::ERR === $type) { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $errorOutput->write("<error>STDERR</error> "); } $errorOutput->write($buffer, FALSE, OutputInterface::OUTPUT_RAW); } else { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->write("<comment>STDOUT</comment> "); } $output->write($buffer, FALSE, OutputInterface::OUTPUT_RAW); } }); if (!$process->isSuccessful()) { $errorOutput->writeln("<error>[[ {$gitRepo->getPath()}: exit code = {$process->getExitCode()} ]]</error>"); $statusCode = 2; } } putenv("path"); putenv("toplevel"); return $statusCode; }
protected function execute(InputInterface $input, OutputInterface $output) { $dir = implode(DIRECTORY_SEPARATOR, [$this->getContainer()->get('kernel')->getRootDir(), '..', 'utils', 'dumpdb']); $command = implode(DIRECTORY_SEPARATOR, [$dir, 'dumpdb']); chdir($dir); $process = new \Symfony\Component\Process\Process($command); $process->mustRun(); if (!$process->isSuccessful()) { throw new ProcessFailedException($process); } $stderr = $process->getErrorOutput(); $stderr = trim($stderr); $stdout = $process->getOutput(); $result = implode("\n\n", [$stderr, $stdout]); $output->writeln($result); }
/** * @param $commands * @param \Symfony\Component\Console\Output\ConsoleOutput $output * * @return boolean */ function execute_commands($commands, $output) { foreach ($commands as $command) { $output->writeln(sprintf('<info>Executing : </info> %s', $command)); $p = new \Symfony\Component\Process\Process($command); $p->setTimeout(null); $p->run(function ($type, $data) use($output) { $output->write($data); }); if (!$p->isSuccessful()) { return false; } $output->writeln(""); } return true; }
/** * Runs task */ protected function _run() { $this->_Process = new TaskProcess($this->_task['command'] . $this->_argsToString($this->_task['arguments']), $this->_task['path']); $this->_Process->setTimeout($this->_task['timeout']); try { $this->_Process->start(function ($type, $buffer) { if ('err' === $type) { $this->_Shell->err($buffer); $this->_task['stderr'] .= $buffer; } else { $this->_Shell->out($buffer); $this->_task['stdout'] .= $buffer; } $this->_TaskServer->updated($this->_task); }); while ($this->_Process->isRunning()) { $this->_task['process_id'] = (int) $this->_Process->getPid(); $this->_TaskServer->updateStatistics($this->_task); $this->_Process->checkTimeout(); sleep(Configure::read('Task.checkInterval')); if ($this->_TaskServer->mustStop($this->_task['id'])) { $this->_Process->stop(Configure::read('Task.stopTimeout')); $this->_task['code'] = 143; $this->_task['code_string'] = TaskProcess::$exitCodes[143]; return $this->_stopped(true); } } $this->_task['code'] = $this->_Process->getExitCode(); $this->_task['code_string'] = $this->_Process->getExitCodeText(); } catch (Exception $Exception) { $this->_task['code'] = 134; $this->_task['code_string'] = $Exception->getMessage(); } $this->_stopped(false); }
public static function run($pluginsInitCode, Kwf_SourceMaps_SourceMap $sourcemap) { $js = "\n require('es6-promise').polyfill(); //required for older nodejs\n var postcss = require('postcss');\n var plugins = [];\n " . $pluginsInitCode . "\n var instance = postcss( plugins );\n var css = '';\n process.stdin.setEncoding('utf-8')\n process.stdin.on('data', function(buf) { css += buf.toString(); });\n process.stdin.on('end', function() {\n instance.process(css).then(function (result) {\n process.stdout.write(result.css);\n }).catch(function(e) {\n console.log(e);\n process.exit(1);\n });\n });\n process.stdin.resume();\n "; $runfile = tempnam("temp/", 'postcss'); file_put_contents($runfile, $js); putenv("NODE_PATH=" . getcwd() . "/node_modules" . PATH_SEPARATOR . getcwd() . "/" . KWF_PATH . PATH_SEPARATOR . getcwd() . "/"); $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . $runfile; $cmd .= " 2>&1"; $process = new Symfony\Component\Process\Process($cmd); $mapData = $sourcemap->getMapContentsData(false); $hasSourcemap = !!$mapData->mappings; if ($hasSourcemap) { $process->setInput($sourcemap->getFileContentsInlineMap(false)); } else { $process->setInput($sourcemap->getFileContents()); } if ($process->run() !== 0) { throw new Kwf_Exception("Process '{$cmd}' failed with " . $process->getExitCode() . "\n" . $process->getOutput()); } putenv("NODE_PATH="); unlink($runfile); $out = $process->getOutput(); if (Kwf_SourceMaps_SourceMap::hasInline($out)) { $ret = Kwf_SourceMaps_SourceMap::createFromInline($out); } else { $ret = Kwf_SourceMaps_SourceMap::createEmptyMap($out); $ret->setMimeType('text/css'); } $ret->setSources($sourcemap->getSources()); return $ret; }
public static function parse($filename) { if (substr($filename, 0, strlen(getcwd() . '/temp/')) == getcwd() . '/temp/') { $cacheId = md5_file($filename); } else { $cacheId = str_replace(array('/', '.', '-'), '_', $filename) . '__' . md5_file($filename); } $ret = self::_getCache()->load($cacheId); if ($ret === false) { $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . __DIR__ . "/Parser.js " . $filename; $process = new Symfony\Component\Process\Process($cmd); $process->mustRun(); $out = json_decode($process->getOutput(), true); $ret = array(); foreach (array_keys($out[0]['deps']) as $i) { $ret[] = $i; } self::_getCache()->save($ret, $cacheId); } return $ret; }
public function perform() { set_time_limit(0); $log = new DeploynautLogFile($this->args['logfile']); $projects = DNProject::get()->filter('Name', Convert::raw2sql($this->args['projectName'])); $project = $projects->first(); $path = $project->getLocalCVSPath(); $env = $this->args['env']; $log->write('Starting git fetch for project "' . $project->Name . '"'); // if an alternate user has been configured for clone, run the command as that user // @todo Gitonomy doesn't seem to have any way to prefix the command properly, if you // set 'sudo -u composer git' as the "command" parameter, it tries to run the whole // thing as a single command and fails $user = DNData::inst()->getGitUser(); if (!empty($user)) { $command = sprintf('cd %s && sudo -u %s git fetch -p origin +refs/heads/*:refs/heads/* --tags', $path, $user); $process = new \Symfony\Component\Process\Process($command); $process->setEnv($env); $process->setTimeout(3600); $process->run(); if (!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } } else { $repository = new Gitonomy\Git\Repository($path, array('environment_variables' => $env)); $repository->run('fetch', array('-p', 'origin', '+refs/heads/*:refs/heads/*', '--tags')); } $log->write('Git fetch is finished'); }
public function filter(Kwf_SourceMaps_SourceMap $sourcemap) { putenv("NODE_PATH=" . getcwd() . "/node_modules"); $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . __DIR__ . "/CssChunks.js"; $cmd .= " 2>&1"; $process = new Symfony\Component\Process\Process($cmd); $process->setInput($sourcemap->getFileContentsInlineMap(false)); $process->mustRun(); $out = $process->getOutput(); $out = explode("\n/* ***** NEXT CHUNK ***** */\n", $out); $ret = array(); foreach ($out as $chunk) { if (Kwf_SourceMaps_SourceMap::hasInline($chunk)) { $mapChunk = Kwf_SourceMaps_SourceMap::createFromInline($chunk); } else { $mapChunk = Kwf_SourceMaps_SourceMap::createEmptyMap($chunk); $mapChunk->setMimeType('text/css'); } $ret[] = $mapChunk; } return $ret; }
/** * 编译脚本(字符串格式), 返回编译后的命令数组 * @param $script */ public static function complie($script, $siteId) { $s = new \Symfony\Component\Process\Process('sdf'); $s->run(); $realScript = self::twigVar($script, $siteId); $commandList = self::commandInit(); $lines = explode("\n", $realScript); //去除空行 $scriptLines = array(); foreach ($lines as $line) { $line = trim($line); if (empty($line)) { continue; } $scriptLines[] = $line; } $startPattern = '/^@(after|before):(remote|local|handle)$/i'; $len = count($scriptLines); for ($psl = 0; $psl < $len;) { while ($psl < $len && $scriptLines[$psl][0] != '@') { $psl++; } if ($psl >= $len) { break; } if (preg_match($startPattern, $scriptLines[$psl], $matchs)) { $order = $matchs[1]; $position = $matchs[2]; $psl++; while ($psl < $len && $scriptLines[$psl][0] != '@') { $commandList[$order][$position][] = $scriptLines[$psl]; $psl++; } } else { throw new Exception('complie error at : ' . $scriptLines[$psl]); } } return $commandList; }
protected function execute(InputInterface $input, OutputInterface $output) { $cfg = $this->getServices()->get('blogCfg'); $workdir = $cfg->get('blog.workdir', getcwd() . '/workdir'); if (is_dir($workdir)) { throw new \RuntimeException("Blog already initialized"); } $repodir = $workdir; $repoUrl = $cfg->get('blog.repository'); if (!$repoUrl) { throw new \RuntimeException("Missing blog.repository configuration."); } $output->writeln(sprintf("Clonning repository %s into workdir ...", $repoUrl)); $cmd = sprintf("git clone %s %s", $repoUrl, $repodir); $proc = new \Symfony\Component\Process\Process($cmd); $proc->setTimeout(null); $proc->run(function ($type, $buffer) use($output) { $output->write('<comment>' . $buffer . '</comment>'); }); if (!$proc->isSuccessful()) { throw new \RuntimeException('Git process failed.'); } $output->writeln("<info>Blog is ready.</info>"); }
public function perform() { set_time_limit(0); $path = $this->args['path']; $repo = $this->args['repo']; $env = $this->args['env']; $logfile = DEPLOYNAUT_LOG_PATH . '/clonegitrepo.log'; $fh = fopen($logfile, 'a'); if (!$fh) { throw new RuntimeException(sprintf('Can\'t open file "%s" for logging.', $logfile)); } // if an alternate user has been configured for clone, run the command as that user $user = DNData::inst()->getGitUser(); if (file_exists($path)) { $command = array(); if (!empty($user)) { $command[] = sprintf('sudo -u %s', $user); } $command[] = sprintf('rm -rf %s', $path); fwrite($fh, sprintf('[%s] Cleaning up existing repository %s', date('Y-m-d H:i:s'), $path) . PHP_EOL); fwrite($fh, sprintf('[%s] Running command: %s', date('Y-m-d H:i:s'), implode(' ', $command)) . PHP_EOL); $process = new \Symfony\Component\Process\Process(implode(' ', $command)); $process->setEnv($env); $process->setTimeout(3600); $process->run(); if (!$process->isSuccessful()) { fwrite($fh, sprintf('[%s] Error cleaning up existing repository: %s', date('Y-m-d H:i:s'), $process->getErrorOutput()) . PHP_EOL); throw new RuntimeException($process->getErrorOutput()); } } fwrite($fh, sprintf('[%s] Cloning repository %s to %s', date('Y-m-d H:i:s'), $repo, $path) . PHP_EOL); echo "[-] CloneGitRepo starting" . PHP_EOL; $command = array(); if (!empty($user)) { $command[] = sprintf('sudo -u %s', $user); } $command[] = sprintf('git clone --bare -q %s %s', $repo, $path); fwrite($fh, sprintf('[%s] Running command: %s', date('Y-m-d H:i:s'), implode(' ', $command)) . PHP_EOL); $process = new \Symfony\Component\Process\Process(implode(' ', $command)); $process->setEnv($env); $process->setTimeout(3600); $process->run(); if (!$process->isSuccessful()) { fwrite($fh, sprintf('[%s] Error cloning repository %s to %s: %s', date('Y-m-d H:i:s'), $repo, $path, $process->getErrorOutput()) . PHP_EOL); throw new RuntimeException($process->getErrorOutput()); } fwrite($fh, sprintf('[%s] Successfully cloned repository %s to %s', date('Y-m-d H:i:s'), $repo, $path) . PHP_EOL); }
public function perform() { set_time_limit(0); $path = $this->args['path']; $repo = $this->args['repo']; $env = $this->args['env']; $logfile = DEPLOYNAUT_LOG_PATH . '/clonegitrepo.log'; $fh = fopen($logfile, 'a'); if (!$fh) { throw new RuntimeException('Can\'t open file "' . $logfile . '" for logging.'); } // if an alternate user has been configured for clone, run the command as that user $user = DNData::inst()->getGitUser(); if (file_exists($path)) { if ($user) { exec(sprintf('sudo -u %s rm -rf %s', $user, $path)); } else { exec(sprintf('rm -rf %s', $path)); } } fwrite($fh, '[' . date('Y-m-d H:i:s') . '] Cloning ' . $repo . ' to ' . $path . PHP_EOL); echo "[-] CloneGitRepo starting" . PHP_EOL; // using git clone straight via system call since doing it via the // Gitonomy\Git\Admin times out. Silly. if ($user) { $command = sprintf('sudo -u %s git clone --bare -q %s %s', $user, $repo, $path); } else { $command = sprintf('git clone --bare -q %s %s', $repo, $path); } fwrite($fh, '[' . date('Y-m-d H:i:s') . '] Running command: ' . $command . PHP_EOL); $process = new \Symfony\Component\Process\Process($command); $process->setEnv($env); $process->setTimeout(3600); $process->run(); if (!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } fwrite($fh, '[' . date('Y-m-d H:i:s') . '] Cloned ' . $repo . ' to ' . $path . PHP_EOL); }
/** * Execute commands on local machine. * @param string $command Command to run locally. * @param int $timeout (optional) Override process command timeout in seconds. * @return Result Output of command. * @throws \RuntimeException */ function runLocally($command, $timeout = 60) { $command = env()->parse($command); if (isVeryVerbose()) { writeln("<comment>Run locally</comment>: {$command}"); } $process = new Symfony\Component\Process\Process($command); $process->setTimeout($timeout); $process->run(function ($type, $buffer) { if (isDebug()) { if ('err' === $type) { write("<fg=red>></fg=red> {$buffer}"); } else { write("<fg=green>></fg=green> {$buffer}"); } } }); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } return new Result($process->getOutput()); }
/** * Run the queue fetching process. * @param string $command The command. * @param string $cwd The working directory. * @param integer $timeout The timeout. * @param array $env The environment to be passed. * @return void */ protected function runQueueFetching($command, $cwd = null, $timeout = null, array $env = []) { $process = new \Symfony\Component\Process\Process($command, isset($cwd) ? $cwd : getcwd(), $env, null, $timeout); $process->setTimeout($timeout); $process->setIdleTimeout(null); $process->run(); if ($process->isSuccessful()) { //TODO logging. $this->stdout($process->getOutput() . PHP_EOL); $this->stdout($process->getErrorOutput() . PHP_EOL); } else { //TODO logging. $this->stdout($process->getOutput() . PHP_EOL); $this->stdout($process->getErrorOutput() . PHP_EOL); } }
/** * Adds a web and login system-user. * * Both are in the <name>_grp group * * _web has writeaccess to the webroot and nothing else * _login has write-access to */ private function taskCreateSystemUserAndGroup() { // Create the web-user. $group_esc = escapeshellarg($this->virtualHostConfiguration['group']); $process = new \Symfony\Component\Process\Process('addgroup --force-badname ' . $group_esc); try { $process->mustRun(); } catch (ProcessFailedException $e) { $this->output->writeln('Could not create the group ' . $this->virtualHostConfiguration['group'] . ': ' . $e->getMessage()); throw $e; } $web_homedir_esc = escapeshellarg($this->virtualHostConfiguration['web_homedir']); $web_user_esc = escapeshellarg($this->virtualHostConfiguration['web_user']); $process = new \Symfony\Component\Process\Process('adduser --force-badname --no-create-home --home ' . $web_homedir_esc . ' --shell /bin/false --disabled-login --gecos \'\' --ingroup ' . $group_esc . ' ' . $web_user_esc); try { $process->mustRun(); } catch (ProcessFailedException $e) { $this->output->writeln('Unable to create user ' . $this->virtualHostConfiguration['web_user'] . ': ' . $e->getMessage()); throw $e; } // Create the login-user. $login_homedir_esc = escapeshellarg($this->virtualHostConfiguration['login_homedir']); $login_user_esc = escapeshellarg($this->virtualHostConfiguration['login_user']); $process = new \Symfony\Component\Process\Process('adduser --force-badname --no-create-home --home ' . $login_homedir_esc . ' --disabled-login --gecos \'\' --ingroup ' . $group_esc . ' ' . $login_user_esc); try { $process->mustRun(); } catch (ProcessFailedException $e) { $this->output->writeln('Unable to create user ' . $this->virtualHostConfiguration['login_user'] . ': ' . $e->getMessage()); throw $e; } }
protected function compileWithCommand($bin, $source, $target) { $sourceFilePath = trim(Director::getAbsFile($source)); $targetFilePath = trim(Director::getAbsFile($target)); $command = $bin . " " . escapeshellarg($sourceFilePath); $process = new \Symfony\Component\Process\Process($command); $process->run(); if ($process->isSuccessful()) { $css = $process->getOutput(); if (!file_exists(dirname($targetFilePath))) { mkdir(dirname($targetFilePath), null, true); } file_put_contents($targetFilePath, $css); $this->filesCacheAdd($source); $this->log[] = ["compiled {$source} to {$target}", 'info']; } else { $message = $process->getErrorOutput(); if ($process->getExitCode() != 1 || !$message) { $message = "\"{$command}\": non-zero exit code {$process->getExitCode()} '{$process->getExitCodeText()}'. (Output: '{$message}')"; } $this->log[] = ["failed to compile {$source} with {$bin}: {$message}", 'error']; SS_Log::log(new Exception($message), SS_Log::ERR); } }
/** * Execute commands in parallel. * * @param array $cmds list of commands to be executed. * @param string $cwd absolute path of working directory. * @return array list of processes. */ function cli_execute_parallel($cmds, $cwd = null) { require_once __DIR__ . "/../../vendor/autoload.php"; $processes = array(); // Create child process. foreach ($cmds as $name => $cmd) { $process = new Symfony\Component\Process\Process($cmd); $process->setWorkingDirectory($cwd); $process->setTimeout(null); $processes[$name] = $process; $processes[$name]->start(); // If error creating process then exit. if ($processes[$name]->getStatus() !== 'started') { echo "Error starting process: {$name}"; foreach ($processes[$name] as $process) { if ($process) { $process->signal(SIGKILL); } } exit(1); } } return $processes; }
/** * @url /git/git-pull * @method POST */ public function gitPull($redirectionOutput) { $dir = dirname(dirname(dirname(dirname(dirname(dirname(__DIR__)))))); $process = new \Symfony\Component\Process\Process('git pull', $dir); $process->setTimeout(60); $process->run(); $redirectOutput->setLocationToRoute(get_class() . '::gitPanel'); }
/** * Executes the given command via shell and returns the complete output as * a string * * @param string $command * * @return array(status, stdout, stderr) */ protected function executeCommand($command) { if (class_exists('Symfony\\Component\\Process\\Process')) { $process = new \Symfony\Component\Process\Process($command, $this->env); if ($this->timeout !== false) { $process->setTimeout($this->timeout); } } else { $process = new Process($command, $this->env); } $process->run(); return array($process->getExitCode(), $process->getOutput(), $process->getErrorOutput()); }
$data = json_decode($payload, true); $payloadHash = hash_hmac($algo, $payload, $secret); if ($hash === $payloadHash) { $request->attributes->set('payload', $data); } else { return new Response('Payload hash does not match hub signature.', Response::HTTP_FORBIDDEN); } } }, Silex\Application::EARLY_EVENT); // Auto update deployer.phar on GitHub WebHook. $controller->post('update/deployer', function (Request $request) use($app) { $event = $request->headers->get('X-Github-Event'); $payload = $request->attributes->get('payload'); if ($event === 'create' && $payload['ref_type'] === 'tag') { file_put_contents($app['schedule'], "update:deployer\n", FILE_APPEND); return new Response('Schedule task to update deployer created.', Response::HTTP_OK, ['Content-Type' => 'text/plain']); } return new Response('', Response::HTTP_FORBIDDEN, ['Content-Type' => 'text/plain']); }); // Auto update docs on GitHub WebHook. $controller->post('update/{what}', function (Request $request, $what) use($app) { $event = $request->headers->get('X-Github-Event'); $payload = $request->attributes->get('payload'); if ($event === 'pull_request' && $payload['action'] === 'closed' && $payload['pull_request']['merged'] || $event === 'push') { $process = new \Symfony\Component\Process\Process('php ' . $app['cli'] . ' update:' . $what); $process->run(); return new Response("Update `{$what}` successfully.\n\n" . $process->getOutput(), Response::HTTP_OK, ['Content-Type' => 'text/plain']); } return new Response("The `{$what}` was not updated.", Response::HTTP_OK, ['Content-Type' => 'text/plain']); })->assert('what', '(documentation)|(recipes)'); return $controller;
#!/usr/bin/php <?php $config = ['git_urls' => ['https://github.com/symfony/Process.git' => 'sf_process/'], 'autoload_config' => ['sf_process/' => 'Symfony\\Component\\Process'], 'example' => function () { $process = new Symfony\Component\Process\Process('ls -lsa'); $process->setTimeout(5); $process->run(); print $process->getOutput(); }]; if ($return_config) { return $config; } require_once __DIR__ . '/_yf_autoloader.php'; new yf_autoloader($config);
/** * @TODO build this from the yaml file on the fly */ $yml = new Symfony\Component\Yaml\Yaml(); $tests = $yml->parse(__DIR__ . '/../behat.yml'); $run = []; $env = getenv('APP_ENV'); foreach ($tests as $key => $test) { if (strpos($key, $env) !== false) { $run[] = $key; } } $failing_test = []; foreach ($run as $test) { $command = "bin/behat --stop-on-failure --no-paths --tags='@api,~@wip' --profile={$test}"; $run = new \Symfony\Component\Process\Process($command); $run->setTimeout(600); $run->run(function ($type, $buffer) use($failing_test, $test) { if (Symfony\Component\Process\Process::ERR === $type) { $failing_test[] = $test; //throw new \Exception(sprintf("Test Failed %s", $buffer)); } else { echo $buffer; } }); if ($run->getExitCode() != 0) { $failing_test[] = $test; } } if (count($failing_test)) { $message = print_r($failing_test, 1);