forked from composer/composer
/
RequireCommand.php
512 lines (437 loc) · 22.7 KB
/
RequireCommand.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
<?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\DependencyResolver\Request;
use Composer\Util\Filesystem;
use Symfony\Component\Console\Input\InputInterface;
use Composer\Console\Input\InputArgument;
use Composer\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Factory;
use Composer\Installer;
use Composer\Installer\InstallerEvents;
use Composer\Json\JsonFile;
use Composer\Json\JsonManipulator;
use Composer\Package\Version\VersionParser;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\BasePackage;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Composer\Repository\CompositeRepository;
use Composer\Repository\PlatformRepository;
use Composer\IO\IOInterface;
use Composer\Advisory\Auditor;
use Composer\Util\Silencer;
/**
* @author Jérémy Romey <jeremy@free-agent.fr>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class RequireCommand extends BaseCommand
{
use CompletionTrait;
use PackageDiscoveryTrait;
/** @var bool */
private $newlyCreated;
/** @var bool */
private $firstRequire;
/** @var JsonFile */
private $json;
/** @var string */
private $file;
/** @var string */
private $composerBackup;
/** @var string file name */
private $lock;
/** @var ?string contents before modification if the lock file exists */
private $lockBackup;
/** @var bool */
private $dependencyResolutionCompleted = false;
/**
* @return void
*/
protected function configure()
{
$this
->setName('require')
->setAliases(array('r'))
->setDescription('Adds required packages to your composer.json and installs them.')
->setDefinition(array(
new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Optional package name can also include a version constraint, e.g. foo/bar or foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"', null, $this->suggestAvailablePackageInclPlatform()),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Add requirement to require-dev.'),
new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'),
new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist (default behavior).'),
new InputOption('prefer-install', null, InputOption::VALUE_REQUIRED, 'Forces installation from package dist|source|auto (auto chooses source for dev versions, dist for the rest).', null, $this->suggestPreferInstall()),
new InputOption('fixed', null, InputOption::VALUE_NONE, 'Write fixed version to the composer.json.'),
new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'DEPRECATED: This flag does not exist anymore.'),
new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies (implies --no-install).'),
new InputOption('no-install', null, InputOption::VALUE_NONE, 'Skip the install step after updating the composer.lock file.'),
new InputOption('no-audit', null, InputOption::VALUE_NONE, 'Skip the audit step after updating the composer.lock file.'),
new InputOption('audit-format', null, InputOption::VALUE_REQUIRED, 'Audit output format. Must be "table", "plain", or "summary".', Auditor::FORMAT_SUMMARY, Auditor::FORMATS),
new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
new InputOption('update-with-dependencies', 'w', InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated, except those that are root requirements.'),
new InputOption('update-with-all-dependencies', 'W', InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements.'),
new InputOption('with-dependencies', null, InputOption::VALUE_NONE, 'Alias for --update-with-dependencies'),
new InputOption('with-all-dependencies', null, InputOption::VALUE_NONE, 'Alias for --update-with-all-dependencies'),
new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'),
new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'),
new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies.'),
new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies.'),
new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'),
new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'),
new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'),
new InputOption('apcu-autoloader-prefix', null, InputOption::VALUE_REQUIRED, 'Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader'),
))
->setHelp(
<<<EOT
The require command adds required packages to your composer.json and installs them.
If you do not specify a package, composer will prompt you to search for a package, and given results, provide a list of
matches to require.
If you do not specify a version constraint, composer will choose a suitable one based on the available package versions.
If you do not want to install the new dependencies immediately you can call it with --no-update
Read more at https://getcomposer.org/doc/03-cli.md#require
EOT
)
;
}
/**
* @throws \Seld\JsonLint\ParsingException
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->file = Factory::getComposerFile();
$io = $this->getIO();
if ($input->getOption('no-suggest')) {
$io->writeError('<warning>You are using the deprecated option "--no-suggest". It has no effect and will break in Composer 3.</warning>');
}
$this->newlyCreated = !file_exists($this->file);
if ($this->newlyCreated && !file_put_contents($this->file, "{\n}\n")) {
$io->writeError('<error>'.$this->file.' could not be created.</error>');
return 1;
}
if (!Filesystem::isReadable($this->file)) {
$io->writeError('<error>'.$this->file.' is not readable.</error>');
return 1;
}
if (filesize($this->file) === 0) {
file_put_contents($this->file, "{\n}\n");
}
$this->json = new JsonFile($this->file);
$this->lock = Factory::getLockFile($this->file);
$this->composerBackup = file_get_contents($this->json->getPath());
$this->lockBackup = file_exists($this->lock) ? file_get_contents($this->lock) : null;
if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) {
pcntl_async_signals(true);
pcntl_signal(SIGINT, function () { $this->revertComposerFile(); });
pcntl_signal(SIGTERM, function () { $this->revertComposerFile(); });
pcntl_signal(SIGHUP, function () { $this->revertComposerFile(); });
}
// check for writability by writing to the file as is_writable can not be trusted on network-mounts
// see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
if (!is_writable($this->file) && false === Silencer::call('file_put_contents', $this->file, $this->composerBackup)) {
$io->writeError('<error>'.$this->file.' is not writable.</error>');
return 1;
}
if ($input->getOption('fixed') === true) {
$config = $this->json->read();
$packageType = empty($config['type']) ? 'library' : $config['type'];
/**
* @see https://github.com/composer/composer/pull/8313#issuecomment-532637955
*/
if ($packageType !== 'project') {
$io->writeError('<error>The "--fixed" option is only allowed for packages with a "project" type to prevent possible misuses.</error>');
if (!isset($config['type'])) {
$io->writeError('<error>If your package is not a library, you can explicitly specify the "type" by using "composer config type project".</error>');
}
return 1;
}
}
$composer = $this->requireComposer();
$repos = $composer->getRepositoryManager()->getRepositories();
$platformOverrides = $composer->getConfig()->get('platform');
// initialize $this->repos as it is used by the PackageDiscoveryTrait
$this->repos = new CompositeRepository(array_merge(
array($platformRepo = new PlatformRepository(array(), $platformOverrides)),
$repos
));
if ($composer->getPackage()->getPreferStable()) {
$preferredStability = 'stable';
} else {
$preferredStability = $composer->getPackage()->getMinimumStability();
}
try {
$requirements = $this->determineRequirements(
$input,
$output,
$input->getArgument('packages'),
$platformRepo,
$preferredStability,
!$input->getOption('no-update'),
$input->getOption('fixed')
);
} catch (\Exception $e) {
if ($this->newlyCreated) {
$this->revertComposerFile(false);
throw new \RuntimeException('No composer.json present in the current directory ('.$this->file.'), this may be the cause of the following exception.', 0, $e);
}
throw $e;
}
$requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
$removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
$requirements = $this->formatRequirements($requirements);
// validate requirements format
$versionParser = new VersionParser();
foreach ($requirements as $package => $constraint) {
if (strtolower($package) === $composer->getPackage()->getName()) {
$io->writeError(sprintf('<error>Root package \'%s\' cannot require itself in its composer.json</error>', $package));
return 1;
}
if ($constraint === 'self.version') {
continue;
}
$versionParser->parseConstraints($constraint);
}
$inconsistentRequireKeys = $this->getInconsistentRequireKeys($requirements, $requireKey);
if (count($inconsistentRequireKeys) > 0) {
foreach ($inconsistentRequireKeys as $package) {
$io->warning(sprintf(
'%s is currently present in the %s key and you ran the command %s the --dev flag, which would move it to the %s key.',
$package,
$removeKey,
$input->getOption('dev') ? 'with' : 'without',
$requireKey
));
}
if ($io->isInteractive()) {
if (!$io->askConfirmation(sprintf('<info>Do you want to move %s?</info> [<comment>no</comment>]? ', count($inconsistentRequireKeys) > 1 ? 'these requirements' : 'this requirement'), false)) {
if (!$io->askConfirmation(sprintf('<info>Do you want to re-run the command %s --dev?</info> [<comment>yes</comment>]? ', $input->getOption('dev') ? 'without' : 'with'), true)) {
return 0;
}
list($requireKey, $removeKey) = array($removeKey, $requireKey);
}
}
}
$sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages');
$this->firstRequire = $this->newlyCreated;
if (!$this->firstRequire) {
$composerDefinition = $this->json->read();
if (count($composerDefinition['require'] ?? []) === 0 && count($composerDefinition['require-dev'] ?? []) === 0) {
$this->firstRequire = true;
}
}
if (!$input->getOption('dry-run') && !$this->updateFileCleanly($this->json, $requirements, $requireKey, $removeKey, $sortPackages)) {
$composerDefinition = $this->json->read();
foreach ($requirements as $package => $version) {
$composerDefinition[$requireKey][$package] = $version;
unset($composerDefinition[$removeKey][$package]);
if (isset($composerDefinition[$removeKey]) && count($composerDefinition[$removeKey]) === 0) {
unset($composerDefinition[$removeKey]);
}
}
$this->json->write($composerDefinition);
}
$io->writeError('<info>'.$this->file.' has been '.($this->newlyCreated ? 'created' : 'updated').'</info>');
if ($input->getOption('no-update')) {
return 0;
}
$composer->getPluginManager()->deactivateInstalledPlugins();
try {
return $this->doUpdate($input, $output, $io, $requirements, $requireKey, $removeKey);
} catch (\Exception $e) {
if (!$this->dependencyResolutionCompleted) {
$this->revertComposerFile(false);
}
throw $e;
}
}
/**
* @param array<string, string> $newRequirements
* @param string $requireKey
* @return string[]
*/
private function getInconsistentRequireKeys(array $newRequirements, string $requireKey): array
{
$requireKeys = $this->getPackagesByRequireKey();
$inconsistentRequirements = array();
foreach ($requireKeys as $package => $packageRequireKey) {
if (!isset($newRequirements[$package])) {
continue;
}
if ($requireKey !== $packageRequireKey) {
$inconsistentRequirements[] = $package;
}
}
return $inconsistentRequirements;
}
/**
* @return array<string, string>
*/
private function getPackagesByRequireKey(): array
{
$composerDefinition = $this->json->read();
$require = array();
$requireDev = array();
if (isset($composerDefinition['require'])) {
$require = $composerDefinition['require'];
}
if (isset($composerDefinition['require-dev'])) {
$requireDev = $composerDefinition['require-dev'];
}
return array_merge(
array_fill_keys(array_keys($require), 'require'),
array_fill_keys(array_keys($requireDev), 'require-dev')
);
}
/**
* @param array<string, string> $requirements
* @param string $requireKey
* @param string $removeKey
* @return int
* @throws \Exception
*/
private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements, string $requireKey, string $removeKey): int
{
// Update packages
$this->resetComposer();
$composer = $this->requireComposer();
$this->dependencyResolutionCompleted = false;
$composer->getEventDispatcher()->addListener(InstallerEvents::PRE_OPERATIONS_EXEC, function (): void {
$this->dependencyResolutionCompleted = true;
}, 10000);
if ($input->getOption('dry-run')) {
$rootPackage = $composer->getPackage();
$links = array(
'require' => $rootPackage->getRequires(),
'require-dev' => $rootPackage->getDevRequires(),
);
$loader = new ArrayLoader();
$newLinks = $loader->parseLinks($rootPackage->getName(), $rootPackage->getPrettyVersion(), BasePackage::$supportedLinkTypes[$requireKey]['method'], $requirements);
$links[$requireKey] = array_merge($links[$requireKey], $newLinks);
foreach ($requirements as $package => $constraint) {
unset($links[$removeKey][$package]);
}
$rootPackage->setRequires($links['require']);
$rootPackage->setDevRequires($links['require-dev']);
}
$updateDevMode = !$input->getOption('update-no-dev');
$optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
$authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
$apcuPrefix = $input->getOption('apcu-autoloader-prefix');
$apcu = $apcuPrefix !== null || $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader');
$updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED;
$flags = '';
if ($input->getOption('update-with-all-dependencies') || $input->getOption('with-all-dependencies')) {
$updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS;
$flags .= ' --with-all-dependencies';
} elseif ($input->getOption('update-with-dependencies') || $input->getOption('with-dependencies')) {
$updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE;
$flags .= ' --with-dependencies';
}
$io->writeError('<info>Running composer update '.implode(' ', array_keys($requirements)).$flags.'</info>');
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$composer->getInstallationManager()->setOutputProgress(!$input->getOption('no-progress'));
$install = Installer::create($io, $composer);
list($preferSource, $preferDist) = $this->getPreferredInstallOptions($composer->getConfig(), $input);
$install
->setDryRun($input->getOption('dry-run'))
->setVerbose($input->getOption('verbose'))
->setPreferSource($preferSource)
->setPreferDist($preferDist)
->setDevMode($updateDevMode)
->setOptimizeAutoloader($optimize)
->setClassMapAuthoritative($authoritative)
->setApcuAutoloader($apcu, $apcuPrefix)
->setUpdate(true)
->setInstall(!$input->getOption('no-install'))
->setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies)
->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input))
->setPreferStable($input->getOption('prefer-stable'))
->setPreferLowest($input->getOption('prefer-lowest'))
->setAudit(!$input->getOption('no-audit'))
->setAuditFormat($this->getAuditFormat($input))
;
// if no lock is present, or the file is brand new, we do not do a
// partial update as this is not supported by the Installer
if (!$this->firstRequire && $composer->getLocker()->isLocked()) {
$install->setUpdateAllowList(array_keys($requirements));
}
$status = $install->run();
if ($status !== 0) {
if ($status === Installer::ERROR_DEPENDENCY_RESOLUTION_FAILED) {
foreach ($this->normalizeRequirements($input->getArgument('packages')) as $req) {
if (!isset($req['version'])) {
$io->writeError('You can also try re-running composer require with an explicit version constraint, e.g. "composer require '.$req['name'].':*" to figure out if any version is installable, or "composer require '.$req['name'].':^2.1" if you know which you need.');
break;
}
}
}
$this->revertComposerFile(false);
}
return $status;
}
/**
* @param array<string, string> $new
* @param string $requireKey
* @param string $removeKey
* @param bool $sortPackages
* @return bool
*/
private function updateFileCleanly(JsonFile $json, array $new, string $requireKey, string $removeKey, bool $sortPackages): bool
{
$contents = file_get_contents($json->getPath());
$manipulator = new JsonManipulator($contents);
foreach ($new as $package => $constraint) {
if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) {
return false;
}
if (!$manipulator->removeSubNode($removeKey, $package)) {
return false;
}
}
$manipulator->removeMainKeyIfEmpty($removeKey);
file_put_contents($json->getPath(), $manipulator->getContents());
return true;
}
protected function interact(InputInterface $input, OutputInterface $output): void
{
}
/**
* @param bool $hardExit
* @return void
*/
public function revertComposerFile(bool $hardExit = true): void
{
$io = $this->getIO();
if ($this->newlyCreated) {
$io->writeError("\n".'<error>Installation failed, deleting '.$this->file.'.</error>');
unlink($this->json->getPath());
if (file_exists($this->lock)) {
unlink($this->lock);
}
} else {
$msg = ' to its ';
if ($this->lockBackup) {
$msg = ' and '.$this->lock.' to their ';
}
$io->writeError("\n".'<error>Installation failed, reverting '.$this->file.$msg.'original content.</error>');
file_put_contents($this->json->getPath(), $this->composerBackup);
if ($this->lockBackup) {
file_put_contents($this->lock, $this->lockBackup);
}
}
if ($hardExit) {
exit(1);
}
}
}