-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloudRun.php
More file actions
294 lines (227 loc) · 8.12 KB
/
CloudRun.php
File metadata and controls
294 lines (227 loc) · 8.12 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<?php
declare(strict_types=1);
namespace Pest\PestCloud;
use CURLFile;
use Phar;
use PharData;
use RuntimeException;
/**
* @internal
*/
class CloudRun
{
private const int MAX_TARBALL_SIZE = 50 * 1024 * 1024;
private const int MAX_RETRIES = 3;
/**
* @param array<int, string> $arguments
*/
public function handle(array $arguments): int
{
$projectPath = (string) getcwd();
$config = $this->loadConfig($projectPath);
$apiUrl = is_string($_SERVER['PEST_CLOUD_URL'] ?? null)
? $_SERVER['PEST_CLOUD_URL']
: 'https://cloud.pestphp.com';
$apiToken = is_string($_SERVER['PEST_CLOUD_TOKEN'] ?? null)
? $_SERVER['PEST_CLOUD_TOKEN']
: '';
if ($apiToken === '') {
fwrite(STDERR, "Error: No API token configured. Set the PEST_CLOUD_TOKEN environment variable.\n");
return 1;
}
$pestArguments = implode(' ', $arguments);
$files = $config['respectGitignore']
? $this->getGitTrackedFiles($projectPath)
: $this->getAllFiles($projectPath);
$files = $this->applyExclusions($files, $config['exclude']);
if ($files === []) {
fwrite(STDERR, "Error: No files to include in the tarball.\n");
return 1;
}
$tarballPath = $this->createTarball($projectPath, $files);
try {
$size = filesize($tarballPath);
if ($size === false || $size > self::MAX_TARBALL_SIZE) {
fwrite(STDERR, "Error: Project tarball exceeds the 50 MB limit. Add more exclusions to pest.cloud.json.\n");
return 1;
}
$response = $this->upload($apiUrl, $apiToken, $tarballPath, $pestArguments);
echo "Run created successfully.\n";
echo "ID: {$response['id']}\n";
echo "Status: {$response['status']}\n";
return 0;
} finally {
if (file_exists($tarballPath)) {
unlink($tarballPath);
}
}
}
/**
* @return array{respectGitignore: bool, exclude: list<string>}
*/
private function loadConfig(string $projectPath): array
{
$defaults = [
'respectGitignore' => true,
'exclude' => [],
];
$configPath = $projectPath.'/pest.cloud.json';
if (! file_exists($configPath)) {
return $defaults;
}
$content = file_get_contents($configPath);
if ($content === false) {
return $defaults;
}
$config = json_decode($content, true);
if (! is_array($config)) {
return $defaults;
}
/** @var array{respectGitignore?: bool, exclude?: list<string>} $config */
return [
'respectGitignore' => $config['respectGitignore'] ?? true,
'exclude' => $config['exclude'] ?? [],
];
}
/**
* @return list<string>
*/
private function getGitTrackedFiles(string $projectPath): array
{
$command = 'cd '.escapeshellarg($projectPath).' && git ls-files --cached --others --exclude-standard';
$output = [];
$resultCode = 0;
exec($command, $output, $resultCode);
if ($resultCode !== 0) {
return $this->getAllFiles($projectPath);
}
return array_values(array_filter(
$output,
fn (string $file): bool => $file !== '' && is_file($projectPath.'/'.$file),
));
}
/**
* @return list<string>
*/
private function getAllFiles(string $projectPath): array
{
$files = [];
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($projectPath, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::LEAVES_ONLY,
);
/** @var \SplFileInfo $file */
foreach ($iterator as $file) {
if ($file->isFile()) {
$files[] = substr($file->getPathname(), strlen($projectPath) + 1);
}
}
return $files;
}
/**
* @param list<string> $files
* @param list<string> $exclusions
* @return list<string>
*/
private function applyExclusions(array $files, array $exclusions): array
{
if ($exclusions === []) {
return $files;
}
return array_values(array_filter($files, function (string $file) use ($exclusions): bool {
foreach ($exclusions as $pattern) {
if (fnmatch($pattern, $file) || fnmatch($pattern, basename($file)) || str_starts_with($file, rtrim($pattern, '/').'/')) {
return false;
}
}
return true;
}));
}
/**
* @param list<string> $files
*/
private function createTarball(string $projectPath, array $files): string
{
$tarPath = sys_get_temp_dir().'/pest_cloud_'.bin2hex(random_bytes(8)).'.tar';
$tarballPath = $tarPath.'.gz';
$phar = new PharData($tarPath);
foreach ($files as $file) {
$fullPath = $projectPath.'/'.$file;
if (is_file($fullPath)) {
$phar->addFile($fullPath, $file);
}
}
$phar->compress(Phar::GZ);
if (file_exists($tarPath)) {
unlink($tarPath);
}
return $tarballPath;
}
/**
* @return array{id: string, status: string}
*/
private function upload(string $apiUrl, string $apiToken, string $tarballPath, string $pestArguments): array
{
$url = rtrim($apiUrl, '/').'/api/run';
$lastException = null;
for ($attempt = 1; $attempt <= self::MAX_RETRIES; $attempt++) {
try {
return $this->doUpload($url, $apiToken, $tarballPath, $pestArguments);
} catch (RuntimeException $e) {
$lastException = $e;
if (str_contains($e->getMessage(), '401') || str_contains($e->getMessage(), '422')) {
throw $e;
}
if ($attempt < self::MAX_RETRIES) {
sleep(2 ** ($attempt - 1));
}
}
}
throw $lastException;
}
/**
* @return array{id: string, status: string}
*/
private function doUpload(string $url, string $apiToken, string $tarballPath, string $pestArguments): array
{
$ch = curl_init($url);
$postFields = [
'tarball' => new CURLFile($tarballPath, 'application/gzip', 'project.tar.gz'),
];
if ($pestArguments !== '') {
$postFields['pest_arguments'] = $pestArguments;
}
curl_setopt_array($ch, [
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer '.$apiToken,
'Accept: application/json',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($response === false) {
throw new RuntimeException('Network error: '.$error);
}
/** @var array{id?: string, status?: string, message?: string}|null $body */
$body = json_decode((string) $response, true);
if ($httpCode === 401) {
throw new RuntimeException('Authentication failed (401): Check your API token.');
}
if ($httpCode === 422) {
$message = is_array($body) ? ($body['message'] ?? 'Validation error') : 'Validation error';
throw new RuntimeException('Validation error (422): '.$message);
}
if ($httpCode >= 500) {
throw new RuntimeException("Server error ({$httpCode}): The service may be temporarily unavailable.");
}
if ($httpCode !== 201 || ! is_array($body) || ! isset($body['id'], $body['status'])) {
throw new RuntimeException("Unexpected response (HTTP {$httpCode}): ".$response);
}
return ['id' => $body['id'], 'status' => $body['status']];
}
}