-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPlatformInstaller.php
More file actions
331 lines (277 loc) · 10.6 KB
/
PlatformInstaller.php
File metadata and controls
331 lines (277 loc) · 10.6 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
<?php
declare(strict_types=1);
namespace Codewithkyrian\PlatformPackageInstaller;
use Composer\Installer\LibraryInstaller;
use Composer\IO\IOInterface;
use Composer\Package\PackageInterface;
use Composer\PartialComposer;
use React\Promise\PromiseInterface;
class PlatformInstaller extends LibraryInstaller
{
private ArtifactUrlResolver $artifactUrlResolver;
public function __construct(IOInterface $io, PartialComposer $composer)
{
parent::__construct($io, $composer, "platform-package");
$this->artifactUrlResolver = new ArtifactUrlResolver();
}
public function download(PackageInterface $package, ?PackageInterface $prevPackage = null): ?PromiseInterface
{
if ($url = $this->resolveDistUrl($package)) {
$package->setDistUrl($url);
$package->setDistType($this->inferArchiveType($url));
}
return parent::download($package, $prevPackage);
}
private function resolveDistUrl(PackageInterface $package): string|false
{
$artifacts = $this->resolveArtifactsConfig($package);
if ($artifacts === false) {
return false;
}
$normalized = $this->normalizeArtifactsConfig($package, $artifacts);
if ($normalized === false) {
return false;
}
$validatedUrls = $this->validateArtifactUrls($package, $normalized['urls']);
if ($matchingTemplate = Platform::findBestMatch($validatedUrls)) {
$defaultVars = $this->normalizeVars($normalized['vars']);
$overrideVars = $this->resolveOverrideVars($package);
$hasOverrides = $overrideVars !== [];
$primaryVars = $this->artifactUrlResolver->mergeVars($defaultVars, $overrideVars, $package->getPrettyVersion());
$primaryResult = $this->resolveCandidateUrl($matchingTemplate, $primaryVars);
if ($primaryResult['url'] !== false) {
return $primaryResult['url'];
}
if ($hasOverrides) {
$fallbackVars = $this->artifactUrlResolver->mergeVars($defaultVars, [], $package->getPrettyVersion());
$fallbackResult = $this->resolveCandidateUrl($matchingTemplate, $fallbackVars);
if ($fallbackResult['url'] !== false) {
$this->io->writeError(
"{$package->getName()}: Override-resolved artifact URL failed ({$primaryResult['reason']}). ".
"Falling back to package default variables URL: {$fallbackResult['url']}"
);
return $fallbackResult['url'];
}
$this->io->writeError(
"{$package->getName()}: Override-resolved artifact URL failed ({$primaryResult['reason']}). ".
"Default-variable fallback also failed ({$fallbackResult['reason']})."
);
return false;
}
$this->io->writeError("{$package->getName()}: {$primaryResult['reason']}");
return false;
}
$this->io->writeError("{$package->getName()}: No download URL found for current platform");
return false;
}
/**
* Resolve artifact config from v2 and legacy keys.
*
* v2 preferred key: extra.artifacts
* legacy key: extra.platform-urls
*
* @return array<string, mixed>|false
*/
private function resolveArtifactsConfig(PackageInterface $package): array|false
{
$extra = $package->getExtra();
if (array_key_exists('artifacts', $extra)) {
$artifacts = $extra['artifacts'];
if (!is_array($artifacts)) {
$this->io->writeError("{$package->getName()}: Invalid extra.artifacts config (expected object)");
return false;
}
return $artifacts;
}
if (array_key_exists('platform-urls', $extra)) {
$legacy = $extra['platform-urls'];
if (!is_array($legacy)) {
$this->io->writeError("{$package->getName()}: Invalid extra.platform-urls config (expected object)");
return false;
}
$this->io->writeError("{$package->getName()}: extra.platform-urls is deprecated. Please migrate to extra.artifacts.");
return $legacy;
}
return [];
}
/**
* Supports two artifact formats:
* 1) Simple: artifacts = { "darwin-arm64": "https://..." }
* 2) Extended: artifacts = { "urls": {...}, "vars": {...} }
*
* @param array<string, mixed> $artifacts
*
* @return array{urls: array<string, mixed>, vars: array<string, mixed>}|false
*/
private function normalizeArtifactsConfig(PackageInterface $package, array $artifacts): array|false
{
if (array_key_exists('urls', $artifacts)) {
$urls = $artifacts['urls'];
if (!is_array($urls)) {
$this->io->writeError("{$package->getName()}: Invalid extra.artifacts.urls config (expected object)");
return false;
}
$vars = $artifacts['vars'] ?? [];
if (!is_array($vars)) {
$this->io->writeError("{$package->getName()}: Invalid extra.artifacts.vars config (expected object)");
return false;
}
return [
'urls' => $urls,
'vars' => $vars,
];
}
if (array_key_exists('vars', $artifacts)) {
$this->io->writeError("{$package->getName()}: Invalid extra.artifacts config. Use extra.artifacts.urls when defining extra.artifacts.vars");
return false;
}
return [
'urls' => $artifacts,
'vars' => [],
];
}
/**
* Check if a URL exists by sending a HEAD request
*/
private function urlExists(string $url): bool
{
try {
$headers = @get_headers($url);
if ($headers === false) {
return false;
}
return str_contains($headers[0], '200') || str_contains($headers[0], '302');
} catch (\Exception) {
return false;
}
}
/**
* @param PackageInterface $package
* @param array<string, mixed> $platformUrls
*
* @return array<string, string>
*/
private function validateArtifactUrls(PackageInterface $package, array $platformUrls): array
{
$validatedPlatforms = [];
foreach ($platformUrls as $platform => $url) {
if (!is_string($platform) || $platform === '') {
continue;
}
if (!is_string($url) || $url === '') {
$this->io->writeError("{$package->getName()}: Invalid artifact URL for platform '$platform' (expected non-empty string). Skipping...");
continue;
}
$validatedPlatforms[strtolower($platform)] = $url;
}
return $validatedPlatforms;
}
private function resolveOverrideVars(PackageInterface $package): array
{
$rootExtra = $this->composer->getPackage()->getExtra();
$platformPackages = $rootExtra['platform-packages'] ?? [];
if (!is_array($platformPackages)) {
$platformPackages = [];
}
$overrideVars = $platformPackages[$package->getName()] ?? [];
if (!is_array($overrideVars)) {
$overrideVars = [];
}
return $this->normalizeVars($overrideVars);
}
/**
* @param array<string, mixed> $vars
*
* @return array<string, mixed>
*/
private function normalizeVars(array $vars): array
{
$normalized = [];
foreach ($vars as $key => $value) {
if (!is_string($key) || $key === '') {
continue;
}
$normalized[$key] = $value;
}
return $normalized;
}
/**
* @param array<string, string> $vars
*
* @return array{url: string|false, reason: string}
*/
private function resolveCandidateUrl(string $template, array $vars): array
{
$resolvedUrl = $this->artifactUrlResolver->applyTemplate($template, $vars);
$unresolved = $this->artifactUrlResolver->unresolvedPlaceholders($resolvedUrl);
if ($unresolved !== []) {
$missing = implode(', ', array_map(fn($k) => '{'.$k.'}', $unresolved));
return [
'url' => false,
'reason' => "Unresolved URL placeholders: {$missing}",
];
}
if (!filter_var($resolvedUrl, FILTER_VALIDATE_URL)) {
return [
'url' => false,
'reason' => "Invalid resolved URL: {$resolvedUrl}",
];
}
if (!$this->urlExists($resolvedUrl)) {
return [
'url' => false,
'reason' => "URL found for current platform but it doesn't exist: {$resolvedUrl}",
];
}
return [
'url' => $resolvedUrl,
'reason' => 'ok',
];
}
private function inferArchiveType(string $url): string
{
$urlPath = parse_url($url, PHP_URL_PATH);
$extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
$archiveTypes = [
// Compressed archives
'zip' => 'zip',
'tar' => 'tar',
'gz' => 'tar',
'tgz' => 'tar',
'tbz2' => 'tar',
'bz2' => 'tar',
'7z' => '7z',
'rar' => 'rar',
// Less common but still valid
'xz' => 'tar',
'lz' => 'tar',
'lzma' => 'tar',
];
if (isset($archiveTypes[$extension])) {
return $archiveTypes[$extension];
}
try {
$headers = get_headers($url, true);
if (is_array($headers)) {
$contentType = strtolower($headers['Content-Type'] ?? '');
// Common content type mappings
$contentTypeMap = [
'application/zip' => 'zip',
'application/x-zip-compressed' => 'zip',
'application/x-tar' => 'tar',
'application/x-gzip' => 'tar',
'application/gzip' => 'tar',
'application/x-bzip2' => 'tar',
];
foreach ($contentTypeMap as $type => $archiveType) {
if (strpos($contentType, $type) !== false) {
return $archiveType;
}
}
}
} catch (\Exception) {
}
// Fallback to ZIP if no other type could be determined
return 'zip';
}
}