-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProjectPackageArchiveExtractor.php
More file actions
352 lines (298 loc) · 11.4 KB
/
Copy pathProjectPackageArchiveExtractor.php
File metadata and controls
352 lines (298 loc) · 11.4 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
<?php
declare(strict_types=1);
namespace Oak\Engine\Installer;
final class ProjectPackageArchiveExtractor
{
/**
* @param array<string> $excludeFolders
* @param array<string> $excludeFiles
*
* @return array{
* extracted: list<string>,
* skipped_files: list<string>,
* skipped_folders: list<string>
* }
*/
public function extractTarGz(
string $archiveContent,
string $targetDir,
array $excludeFolders,
array $excludeFiles,
): array {
$tempDirectory = sys_get_temp_dir().'/project_package_'.bin2hex(random_bytes(8));
if (!createDirectoryTree($tempDirectory, 0o755)) {
throw new \RuntimeException(sprintf('Unable to create temp directory "%s".', $tempDirectory));
}
$gzFile = $tempDirectory.'/package.tar.gz';
try {
if (false === file_put_contents($gzFile, $archiveContent)) {
throw new \RuntimeException(sprintf('Unable to write temp archive "%s".', $gzFile));
}
return $this->extractGzFileIntoTarget($gzFile, $tempDirectory, $targetDir, $excludeFolders, $excludeFiles);
} finally {
$this->recursiveDelete($tempDirectory);
}
}
/**
* @param array<string> $excludeFolders
* @param array<string> $excludeFiles
*
* @return array{
* extracted: list<string>,
* skipped_files: list<string>,
* skipped_folders: list<string>
* }
*/
public function extractTarGzFile(
string $archivePath,
string $targetDir,
array $excludeFolders,
array $excludeFiles,
): array {
if (!is_file($archivePath)) {
throw new \RuntimeException(sprintf('Package archive "%s" does not exist.', $archivePath));
}
$tempDirectory = sys_get_temp_dir().'/project_package_'.bin2hex(random_bytes(8));
if (!createDirectoryTree($tempDirectory, 0o755)) {
throw new \RuntimeException(sprintf('Unable to create temp directory "%s".', $tempDirectory));
}
try {
return $this->extractGzFileIntoTarget($archivePath, $tempDirectory, $targetDir, $excludeFolders, $excludeFiles);
} finally {
$this->recursiveDelete($tempDirectory);
}
}
/**
* @param array<string> $excludeFolders
* @param array<string> $excludeFiles
*
* @return array{
* extracted: list<string>,
* skipped_files: list<string>,
* skipped_folders: list<string>
* }
*/
private function extractGzFileIntoTarget(
string $gzFile,
string $tempDirectory,
string $targetDir,
array $excludeFolders,
array $excludeFiles,
): array {
$extractionDirectory = $tempDirectory.'/extract';
if (!createDirectoryTree($extractionDirectory, 0o755)) {
throw new \RuntimeException(sprintf('Unable to create extraction directory "%s".', $extractionDirectory));
}
$this->streamExtractGzTar($gzFile, $extractionDirectory);
$sourceDirectory = $this->resolveSourceDirectory($extractionDirectory);
return $this->copyExtractedDirectory(
$sourceDirectory,
$targetDir,
$excludeFolders,
$excludeFiles,
);
}
private function streamExtractGzTar(string $gzFile, string $extractionDirectory): void
{
$tarBinary = $this->resolveTarBinary();
if (null !== $tarBinary) {
$this->streamExtractGzTarWithBinary($tarBinary, $gzFile, $extractionDirectory);
return;
}
$this->streamExtractGzTarWithPhar($gzFile, $extractionDirectory);
}
private function resolveTarBinary(): ?string
{
$candidates = ['/bin/tar', '/usr/bin/tar', '/usr/local/bin/tar'];
foreach ($candidates as $candidate) {
if (is_file($candidate) && is_executable($candidate)) {
return $candidate;
}
}
$pathEnv = getenv('PATH');
if (is_string($pathEnv) && '' !== $pathEnv) {
$directories = explode(\PATH_SEPARATOR, $pathEnv);
foreach ($directories as $directory) {
$candidate = rtrim($directory, '/').'/tar';
if (is_file($candidate) && is_executable($candidate)) {
return $candidate;
}
}
}
return null;
}
private function streamExtractGzTarWithBinary(string $tarBinary, string $gzFile, string $extractionDirectory): void
{
$absoluteArchive = realpath($gzFile);
if (false === $absoluteArchive) {
throw new \RuntimeException(sprintf('Package archive "%s" does not exist.', $gzFile));
}
$command = [
$tarBinary,
'--extract',
'--gzip',
'--no-same-owner',
'--no-same-permissions',
'--file='.$absoluteArchive,
'--directory='.$extractionDirectory,
];
$process = proc_open($command, [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $pipes);
if (!is_resource($process)) {
throw new \RuntimeException('Unable to start tar process for package extraction.');
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if (0 !== $exitCode) {
throw new \RuntimeException(sprintf('Failed to extract package archive (exit %d): %s', $exitCode, '' !== $stderr ? trim($stderr) : (is_string($stdout) ? trim($stdout) : '')));
}
}
private function streamExtractGzTarWithPhar(string $gzFile, string $extractionDirectory): void
{
$phar = new \PharData($gzFile);
$phar->decompress();
$tarFile = preg_replace('/\.gz$/i', '', $gzFile);
if (!is_string($tarFile) || !is_file($tarFile)) {
throw new \RuntimeException(sprintf('Failed to decompress package archive "%s".', $gzFile));
}
try {
$archive = new \PharData($tarFile);
$archive->extractTo($extractionDirectory, null, true);
} finally {
@unlink($tarFile);
}
}
private function resolveSourceDirectory(string $extractionDirectory): string
{
$entries = array_values(array_filter(
scandir($extractionDirectory) ?: [],
static fn (string $entry): bool => '.' !== $entry && '..' !== $entry,
));
if (1 === count($entries)) {
$candidate = $extractionDirectory.'/'.$entries[0];
if (is_dir($candidate)) {
return $candidate;
}
}
return $extractionDirectory;
}
/**
* @param array<string> $excludeFolders
* @param array<string> $excludeFiles
*
* @return array{extracted: list<string>, skipped_files: list<string>, skipped_folders: list<string>}
*/
private function copyExtractedDirectory(
string $sourceDir,
string $targetDir,
array $excludeFolders,
array $excludeFiles,
): array {
$extractedFiles = [];
$skippedFiles = [];
$skippedFolders = [];
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($sourceDir, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST,
);
foreach ($iterator as $item) {
if (!$item instanceof \SplFileInfo) {
continue;
}
$absolutePath = $item->getPathname();
$relativePath = substr($absolutePath, strlen($sourceDir) + 1);
if ('' === $relativePath) {
continue;
}
$relativePathNormalized = str_replace('\\', '/', $relativePath);
$parentDir = dirname($relativePathNormalized);
if ('.' === $parentDir) {
$parentDir = '';
}
if ($item->isDir()) {
foreach ($excludeFolders as $excludeFolder) {
$excludeNormalized = trim(str_replace('\\', '/', $excludeFolder), '/');
if ($relativePathNormalized === $excludeNormalized || str_starts_with($relativePathNormalized, $excludeNormalized.'/')) {
$skippedFolders[] = $relativePath;
continue 2;
}
}
$targetPath = rtrim($targetDir, '/').'/'.$relativePath;
if (!is_dir($targetPath)) {
if (!createDirectoryTree($targetPath, 0o755)) {
throw new \RuntimeException(sprintf('Unable to create directory "%s".', $targetPath));
}
}
continue;
}
if ('' !== $parentDir) {
foreach ($excludeFolders as $excludeFolder) {
$excludeNormalized = trim(str_replace('\\', '/', $excludeFolder), '/');
if ($parentDir === $excludeNormalized || str_starts_with($parentDir, $excludeNormalized.'/')) {
$skippedFiles[] = $relativePath;
continue 2;
}
}
}
$fileName = basename($relativePathNormalized);
foreach ($excludeFiles as $excludeFile) {
$excludeNormalized = trim(str_replace('\\', '/', $excludeFile), '/');
if ($relativePathNormalized === $excludeNormalized || $fileName === $excludeNormalized) {
$skippedFiles[] = $relativePath;
continue 2;
}
}
$targetPath = rtrim($targetDir, '/').'/'.$relativePath;
$targetDirectoryPath = dirname($targetPath);
if (!is_dir($targetDirectoryPath)) {
if (!createDirectoryTree($targetDirectoryPath, 0o755)) {
throw new \RuntimeException(sprintf('Unable to create directory "%s".', $targetDirectoryPath));
}
} elseif (!is_writable($targetDirectoryPath)) {
@chmod($targetDirectoryPath, 0o755);
}
if (file_exists($targetPath) && !is_writable($targetPath)) {
@chmod($targetPath, 0o644);
}
if (!copy($absolutePath, $targetPath)) {
throw new \RuntimeException(sprintf('Unable to copy "%s" to "%s".', $absolutePath, $targetPath));
}
$extractedFiles[] = $relativePath;
}
return [
'extracted' => $extractedFiles,
'skipped_files' => $skippedFiles,
'skipped_folders' => $skippedFolders,
];
}
private function recursiveDelete(string $path): void
{
if (!file_exists($path)) {
return;
}
if (is_file($path)) {
unlink($path);
return;
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST,
);
foreach ($iterator as $item) {
if (!$item instanceof \SplFileInfo) {
continue;
}
if ($item->isDir()) {
rmdir($item->getPathname());
continue;
}
unlink($item->getPathname());
}
rmdir($path);
}
}