setEnv() public method

An environment variable value should be a string. If it is an array, the variable is ignored. That happens in PHP when 'argv' is registered into the $_ENV array for instance.
public setEnv ( array $env ) : self
$env array The new environment variables
return self The current Process instance
示例#1
0
文件: Exec.php 项目: jjok/Robo
 /**
  * {@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);
 }
示例#2
0
 function render($context = null, $vars = array())
 {
     $options = $this->options;
     $compress = @$options["compress"] ?: false;
     $outputFile = tempnam(sys_get_temp_dir(), 'metatemplate_template_less_output');
     $finder = new ExecutableFinder();
     $bin = @$this->options["less_bin"] ?: self::DEFAULT_LESSC;
     $cmd = $finder->find($bin);
     if ($cmd === null) {
         throw new \UnexpectedValueException("'{$bin}' executable was not found. Make sure it's installed.");
     }
     if ($compress) {
         $cmd .= ' -x';
     }
     if (array_key_exists('include_path', $this->options)) {
         $cmd .= sprintf('--include-path %s', escapeshellarg(join(PATH_SEPARATOR, (array) $this->options['include_path'])));
     }
     $cmd .= " --no-color - {$outputFile}";
     $process = new Process($cmd);
     $process->setStdin($this->getData());
     if ($this->isFile()) {
         $process->setWorkingDirectory(dirname($this->source));
     }
     $process->setEnv(array('PATH' => getenv("PATH")));
     $process->run();
     $content = @file_get_contents($outputFile);
     @unlink($outputFile);
     if (!$process->isSuccessful()) {
         throw new \RuntimeException("{$cmd} returned an error: " . $process->getErrorOutput());
     }
     return $content;
 }
示例#3
0
 function render($context = null, $vars = array())
 {
     $finder = new ExecutableFinder();
     $bin = @$this->options["tsc_bin"] ?: self::DEFAULT_TSC;
     $cmd = $finder->find($bin);
     if ($cmd === null) {
         throw new \UnexpectedValueException("'{$bin}' executable was not found. Make sure it's installed.");
     }
     $inputFile = sys_get_temp_dir() . '/pipe_typescript_input_' . uniqid() . '.ts';
     file_put_contents($inputFile, $this->getData());
     $outputFile = tempnam(sys_get_temp_dir(), 'pipe_typescript_output_') . '.js';
     $cmd .= " --out " . escapeshellarg($outputFile) . ' ' . escapeshellarg($inputFile);
     $process = new Process($cmd);
     $process->setEnv(array('PATH' => @$_SERVER['PATH'] ?: join(PATH_SEPARATOR, array("/bin", "/sbin", "/usr/bin", "/usr/local/bin", "/usr/local/share/npm/bin"))));
     if ($this->isFile()) {
         $process->setWorkingDirectory(dirname($this->source));
     }
     $process->run();
     unlink($inputFile);
     if ($process->getErrorOutput()) {
         throw new \RuntimeException("tsc({$this->source}) returned an error:\n {$process->getErrorOutput()}");
     }
     $data = file_get_contents($outputFile);
     unlink($outputFile);
     return $data;
 }
示例#4
0
文件: Exec.php 项目: stefanhuber/Robo
 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);
 }
示例#5
0
文件: Util.php 项目: laradic/support
 public static function shell($commands, array $opts = [])
 {
     //$cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array()
     if (is_array($commands)) {
         $procs = [];
         foreach ($commands as $command) {
             $procs[] = static::shell($command, $opts);
         }
         return $procs;
     }
     $process = new Process($commands);
     $options = array_replace(['type' => 'sync', 'cwd' => null, 'env' => null, 'timeout' => 60, 'callback' => null, 'output' => true], $opts);
     $options['cwd'] !== null && $process->setWorkingDirectory($options['cwd']);
     $options['env'] !== null && $process->setEnv($options['env']);
     is_int($options['timeout']) && $process->setTimeout($options['timeout']);
     if ($options['output'] === true) {
         $process->enableOutput();
     } else {
         $process->disableOutput();
     }
     $type = $options['type'];
     if ($type === 'sync') {
         $process->run($options['callback']);
     } elseif ($type === 'async') {
         $process->start();
     }
     return $process;
 }
 /**
  * @When I run phpspec and answer :answer when asked if I want to generate the code
  */
 public function iRunPhpspecAndAnswerWhenAskedIfIWantToGenerateTheCode($answer)
 {
     $command = sprintf('%s %s', $this->buildPhpSpecCmd(), 'run');
     $env = array('SHELL_INTERACTIVE' => true, 'HOME' => $_SERVER['HOME']);
     $this->process = $process = new Process($command);
     $process->setEnv($env);
     $process->setInput($answer);
     $process->run();
 }
 /**
  * @Given :class exists
  */
 public function exists($class)
 {
     $descCmd = $this->buildCmd(sprintf('desc %s', $class));
     $runCmd = $this->buildCmd('run');
     $cmd = sprintf('%s && %s', $descCmd, $runCmd);
     $process = new Process($cmd);
     $process->setEnv(['SHELL_INTERACTIVE' => true]);
     $process->setInput('Y');
     $process->run();
     if (!$process->isSuccessful()) {
         throw new \RuntimeException($process->getErrorOutput());
     }
 }
 /**
  * @When I run the spec for :fqcn
  */
 public function iRunTheSpecFor($fqcn)
 {
     $cmd = $this->buildCmd(sprintf('run %s', $fqcn));
     $cmd .= ' --format pretty';
     $process = new Process($cmd);
     $process->setEnv(['SHELL_INTERACTIVE' => true]);
     $process->setInput('Y');
     $process->run();
     $this->lastOutput = $process->getOutput();
     if (!$process->isSuccessful()) {
         throw new \RuntimeException($process->getErrorOutput());
     }
 }
示例#9
0
 /**
  * Run a command in the shell.
  *
  * @param $command
  * @param int   $timeoutInSeconds
  * @param array $env
  *
  * @return bool|string
  */
 public function run($command, $timeoutInSeconds = 60, array $env = null)
 {
     $process = new Process($command);
     $process->setTimeout($timeoutInSeconds);
     if ($env != null) {
         $process->setEnv($env);
     }
     $process->run();
     if ($process->isSuccessful()) {
         return true;
     } else {
         return $process->getErrorOutput();
     }
 }
 /**
  * Runs behat command with provided parameters
  *
  * @When /^I run "behat(?: ((?:\"|[^"])*))?"$/
  *
  * @param   string $argumentsString
  */
 public function iRunBehat($argumentsString = '')
 {
     $argumentsString = strtr($argumentsString, array('\'' => '"'));
     $this->process->setWorkingDirectory($this->workingDir);
     $this->process->setCommandLine(sprintf('%s %s %s %s', $this->phpBin, escapeshellarg(BEHAT_BIN_PATH), $argumentsString, strtr('--format-settings=\'{"timer": false}\'', array('\'' => '"', '"' => '\\"'))));
     // Don't reset the LANG variable on HHVM, because it breaks HHVM itself
     if (!defined('HHVM_VERSION')) {
         $env = $this->process->getEnv();
         $env['LANG'] = 'en';
         // Ensures that the default language is en, whatever the OS locale is.
         $this->process->setEnv($env);
     }
     $this->process->start();
     $this->process->wait();
 }
示例#11
0
 /**
  * @param string          $command
  * @param array           $arguments
  * @param array           $env
  * @param LoggerInterface $logger
  *
  * @return Process
  */
 public static function exec($command, array $arguments, array $env = [], LoggerInterface $logger = null)
 {
     $process = new BaseProcess(strtr($command, $arguments));
     if ($logger) {
         $logger->debug('Executing ' . $process->getCommandLine());
     }
     try {
         $process->setEnv($env)->setTimeout(null)->mustRun();
     } catch (ProcessFailedException $exception) {
         if ($logger) {
             $logger->error($exception->getMessage());
         }
         throw $exception;
     }
     return $process;
 }
示例#12
0
 /**
  * Executes an SVN command.
  *
  * @param array|string $command
  * @param bool         $ssh
  *
  * @return [bool, string]
  */
 public function execute($command, $ssh = false)
 {
     if (is_array($command)) {
         $command = implode(' ', $command);
     }
     $output = '';
     with($process = new Process($this->binary() . ' ' . $command))->setWorkingDirectory($this->location)->setTimeout(null)->setIdleTimeout(null);
     if ($ssh) {
         $process->setEnv(['SVN_SSH' => env('SSH_KEY_PATH')]);
     }
     $process->run(function ($t, $buffer) use(&$output) {
         $output .= $buffer;
     });
     $response = [$successful = $process->isSuccessful(), $output];
     return $response;
 }
示例#13
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var string $webRoot */
     $webRoot = $this->getContainer()->getParameter('oro_require_js.web_root');
     /** @var array $config */
     $config = $this->getContainer()->getParameter('oro_require_js');
     /** @var RequireJSConfigProvider $configProvider */
     $configProvider = $this->getContainer()->get('oro_requirejs_config_provider');
     $output->writeln('Generating require.js main config');
     $mainConfigContent = $configProvider->generateMainConfig();
     // for some reason built application gets broken with configuration in "oneline-json"
     $mainConfigContent = str_replace(',', ",\n", $mainConfigContent);
     $mainConfigFilePath = $webRoot . DIRECTORY_SEPARATOR . self::MAIN_CONFIG_FILE_NAME;
     if (false === @file_put_contents($mainConfigFilePath, $mainConfigContent)) {
         throw new \RuntimeException('Unable to write file ' . $mainConfigFilePath);
     }
     $output->writeln('Generating require.js build config');
     $buildConfigContent = $configProvider->generateBuildConfig(self::MAIN_CONFIG_FILE_NAME);
     $buildConfigContent = '(' . json_encode($buildConfigContent) . ')';
     $buildConfigFilePath = $webRoot . DIRECTORY_SEPARATOR . self::BUILD_CONFIG_FILE_NAME;
     if (false === @file_put_contents($buildConfigFilePath, $buildConfigContent)) {
         throw new \RuntimeException('Unable to write file ' . $buildConfigFilePath);
     }
     if (isset($config['js_engine']) && $config['js_engine']) {
         $output->writeln('Running code optimizer');
         $command = $config['js_engine'] . ' ' . self::OPTIMIZER_FILE_PATH . ' -o ' . basename($buildConfigFilePath) . ' 1>&2';
         $process = new Process($command, $webRoot);
         $process->setTimeout($config['building_timeout']);
         // some workaround when this command is launched from web
         if (isset($_SERVER['PATH'])) {
             $env = $_SERVER;
             if (isset($env['Path'])) {
                 unset($env['Path']);
             }
             $process->setEnv($env);
         }
         $process->run();
         if (!$process->isSuccessful()) {
             throw new \RuntimeException($process->getErrorOutput());
         }
         $output->writeln('Cleaning up');
         if (false === @unlink($buildConfigFilePath)) {
             throw new \RuntimeException('Unable to remove file ' . $buildConfigFilePath);
         }
         $output->writeln(sprintf('<comment>%s</comment> <info>[file+]</info> %s', date('H:i:s'), realpath($webRoot . DIRECTORY_SEPARATOR . $config['build_path'])));
     }
 }
示例#14
0
 function render($context = null, $vars = array())
 {
     $finder = new ExecutableFinder();
     $bin = @$this->options["coffee_bin"] ?: self::DEFAULT_COFFEE;
     $cmd = $finder->find($bin);
     if ($cmd === null) {
         throw new \UnexpectedValueException("'{$bin}' executable was not found. Make sure it's installed.");
     }
     $cmd .= " -sc";
     $process = new Process($cmd);
     $process->setEnv(array('PATH' => @$_SERVER['PATH'] ?: join(PATH_SEPARATOR, array("/bin", "/sbin", "/usr/bin", "/usr/local/bin"))));
     $process->setStdin($this->data);
     $process->run();
     if (!$process->isSuccessful()) {
         throw new \RuntimeException("coffee({$this->source}) returned an error:\n {$process->getErrorOutput()}");
     }
     return $process->getOutput();
 }
示例#15
0
 /**
  * @Given /^I run in project "([^"]*)" as "([^"]*)":$/
  */
 public function iRunInProjectAs($project, $username, PyStringNode $commands)
 {
     $commands = $commands->getLines();
     $this->run(function ($kernel) use($project, $username, $commands) {
         $em = $kernel->getContainer()->get('doctrine')->getManager();
         $project = $em->getRepository('GitonomyCoreBundle:Project')->findOneByName($project);
         $user = $em->getRepository('GitonomyCoreBundle:User')->findOneByUsername($username);
         // create temp folders
         do {
             $dir = sys_get_temp_dir() . '/shell_' . md5(mt_rand());
         } while (is_dir($dir));
         mkdir($dir, 0777, true);
         register_shutdown_function(function () use($dir) {
             $iterator = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS);
             $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST);
             foreach ($iterator as $file) {
                 if (!is_link($file)) {
                     chmod($file, 0777);
                 }
                 if (is_dir($file)) {
                     rmdir($file);
                 } else {
                     unlink($file);
                 }
             }
             chmod($dir, 0777);
             rmdir($dir);
         });
         $repo = Admin::cloneTo($dir, $project->getRepository()->getPath(), false);
         foreach ($commands as $command) {
             $process = new Process($command);
             $process->setWorkingDirectory($dir);
             $env = array('GITONOMY_USER' => $username, 'GITONOMY_PROJECT' => $project->getSlug());
             $env = array_merge($_SERVER, $env);
             $process->setEnv($env);
             $process->run();
             if (!$process->isSuccessful()) {
                 throw new \RuntimeException(sprintf("Execution of command '%s' failed: \n%s\n%s", $command, $process->getOutput(), $process->getErrorOutput()));
             }
         }
     });
 }
示例#16
0
 protected function compileProcess(Process $process, $path)
 {
     $process->setEnv(['PATH' => implode(':', array_merge($this->paths, [trim(`echo \$PATH`)]))]);
     $out = '';
     $err = '';
     $status = $process->run(function ($type, $line) use(&$out, &$err) {
         if ($type === 'out') {
             $out .= $line . PHP_EOL;
         } else {
             if ($type === 'err') {
                 $err .= $line . PHP_EOL;
             }
         }
     });
     if ($status === 0) {
         return $out;
     } else {
         throw new CompilationException($path, $err, ['path' => $process->getEnv()['PATH'], 'time' => date('Y-m-d H:i T'), 'command' => $process->getCommandLine()]);
     }
 }
 /**
  * Sets specified ENV variable
  *
  * @When /^"BEHAT_PARAMS" environment variable is set to:$/
  *
  * @param PyStringNode $value
  */
 public function iSetEnvironmentVariable(PyStringNode $value)
 {
     $this->process->setEnv(array('BEHAT_PARAMS' => (string) $value));
 }
示例#18
0
 /**
  * Runs a specific command in the build process.
  *
  * @param string $command
  * @return int
  */
 protected function runCommand($command)
 {
     $command = $this->parseBuildScriptLine($command);
     $config = $this->system->getConfig();
     $this->log("<strong>\$ {$command}</strong>");
     $process = new Process($command, $this->workingDir);
     $process->setTimeout(10 * 60);
     if (isset($config['env']) && isset($config['env']['path'])) {
         $env = $_SERVER;
         $env['PATH'] = $config['env']['path'];
         $process->setEnv($env);
     }
     $process->run(function ($type, $buffer) {
         file_put_contents($this->outputFile, $buffer, FILE_APPEND);
     });
     return $process->getExitCode();
 }
 private function getMediaInfo($file)
 {
     $process = new Process('mediainfo -f --Output=XML \'' . $file . '\'');
     $process->setEnv(array("LANG" => "en_US.UTF-8"));
     $process->setTimeout(60);
     $process->run();
     if (!$process->isSuccessful()) {
         throw new \RuntimeException($process->getErrorOutput());
     }
     return $process->getOutput();
 }
示例#20
0
 /**
  * Gets the path for the request assets and handles caching/etag responses
  * Automatically sends a 404 and exits if path doesn't exist or fails a security check
  *
  * @param string $contentType
  * @param Process $process Process should compile asset and write to stdout.  If null, path contents will be ouputed
  * @param int $lastModified If null, filemtime will be used, should return a unix timestamp
  */
 private function process($contentType, Process $process = null, $lastModified = null)
 {
     if ($lastModified === null) {
         $lastModified = filemtime($this->path);
     }
     $etag = '"' . sha1($this->path . $lastModified) . '"';
     if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
         if ($_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
             header('HTTP/1.1 304 Not Modified');
             exit;
         }
     }
     $dateFormat = 'D, d M Y H:i:s T';
     header('Cache-Control: public, max-age=31536000');
     header('Expires: ' . gmdate($dateFormat, $lastModified + 31536000));
     header('Last-Modified: ' . gmdate($dateFormat, $lastModified));
     header('ETag: ' . $etag);
     header('Content-Type: ' . $contentType . '; charset=utf-8');
     $compile = function () use($process) {
         if ($process === null) {
             return file_get_contents($this->path);
         } else {
             header('X-Cached: false');
             $paths = ['/bin/', '/usr/bin/', '/usr/local/bin/'];
             foreach ($paths as $k => $v) {
                 if (!file_exists($v)) {
                     unset($paths[$k]);
                 }
             }
             $process->setEnv(['PATH' => trim(`echo \$PATH`) . ':' . implode(':', $paths)]);
             $out = '';
             $err = '';
             $status = $process->run(function ($type, $line) use(&$out, &$err) {
                 if ($type === 'out') {
                     $out .= $line . "\n";
                 } else {
                     if ($type === 'err') {
                         $err .= $line . "\n";
                     }
                 }
             });
             if ($status === 0) {
                 return $out;
             } else {
                 echo "/* PATH: " . $process->getEnv()['PATH'] . " */\n";
                 echo "/* TIME: " . date('Y-m-d H:i T') . " */\n";
                 echo "/* COMMAND: " . $process->getCommandLine() . " */\n";
                 echo $err;
                 exit;
             }
         }
     };
     if (isset($_GET['ignore-cache'])) {
         echo $compile();
     } else {
         echo app('cache')->remember(str_slug($this->path) . '-' . md5($lastModified), 1440, $compile);
     }
     exit;
 }
示例#21
0
<?php

require_once './autoloader.php';
$loader->registerNamespace('Symfony\\', EVA_LIB_PATH . '/Symfony/');
$appGlobelConfig = (include EVA_CONFIG_PATH . DIRECTORY_SEPARATOR . 'application.config.php');
$appLocalConfig = EVA_CONFIG_PATH . DIRECTORY_SEPARATOR . 'application.local.config.php';
if (file_exists($appLocalConfig)) {
    $appLocalConfig = (include $appLocalConfig);
    $appGlobelConfig = array_merge($appGlobelConfig, $appLocalConfig);
}
Zend\Mvc\Application::init($appGlobelConfig);
use Symfony\Component\Process\Process;
$process = new Process('C:\\Windows\\System32\\cmd.exe /V:ON /E:ON /C ""C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\AlloVince\\AppData\\Local\\Temp\\assB045.tmp""');
$process->setEnv(array('NODE_PATH' => 'C:\\Users\\AlloVince\\AppData\\Roaming\\npm\\node_modules'));
$process->setTimeout(3600);
$process->run();
if (!$process->isSuccessful()) {
    p($process);
}
print $process->getOutput();
示例#22
0
 /**
  * @param string $cwd
  * @param null|[] $env
  * @param null|int $timeout
  *
  * @return string
  */
 public function run($cwd = null, $env = null, $timeout = null)
 {
     $env = array_merge($this->environments, (array) $env);
     $this->environments = [];
     $process = new Process($this->toString(), $cwd);
     $process->setTimeout($timeout);
     if ($env) {
         $environments = [];
         foreach ($env as $name => $value) {
             $environments[$name] = $this->escapeValue($value);
         }
         $process->setEnv($environments);
     }
     $process->mustRun();
     return $process->getOutput();
 }
示例#23
0
文件: Git.php 项目: szoper/PHPGit
 /**
  * Executes a process.
  *
  * @param Process $process The process to run
  *
  * @throws Exception\GitException
  *
  * @return mixed
  */
 public function run(Process $process)
 {
     $env = array_merge($process->getEnv(), $this->getEnvVars());
     $process->setEnv($env);
     $process->run();
     if (!$process->isSuccessful()) {
         throw new GitException($process->getErrorOutput(), $process->getExitCode(), $process->getCommandLine());
     }
     return $process->getOutput();
 }