Skip to content

Commit

Permalink
Exec: Store current working directory
Browse files Browse the repository at this point in the history
  • Loading branch information
jnvsor committed Nov 29, 2017
1 parent c56875c commit afb8bc9
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/Ssh/Exec.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,42 @@
*/
class Exec extends Subsystem
{
protected $cwd;
protected $storeCwd = false;

protected function createResource()
{
$this->resource = $this->getSessionResource();
}

public function run($cmd, $pty = null, array $env = array(), $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS)
{
$cmd .= ';echo -ne "[return_code:$?]"';
if ($this->cwd && $this->storeCwd) {
$cmd = 'cd '.escapeshellarg($this->cwd).';'.$cmd;
}

$cmd .= ';echo -ne "\\0$?\\0";pwd';
$stdout = ssh2_exec($this->getResource(), $cmd, $pty, $env, $width, $height, $width_height_type);
$stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR);
stream_set_blocking($stderr, true);
stream_set_blocking($stdout, true);

$output = stream_get_contents($stdout);
preg_match('/\[return_code:(.*?)\]/', $output, $match);
if ((int) $match[1] !== 0) {
throw new RuntimeException(stream_get_contents($stderr), (int) $match[1]);
preg_match('/\\0(\d+)\\0(.+?)$/', $output, $match);

list($_, $retcode, $cwd) = $match;

$this->cwd = rtrim($cwd, "\r\n");

if ((int) $retcode) {
throw new RuntimeException(stream_get_contents($stderr), (int) $retcode);
}

return preg_replace('/\[return_code:(.*?)\]/', '', $output);
return preg_replace('/\\0(\d+)\\0(.+?)$/', '', $output);
}

public function setStoreCwd($store)
{
$this->storeCwd = $store;
}
}

0 comments on commit afb8bc9

Please sign in to comment.