Skip to content

Commit afb8bc9

Browse files
committed
Exec: Store current working directory
1 parent c56875c commit afb8bc9

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/Ssh/Exec.php

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,25 +13,42 @@
1313
*/
1414
class Exec extends Subsystem
1515
{
16+
protected $cwd;
17+
protected $storeCwd = false;
18+
1619
protected function createResource()
1720
{
1821
$this->resource = $this->getSessionResource();
1922
}
2023

2124
public function run($cmd, $pty = null, array $env = array(), $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS)
2225
{
23-
$cmd .= ';echo -ne "[return_code:$?]"';
26+
if ($this->cwd && $this->storeCwd) {
27+
$cmd = 'cd '.escapeshellarg($this->cwd).';'.$cmd;
28+
}
29+
30+
$cmd .= ';echo -ne "\\0$?\\0";pwd';
2431
$stdout = ssh2_exec($this->getResource(), $cmd, $pty, $env, $width, $height, $width_height_type);
2532
$stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR);
2633
stream_set_blocking($stderr, true);
2734
stream_set_blocking($stdout, true);
2835

2936
$output = stream_get_contents($stdout);
30-
preg_match('/\[return_code:(.*?)\]/', $output, $match);
31-
if ((int) $match[1] !== 0) {
32-
throw new RuntimeException(stream_get_contents($stderr), (int) $match[1]);
37+
preg_match('/\\0(\d+)\\0(.+?)$/', $output, $match);
38+
39+
list($_, $retcode, $cwd) = $match;
40+
41+
$this->cwd = rtrim($cwd, "\r\n");
42+
43+
if ((int) $retcode) {
44+
throw new RuntimeException(stream_get_contents($stderr), (int) $retcode);
3345
}
3446

35-
return preg_replace('/\[return_code:(.*?)\]/', '', $output);
47+
return preg_replace('/\\0(\d+)\\0(.+?)$/', '', $output);
48+
}
49+
50+
public function setStoreCwd($store)
51+
{
52+
$this->storeCwd = $store;
3653
}
3754
}

0 commit comments

Comments
 (0)