-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathCliRunner.php
More file actions
117 lines (90 loc) · 2.39 KB
/
CliRunner.php
File metadata and controls
117 lines (90 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
namespace CzProject\GitPhp\Runners;
use CzProject\GitPhp\CommandProcessor;
use CzProject\GitPhp\GitException;
use CzProject\GitPhp\IRunner;
use CzProject\GitPhp\RunnerResult;
class CliRunner implements IRunner
{
/** @var string */
private $gitBinary;
/** @var CommandProcessor */
protected $commandProcessor;
/**
* @param string $gitBinary
*/
public function __construct($gitBinary = 'git')
{
$this->gitBinary = $gitBinary;
$this->commandProcessor = new CommandProcessor;
}
/**
* @return RunnerResult
*/
public function run($cwd, array $args, array $env = NULL)
{
if (!is_dir($cwd)) {
throw new GitException("Directory '$cwd' not found");
}
$descriptorspec = [
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'], // stderr
];
$pipes = [];
$command = $this->commandProcessor->process($this->gitBinary, $args);
$process = proc_open($command, $descriptorspec, $pipes, $cwd, $env, [
'bypass_shell' => TRUE,
]);
if (!$process) {
throw new GitException("Executing of command '$command' failed (directory $cwd).");
}
// Reset output and error
stream_set_blocking($pipes[1], FALSE);
stream_set_blocking($pipes[2], FALSE);
$stdout = '';
$stderr = '';
while (TRUE) {
// Read standard output
$stdoutOutput = stream_get_contents($pipes[1]);
if (is_string($stdoutOutput)) {
$stdout .= $stdoutOutput;
}
// Read error output
$stderrOutput = stream_get_contents($pipes[2]);
if (is_string($stderrOutput)) {
$stderr .= $stderrOutput;
}
// We are done
if ((feof($pipes[1]) || $stdoutOutput === FALSE) && (feof($pipes[2]) || $stderrOutput === FALSE)) {
break;
}
}
$returnCode = proc_close($process);
return new RunnerResult($command, $returnCode, $this->convertOutput($stdout), $this->convertOutput($stderr));
}
/**
* @return string
*/
public function getCwd()
{
$cwd = getcwd();
if (!is_string($cwd)) {
throw new \CzProject\GitPhp\InvalidStateException('Getting of CWD failed.');
}
return $cwd;
}
/**
* @param string $output
* @return string[]
*/
protected function convertOutput($output)
{
$output = str_replace(["\r\n", "\r"], "\n", $output);
$output = rtrim($output, "\n");
if ($output === '') {
return [];
}
return explode("\n", $output);
}
}