This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlugin.php
399 lines (328 loc) · 14 KB
/
Plugin.php
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
<?php
declare(strict_types=1);
/**
* Copyright (c) 2018-2020 Daniel Bannert
*
* For the full copyright and license information, please view
* the LICENSE.md file that was distributed with this source code.
*
* @see https://github.com/narrowspark/automatic
*/
namespace Narrowspark\Automatic\Prefetcher;
use Closure;
use Composer\Composer;
use Composer\Config;
use Composer\Console\Application;
use Composer\DependencyResolver\Pool;
use Composer\EventDispatcher\EventSubscriberInterface;
use Composer\Installer\InstallerEvent;
use Composer\Installer\InstallerEvents;
use Composer\Installer\PackageEvents;
use Composer\IO\IOInterface;
use Composer\Package\BasePackage;
use Composer\Plugin\PluginEvents;
use Composer\Plugin\PluginInterface;
use Composer\Plugin\PreFileDownloadEvent;
use Composer\Repository\ComposerRepository as BaseComposerRepository;
use Composer\Repository\RepositoryFactory;
use Composer\Repository\RepositoryInterface;
use Composer\Repository\RepositoryManager;
use FilesystemIterator;
use InvalidArgumentException;
use Narrowspark\Automatic\Common\AbstractContainer;
use Narrowspark\Automatic\Common\Downloader\ParallelDownloader;
use Narrowspark\Automatic\Prefetcher\Common\Util;
use Narrowspark\Automatic\Prefetcher\Contract\LegacyTagsManager as LegacyTagsManagerContract;
use Narrowspark\Automatic\Prefetcher\Contract\Prefetcher as PrefetcherContract;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionMethod;
use SplFileInfo;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputInterface;
/**
* @noRector \Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector
*/
final class Plugin implements EventSubscriberInterface, PluginInterface
{
/** @var string */
public const VERSION = '0.13.1';
/** @var string */
public const COMPOSER_EXTRA_KEY = 'prefetcher';
/** @var string */
public const PACKAGE_NAME = 'narrowspark/automatic-composer-prefetcher';
/**
* A Container instance.
*
* @var \Narrowspark\Automatic\Common\Contract\Container
*/
private $container;
/**
* Check if the the plugin is activated.
*
* @var bool
*/
private static $activated = true;
/**
* {@inheritdoc}
*/
public function activate(Composer $composer, IOInterface $io): void
{
// to avoid issues when Automatic Prefetcher is upgraded, we load all PHP classes now
// that way, we are sure to use all classes from the same version.
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(\dirname(__DIR__, 1), FilesystemIterator::SKIP_DOTS)) as $file) {
/** @var SplFileInfo $file */
if (\substr($file->getFilename(), -4) === '.php') {
\class_exists(__NAMESPACE__ . \str_replace('/', '\\', \substr($file->getFilename(), \strlen(__DIR__), -4)));
}
}
if (! \class_exists(AbstractContainer::class)) {
require __DIR__ . \DIRECTORY_SEPARATOR . 'alias.php';
}
if (($errorMessage = $this->getErrorMessage()) !== null) {
self::$activated = false;
$io->writeError('<warning>Narrowspark Automatic Prefetcher has been disabled. ' . $errorMessage . '</warning>');
return;
}
$this->container = new Container($composer, $io);
if ($this->container->get(InputInterface::class) === null) {
self::$activated = false;
$io->writeError('<warning>Narrowspark Automatic Prefetcher has been disabled. No input object found on composer class.</warning>');
return;
}
/** @var \Narrowspark\Automatic\Prefetcher\Contract\LegacyTagsManager $tagsManager */
$tagsManager = $this->container->get(LegacyTagsManagerContract::class);
$this->configureLegacyTagsManager($io, $tagsManager, $this->container->get('composer-extra'));
$composer->setRepositoryManager($this->extendRepositoryManager($composer, $io, $tagsManager));
// overwrite composer instance
$this->container->set(Composer::class, static function () use ($composer): Composer {
return $composer;
});
$this->extendComposer(\debug_backtrace(), $tagsManager);
}
/**
* {@inheritdoc}
*
* @return mixed[][][]|string[]
*/
public static function getSubscribedEvents(): array
{
if (! self::$activated) {
return [];
}
return [
InstallerEvents::PRE_DEPENDENCIES_SOLVING => [['onPreDependenciesSolving', \PHP_INT_MAX]],
InstallerEvents::POST_DEPENDENCIES_SOLVING => [['populateFilesCacheDir', \PHP_INT_MAX]],
PackageEvents::PRE_PACKAGE_INSTALL => [['populateFilesCacheDir', ~\PHP_INT_MAX]],
PackageEvents::PRE_PACKAGE_UPDATE => [['populateFilesCacheDir', ~\PHP_INT_MAX]],
PluginEvents::PRE_FILE_DOWNLOAD => 'onFileDownload',
];
}
/**
* Populate the provider cache.
*/
public function onPreDependenciesSolving(InstallerEvent $event): void
{
$listed = [];
$packages = [];
$pool = $event->getPool();
$pool = Closure::bind(function (): Pool {
foreach ($this->providerRepos as $k => $repo) {
$this->providerRepos[$k] = new class($repo) extends BaseComposerRepository {
/**
* A repository implementation.
*
* @var \Composer\Repository\RepositoryInterface
*/
private $repo;
public function __construct(RepositoryInterface $repo)
{
$this->repo = $repo;
}
/**
* {@inheritdoc}
*
* @return mixed[]
*/
public function whatProvides(Pool $pool, $name, $bypassFilters = false): array
{
$packages = [];
if (! \method_exists($this->repo, 'whatProvides')) {
return $packages;
}
foreach ($this->repo->whatProvides($pool, $name, $bypassFilters) as $k => $p) {
$packages[$k] = clone $p;
}
return $packages;
}
};
}
return $this;
}, clone $pool, $pool)();
foreach ($event->getRequest()->getJobs() as $job) {
if ($job['cmd'] !== 'install' || \strpos($job['packageName'], '/') === false) {
continue;
}
$listed[$job['packageName']] = true;
$packages[] = [$job['packageName'], $job['constraint']];
}
$loadExtraRepos = ! (new ReflectionMethod(Pool::class, 'match'))->isPublic(); // Detect Composer < 1.7.3
$this->container->get(ParallelDownloader::class)->download($packages, static function (string $packageName, $constraint) use (&$listed, &$packages, $pool, $loadExtraRepos): void {
/** @var \Composer\Package\PackageInterface $package */
foreach ($pool->whatProvides($packageName, $constraint, true) as $package) {
$links = $loadExtraRepos ? \array_merge($package->getRequires(), $package->getConflicts(), $package->getReplaces()) : $package->getRequires();
/** @var \Composer\Package\Link $link */
foreach ($links as $link) {
if (isset($listed[$link->getTarget()]) || \strpos($link->getTarget(), '/') === false) {
continue;
}
$listed[$link->getTarget()] = true;
$packages[] = [$link->getTarget(), $link->getConstraint()];
}
}
});
}
/**
* Wrapper for the fetchAllFromOperations function.
*
* @see \Narrowspark\Automatic\Prefetcher\Contract\Prefetcher::fetchAllFromOperations()
*
* @param \Composer\Installer\InstallerEvent|\Composer\Installer\PackageEvent $event
*/
public function populateFilesCacheDir(InstallerEvent $event): void
{
/** @var \Narrowspark\Automatic\Prefetcher\Contract\Prefetcher $prefetcher */
$prefetcher = $this->container->get(PrefetcherContract::class);
$prefetcher->fetchAllFromOperations($event);
}
/**
* Adds the parallel downloader to composer.
*/
public function onFileDownload(PreFileDownloadEvent $event): void
{
/** @var \Narrowspark\Automatic\Common\Downloader\ParallelDownloader $rfs */
$rfs = $this->container->get(ParallelDownloader::class);
if ($event->getRemoteFilesystem() !== $rfs) {
$event->setRemoteFilesystem($rfs->setNextOptions($event->getRemoteFilesystem()->getOptions()));
}
}
/**
* Configure the LegacyTagsManager with legacy package requires.
*/
private function configureLegacyTagsManager(
IOInterface $io,
LegacyTagsManagerContract $tagsManager,
array $extra
): void {
if (false !== $envRequire = \getenv('AUTOMATIC_PREFETCHER_REQUIRE')) {
$requires = [];
foreach (\explode(',', $envRequire) as $packageString) {
[$packageName, $version] = \explode(':', $packageString, 2);
$requires[$packageName] = $version;
}
$this->addLegacyTags($io, $requires, $tagsManager);
} elseif (isset($extra[self::COMPOSER_EXTRA_KEY]['require'])) {
$this->addLegacyTags($io, $extra[self::COMPOSER_EXTRA_KEY]['require'], $tagsManager);
}
}
/**
* Add found legacy tags to the tags manager.
*/
private function addLegacyTags(IOInterface $io, array $requires, LegacyTagsManagerContract $tagsManager): void
{
foreach ($requires as $name => $version) {
if (\is_int($name)) {
$io->writeError(\sprintf('Constrain [%s] skipped, because package name is a number [%s]', $version, $name));
continue;
}
if (\strpos($name, '/') === false) {
$io->writeError(\sprintf('Constrain [%s] skipped, package name [%s] without a slash is not supported', $version, $name));
continue;
}
$tagsManager->addConstraint($name, $version);
}
}
/**
* Extend the repository manager with a truncated composer repository and parallel downloader.
*/
private function extendRepositoryManager(
Composer $composer,
IOInterface $io,
LegacyTagsManagerContract $tagsManager
): RepositoryManager {
$manager = RepositoryFactory::manager(
$io,
$this->container->get(Config::class),
$this->container->get(Composer::class)->getEventDispatcher(),
$this->container->get(ParallelDownloader::class)
);
$setRepositories = Closure::bind(function (RepositoryManager $manager) use ($tagsManager): void {
$manager->repositoryClasses = $this->repositoryClasses;
$manager->setRepositoryClass('composer', TruncatedComposerRepository::class);
$manager->repositories = $this->repositories;
$i = 0;
foreach (RepositoryFactory::defaultRepos(null, $this->config, $manager) as $repo) {
$manager->repositories[$i++] = $repo;
if ($repo instanceof TruncatedComposerRepository) {
$repo->setTagsManager($tagsManager);
}
}
$manager->setLocalRepository($this->getLocalRepository());
}, $composer->getRepositoryManager(), RepositoryManager::class);
$setRepositories($manager);
return $manager;
}
/**
* Check if automatic can be activated.
*/
private function getErrorMessage(): ?string
{
// @codeCoverageIgnoreStart
if (! extension_loaded('openssl')) {
return 'You must enable the openssl extension in your [php.ini] file';
}
if (\version_compare(Util::getComposerVersion(), '1.8.0', '<')) {
return \sprintf('Your version "%s" of Composer is too old; Please upgrade', Composer::VERSION);
}
// @codeCoverageIgnoreEnd
return null;
}
/**
* Extend the composer object with some automatic prefetcher settings.
*
* @param array<int|string, mixed> $backtrace
*/
private function extendComposer(array $backtrace, LegacyTagsManagerContract $tagsManager): void
{
foreach ($backtrace as $trace) {
if (! isset($trace['object']) || ! isset($trace['args'][0])) {
continue;
}
if (! $trace['object'] instanceof Application || ! $trace['args'][0] instanceof ArgvInput) {
continue;
}
/** @var \Symfony\Component\Console\Input\InputInterface $input */
$input = $trace['args'][0];
$app = $trace['object'];
try {
/** @var null|string $command */
$command = $input->getFirstArgument();
$command = $command !== null ? $app->find($command)->getName() : null;
} catch (InvalidArgumentException $e) {
$command = null;
}
if ($command === 'outdated') {
$tagsManager->reset();
}
// When prefer-lowest is set and no stable version has been released,
// we consider "dev" more stable than "alpha", "beta" or "RC". This
// allows testing lowest versions with potential fixes applied.
if ($input->hasParameterOption('--prefer-lowest', true)) {
BasePackage::$stabilities['dev'] = 1 + BasePackage::STABILITY_STABLE;
}
$this->container->get(PrefetcherContract::class)->prefetchComposerRepositories();
break;
}
$this->container->get(PrefetcherContract::class)->populateRepoCacheDir();
}
}