PageRenderTime 57ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/drush/composer/vendor/composer/composer/src/Composer/Installer.php

https://bitbucket.org/kbasarab/kbasarab_vim
PHP | 1500 lines | 914 code | 199 blank | 387 comment | 170 complexity | 8055a5bf8adb2669ce77aa768fb50bf6 MD5 | raw file
Possible License(s): MIT

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer;
  12. use Composer\Autoload\AutoloadGenerator;
  13. use Composer\DependencyResolver\DefaultPolicy;
  14. use Composer\DependencyResolver\Operation\UpdateOperation;
  15. use Composer\DependencyResolver\Operation\InstallOperation;
  16. use Composer\DependencyResolver\Operation\UninstallOperation;
  17. use Composer\DependencyResolver\Operation\OperationInterface;
  18. use Composer\DependencyResolver\PolicyInterface;
  19. use Composer\DependencyResolver\Pool;
  20. use Composer\DependencyResolver\Request;
  21. use Composer\DependencyResolver\Rule;
  22. use Composer\DependencyResolver\Solver;
  23. use Composer\DependencyResolver\SolverProblemsException;
  24. use Composer\Downloader\DownloadManager;
  25. use Composer\EventDispatcher\EventDispatcher;
  26. use Composer\Installer\InstallationManager;
  27. use Composer\Installer\InstallerEvents;
  28. use Composer\Installer\NoopInstaller;
  29. use Composer\Installer\SuggestedPackagesReporter;
  30. use Composer\IO\IOInterface;
  31. use Composer\Package\AliasPackage;
  32. use Composer\Package\CompletePackage;
  33. use Composer\Package\Link;
  34. use Composer\Semver\Constraint\Constraint;
  35. use Composer\Package\Locker;
  36. use Composer\Package\PackageInterface;
  37. use Composer\Package\RootPackageInterface;
  38. use Composer\Repository\CompositeRepository;
  39. use Composer\Repository\InstalledArrayRepository;
  40. use Composer\Repository\PlatformRepository;
  41. use Composer\Repository\RepositoryInterface;
  42. use Composer\Repository\RepositoryManager;
  43. use Composer\Repository\WritableRepositoryInterface;
  44. use Composer\Script\ScriptEvents;
  45. /**
  46. * @author Jordi Boggiano <j.boggiano@seld.be>
  47. * @author Beau Simensen <beau@dflydev.com>
  48. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  49. * @author Nils Adermann <naderman@naderman.de>
  50. */
  51. class Installer
  52. {
  53. /**
  54. * @var IOInterface
  55. */
  56. protected $io;
  57. /**
  58. * @var Config
  59. */
  60. protected $config;
  61. /**
  62. * @var RootPackageInterface
  63. */
  64. protected $package;
  65. /**
  66. * @var DownloadManager
  67. */
  68. protected $downloadManager;
  69. /**
  70. * @var RepositoryManager
  71. */
  72. protected $repositoryManager;
  73. /**
  74. * @var Locker
  75. */
  76. protected $locker;
  77. /**
  78. * @var InstallationManager
  79. */
  80. protected $installationManager;
  81. /**
  82. * @var EventDispatcher
  83. */
  84. protected $eventDispatcher;
  85. /**
  86. * @var AutoloadGenerator
  87. */
  88. protected $autoloadGenerator;
  89. protected $preferSource = false;
  90. protected $preferDist = false;
  91. protected $optimizeAutoloader = false;
  92. protected $classMapAuthoritative = false;
  93. protected $devMode = false;
  94. protected $dryRun = false;
  95. protected $verbose = false;
  96. protected $update = false;
  97. protected $dumpAutoloader = true;
  98. protected $runScripts = true;
  99. protected $ignorePlatformReqs = false;
  100. protected $preferStable = false;
  101. protected $preferLowest = false;
  102. /**
  103. * Array of package names/globs flagged for update
  104. *
  105. * @var array|null
  106. */
  107. protected $updateWhitelist = null;
  108. protected $whitelistDependencies = false;
  109. /**
  110. * @var SuggestedPackagesReporter
  111. */
  112. protected $suggestedPackagesReporter;
  113. /**
  114. * @var RepositoryInterface
  115. */
  116. protected $additionalInstalledRepository;
  117. /**
  118. * Constructor
  119. *
  120. * @param IOInterface $io
  121. * @param Config $config
  122. * @param RootPackageInterface $package
  123. * @param DownloadManager $downloadManager
  124. * @param RepositoryManager $repositoryManager
  125. * @param Locker $locker
  126. * @param InstallationManager $installationManager
  127. * @param EventDispatcher $eventDispatcher
  128. * @param AutoloadGenerator $autoloadGenerator
  129. */
  130. public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
  131. {
  132. $this->io = $io;
  133. $this->config = $config;
  134. $this->package = $package;
  135. $this->downloadManager = $downloadManager;
  136. $this->repositoryManager = $repositoryManager;
  137. $this->locker = $locker;
  138. $this->installationManager = $installationManager;
  139. $this->eventDispatcher = $eventDispatcher;
  140. $this->autoloadGenerator = $autoloadGenerator;
  141. }
  142. /**
  143. * Run installation (or update)
  144. *
  145. * @throws \Exception
  146. * @return int 0 on success or a positive error code on failure
  147. */
  148. public function run()
  149. {
  150. // Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands
  151. // of PHP objects, the GC can spend quite some time walking the tree of references looking
  152. // for stuff to collect while there is nothing to collect. This slows things down dramatically
  153. // and turning it off results in much better performance. Do not try this at home however.
  154. gc_collect_cycles();
  155. gc_disable();
  156. // Force update if there is no lock file present
  157. if (!$this->update && !$this->locker->isLocked()) {
  158. $this->update = true;
  159. }
  160. if ($this->dryRun) {
  161. $this->verbose = true;
  162. $this->runScripts = false;
  163. $this->installationManager->addInstaller(new NoopInstaller);
  164. $this->mockLocalRepositories($this->repositoryManager);
  165. }
  166. if ($this->runScripts) {
  167. // dispatch pre event
  168. $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
  169. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  170. }
  171. $this->downloadManager->setPreferSource($this->preferSource);
  172. $this->downloadManager->setPreferDist($this->preferDist);
  173. // clone root package to have one in the installed repo that does not require anything
  174. // we don't want it to be uninstallable, but its requirements should not conflict
  175. // with the lock file for example
  176. $installedRootPackage = clone $this->package;
  177. $installedRootPackage->setRequires(array());
  178. $installedRootPackage->setDevRequires(array());
  179. // create installed repo, this contains all local packages + platform packages (php & extensions)
  180. $localRepo = $this->repositoryManager->getLocalRepository();
  181. if ($this->update) {
  182. $platformOverrides = $this->config->get('platform') ?: array();
  183. } else {
  184. $platformOverrides = $this->locker->getPlatformOverrides();
  185. }
  186. $platformRepo = new PlatformRepository(array(), $platformOverrides);
  187. $repos = array(
  188. $localRepo,
  189. new InstalledArrayRepository(array($installedRootPackage)),
  190. $platformRepo,
  191. );
  192. $installedRepo = new CompositeRepository($repos);
  193. if ($this->additionalInstalledRepository) {
  194. $installedRepo->addRepository($this->additionalInstalledRepository);
  195. }
  196. $aliases = $this->getRootAliases();
  197. $this->aliasPlatformPackages($platformRepo, $aliases);
  198. if (!$this->suggestedPackagesReporter) {
  199. $this->suggestedPackagesReporter = new SuggestedPackagesReporter($this->io);
  200. }
  201. try {
  202. $res = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode);
  203. if ($res !== 0) {
  204. return $res;
  205. }
  206. } catch (\Exception $e) {
  207. if (!$this->dryRun) {
  208. $this->installationManager->notifyInstalls($this->io);
  209. }
  210. throw $e;
  211. }
  212. if (!$this->dryRun) {
  213. $this->installationManager->notifyInstalls($this->io);
  214. }
  215. // output suggestions if we're in dev mode
  216. if ($this->devMode) {
  217. $this->suggestedPackagesReporter->output($installedRepo);
  218. }
  219. # Find abandoned packages and warn user
  220. foreach ($localRepo->getPackages() as $package) {
  221. if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
  222. continue;
  223. }
  224. $replacement = (is_string($package->getReplacementPackage()))
  225. ? 'Use ' . $package->getReplacementPackage() . ' instead'
  226. : 'No replacement was suggested';
  227. $this->io->writeError(
  228. sprintf(
  229. "<warning>Package %s is abandoned, you should avoid using it. %s.</warning>",
  230. $package->getPrettyName(),
  231. $replacement
  232. )
  233. );
  234. }
  235. if (!$this->dryRun) {
  236. // write lock
  237. if ($this->update) {
  238. $localRepo->reload();
  239. // if this is not run in dev mode and the root has dev requires, the lock must
  240. // contain null to prevent dev installs from a non-dev lock
  241. $devPackages = ($this->devMode || !$this->package->getDevRequires()) ? array() : null;
  242. // split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
  243. if ($this->devMode && $this->package->getDevRequires()) {
  244. $policy = $this->createPolicy();
  245. $pool = $this->createPool(true);
  246. $pool->addRepository($installedRepo, $aliases);
  247. // creating requirements request
  248. $request = $this->createRequest($this->package, $platformRepo);
  249. $request->updateAll();
  250. foreach ($this->package->getRequires() as $link) {
  251. $request->install($link->getTarget(), $link->getConstraint());
  252. }
  253. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request);
  254. $solver = new Solver($policy, $pool, $installedRepo, $this->io);
  255. $ops = $solver->solve($request, $this->ignorePlatformReqs);
  256. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops);
  257. foreach ($ops as $op) {
  258. if ($op->getJobType() === 'uninstall') {
  259. $devPackages[] = $op->getPackage();
  260. }
  261. }
  262. }
  263. $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
  264. $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
  265. $updatedLock = $this->locker->setLockData(
  266. array_diff($localRepo->getCanonicalPackages(), (array) $devPackages),
  267. $devPackages,
  268. $platformReqs,
  269. $platformDevReqs,
  270. $aliases,
  271. $this->package->getMinimumStability(),
  272. $this->package->getStabilityFlags(),
  273. $this->preferStable || $this->package->getPreferStable(),
  274. $this->preferLowest,
  275. $this->config->get('platform') ?: array()
  276. );
  277. if ($updatedLock) {
  278. $this->io->writeError('<info>Writing lock file</info>');
  279. }
  280. }
  281. if ($this->dumpAutoloader) {
  282. // write autoloader
  283. if ($this->optimizeAutoloader) {
  284. $this->io->writeError('<info>Generating optimized autoload files</info>');
  285. } else {
  286. $this->io->writeError('<info>Generating autoload files</info>');
  287. }
  288. $this->autoloadGenerator->setDevMode($this->devMode);
  289. $this->autoloadGenerator->setClassMapAuthoritative($this->classMapAuthoritative);
  290. $this->autoloadGenerator->setRunScripts($this->runScripts);
  291. $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
  292. }
  293. if ($this->runScripts) {
  294. // dispatch post event
  295. $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
  296. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  297. }
  298. $vendorDir = $this->config->get('vendor-dir');
  299. if (is_dir($vendorDir)) {
  300. // suppress errors as this fails sometimes on OSX for no apparent reason
  301. // see https://github.com/composer/composer/issues/4070#issuecomment-129792748
  302. @touch($vendorDir);
  303. }
  304. }
  305. // re-enable GC except on HHVM which triggers a warning here
  306. if (!defined('HHVM_VERSION')) {
  307. gc_enable();
  308. }
  309. return 0;
  310. }
  311. /**
  312. * @param RepositoryInterface $localRepo
  313. * @param RepositoryInterface $installedRepo
  314. * @param PlatformRepository $platformRepo
  315. * @param array $aliases
  316. * @param bool $withDevReqs
  317. * @return int
  318. */
  319. protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $withDevReqs)
  320. {
  321. // init vars
  322. $lockedRepository = null;
  323. $repositories = null;
  324. // initialize locked repo if we are installing from lock or in a partial update
  325. // and a lock file is present as we need to force install non-whitelisted lock file
  326. // packages in that case
  327. if (!$this->update || (!empty($this->updateWhitelist) && $this->locker->isLocked())) {
  328. try {
  329. $lockedRepository = $this->locker->getLockedRepository($withDevReqs);
  330. } catch (\RuntimeException $e) {
  331. // if there are dev requires, then we really can not install
  332. if ($this->package->getDevRequires()) {
  333. throw $e;
  334. }
  335. // no require-dev in composer.json and the lock file was created with no dev info, so skip them
  336. $lockedRepository = $this->locker->getLockedRepository();
  337. }
  338. }
  339. $this->whitelistUpdateDependencies(
  340. $localRepo,
  341. $withDevReqs,
  342. $this->package->getRequires(),
  343. $this->package->getDevRequires()
  344. );
  345. $this->io->writeError('<info>Loading composer repositories with package information</info>');
  346. // creating repository pool
  347. $policy = $this->createPolicy();
  348. $pool = $this->createPool($withDevReqs, $this->update ? null : $lockedRepository);
  349. $pool->addRepository($installedRepo, $aliases);
  350. if ($this->update) {
  351. $repositories = $this->repositoryManager->getRepositories();
  352. foreach ($repositories as $repository) {
  353. $pool->addRepository($repository, $aliases);
  354. }
  355. }
  356. // Add the locked repository after the others in case we are doing a
  357. // partial update so missing packages can be found there still.
  358. // For installs from lock it's the only one added so it is first
  359. if ($lockedRepository) {
  360. $pool->addRepository($lockedRepository, $aliases);
  361. }
  362. // creating requirements request
  363. $request = $this->createRequest($this->package, $platformRepo);
  364. if ($this->update) {
  365. // remove unstable packages from the localRepo if they don't match the current stability settings
  366. $removedUnstablePackages = array();
  367. foreach ($localRepo->getPackages() as $package) {
  368. if (
  369. !$pool->isPackageAcceptable($package->getNames(), $package->getStability())
  370. && $this->installationManager->isPackageInstalled($localRepo, $package)
  371. ) {
  372. $removedUnstablePackages[$package->getName()] = true;
  373. $request->remove($package->getName(), new Constraint('=', $package->getVersion()));
  374. }
  375. }
  376. $this->io->writeError('<info>Updating dependencies'.($withDevReqs ? ' (including require-dev)' : '').'</info>');
  377. $request->updateAll();
  378. if ($withDevReqs) {
  379. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  380. } else {
  381. $links = $this->package->getRequires();
  382. }
  383. foreach ($links as $link) {
  384. $request->install($link->getTarget(), $link->getConstraint());
  385. }
  386. // if the updateWhitelist is enabled, packages not in it are also fixed
  387. // to the version specified in the lock, or their currently installed version
  388. if ($this->updateWhitelist) {
  389. $currentPackages = $this->getCurrentPackages($withDevReqs, $installedRepo);
  390. // collect packages to fixate from root requirements as well as installed packages
  391. $candidates = array();
  392. foreach ($links as $link) {
  393. $candidates[$link->getTarget()] = true;
  394. }
  395. foreach ($localRepo->getPackages() as $package) {
  396. $candidates[$package->getName()] = true;
  397. }
  398. // fix them to the version in lock (or currently installed) if they are not updateable
  399. foreach ($candidates as $candidate => $dummy) {
  400. foreach ($currentPackages as $curPackage) {
  401. if ($curPackage->getName() === $candidate) {
  402. if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
  403. $constraint = new Constraint('=', $curPackage->getVersion());
  404. $request->install($curPackage->getName(), $constraint);
  405. }
  406. break;
  407. }
  408. }
  409. }
  410. }
  411. } else {
  412. $this->io->writeError('<info>Installing dependencies'.($withDevReqs ? ' (including require-dev)' : '').' from lock file</info>');
  413. if (!$this->locker->isFresh()) {
  414. $this->io->writeError('<warning>Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.</warning>', true, IOInterface::QUIET);
  415. }
  416. foreach ($lockedRepository->getPackages() as $package) {
  417. $version = $package->getVersion();
  418. if (isset($aliases[$package->getName()][$version])) {
  419. $version = $aliases[$package->getName()][$version]['alias_normalized'];
  420. }
  421. $constraint = new Constraint('=', $version);
  422. $constraint->setPrettyString($package->getPrettyVersion());
  423. $request->install($package->getName(), $constraint);
  424. }
  425. foreach ($this->locker->getPlatformRequirements($withDevReqs) as $link) {
  426. $request->install($link->getTarget(), $link->getConstraint());
  427. }
  428. }
  429. // force dev packages to have the latest links if we update or install from a (potentially new) lock
  430. $this->processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, $withDevReqs, 'force-links');
  431. // solve dependencies
  432. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request);
  433. $solver = new Solver($policy, $pool, $installedRepo, $this->io);
  434. try {
  435. $operations = $solver->solve($request, $this->ignorePlatformReqs);
  436. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request, $operations);
  437. } catch (SolverProblemsException $e) {
  438. $this->io->writeError('<error>Your requirements could not be resolved to an installable set of packages.</error>', true, IOInterface::QUIET);
  439. $this->io->writeError($e->getMessage());
  440. return max(1, $e->getCode());
  441. }
  442. $this->io->writeError("Analyzed ".count($pool)." packages to resolve dependencies", true, IOInterface::VERBOSE);
  443. $this->io->writeError("Analyzed ".$solver->getRuleSetSize()." rules to resolve dependencies", true, IOInterface::VERBOSE);
  444. // force dev packages to be updated if we update or install from a (potentially new) lock
  445. $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, $withDevReqs, 'force-updates', $operations);
  446. // execute operations
  447. if (!$operations) {
  448. $this->io->writeError('Nothing to install or update');
  449. }
  450. $operations = $this->movePluginsToFront($operations);
  451. $operations = $this->moveUninstallsToFront($operations);
  452. foreach ($operations as $operation) {
  453. // collect suggestions
  454. if ('install' === $operation->getJobType()) {
  455. $this->suggestedPackagesReporter->addSuggestionsFromPackage($operation->getPackage());
  456. }
  457. // updating, force dev packages' references if they're in root package refs
  458. if ($this->update) {
  459. $package = null;
  460. if ('update' === $operation->getJobType()) {
  461. $package = $operation->getTargetPackage();
  462. } elseif ('install' === $operation->getJobType()) {
  463. $package = $operation->getPackage();
  464. }
  465. if ($package && $package->isDev()) {
  466. $references = $this->package->getReferences();
  467. if (isset($references[$package->getName()])) {
  468. $package->setSourceReference($references[$package->getName()]);
  469. $package->setDistReference($references[$package->getName()]);
  470. }
  471. }
  472. if ('update' === $operation->getJobType()
  473. && $operation->getTargetPackage()->isDev()
  474. && $operation->getTargetPackage()->getVersion() === $operation->getInitialPackage()->getVersion()
  475. && (!$operation->getTargetPackage()->getSourceReference() || $operation->getTargetPackage()->getSourceReference() === $operation->getInitialPackage()->getSourceReference())
  476. && (!$operation->getTargetPackage()->getDistReference() || $operation->getTargetPackage()->getDistReference() === $operation->getInitialPackage()->getDistReference())
  477. ) {
  478. $this->io->writeError(' - Skipping update of '. $operation->getTargetPackage()->getPrettyName().' to the same reference-locked version', true, IOInterface::DEBUG);
  479. $this->io->writeError('', true, IOInterface::DEBUG);
  480. continue;
  481. }
  482. }
  483. $event = 'Composer\Installer\PackageEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType());
  484. if (defined($event) && $this->runScripts) {
  485. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
  486. }
  487. // output non-alias ops in dry run, output alias ops in debug verbosity
  488. if ($this->dryRun && false === strpos($operation->getJobType(), 'Alias')) {
  489. $this->io->writeError(' - ' . $operation);
  490. $this->io->writeError('');
  491. } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
  492. $this->io->writeError(' - ' . $operation);
  493. $this->io->writeError('');
  494. }
  495. $this->installationManager->execute($localRepo, $operation);
  496. // output reasons why the operation was ran, only for install/update operations
  497. if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) {
  498. $reason = $operation->getReason();
  499. if ($reason instanceof Rule) {
  500. switch ($reason->getReason()) {
  501. case Rule::RULE_JOB_INSTALL:
  502. $this->io->writeError(' REASON: Required by the root package: '.$reason->getPrettyString($pool));
  503. $this->io->writeError('');
  504. break;
  505. case Rule::RULE_PACKAGE_REQUIRES:
  506. $this->io->writeError(' REASON: '.$reason->getPrettyString($pool));
  507. $this->io->writeError('');
  508. break;
  509. }
  510. }
  511. }
  512. $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($operation->getJobType());
  513. if (defined($event) && $this->runScripts) {
  514. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
  515. }
  516. if (!$this->dryRun) {
  517. $localRepo->write();
  518. }
  519. }
  520. if (!$this->dryRun) {
  521. // force source/dist urls to be updated for all packages
  522. $this->processPackageUrls($pool, $policy, $localRepo, $repositories);
  523. $localRepo->write();
  524. }
  525. return 0;
  526. }
  527. /**
  528. * Workaround: if your packages depend on plugins, we must be sure
  529. * that those are installed / updated first; else it would lead to packages
  530. * being installed multiple times in different folders, when running Composer
  531. * twice.
  532. *
  533. * While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
  534. * it at least fixes the symptoms and makes usage of composer possible (again)
  535. * in such scenarios.
  536. *
  537. * @param OperationInterface[] $operations
  538. * @return OperationInterface[] reordered operation list
  539. */
  540. private function movePluginsToFront(array $operations)
  541. {
  542. $installerOps = array();
  543. foreach ($operations as $idx => $op) {
  544. if ($op instanceof InstallOperation) {
  545. $package = $op->getPackage();
  546. } elseif ($op instanceof UpdateOperation) {
  547. $package = $op->getTargetPackage();
  548. } else {
  549. continue;
  550. }
  551. if ($package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer') {
  552. // ignore requirements to platform or composer-plugin-api
  553. $requires = array_keys($package->getRequires());
  554. foreach ($requires as $index => $req) {
  555. if ($req === 'composer-plugin-api' || preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  556. unset($requires[$index]);
  557. }
  558. }
  559. // if there are no other requirements, move the plugin to the top of the op list
  560. if (!count($requires)) {
  561. $installerOps[] = $op;
  562. unset($operations[$idx]);
  563. }
  564. }
  565. }
  566. return array_merge($installerOps, $operations);
  567. }
  568. /**
  569. * Removals of packages should be executed before installations in
  570. * case two packages resolve to the same path (due to custom installers)
  571. *
  572. * @param OperationInterface[] $operations
  573. * @return OperationInterface[] reordered operation list
  574. */
  575. private function moveUninstallsToFront(array $operations)
  576. {
  577. $uninstOps = array();
  578. foreach ($operations as $idx => $op) {
  579. if ($op instanceof UninstallOperation) {
  580. $uninstOps[] = $op;
  581. unset($operations[$idx]);
  582. }
  583. }
  584. return array_merge($uninstOps, $operations);
  585. }
  586. /**
  587. * @param bool $withDevReqs
  588. * @param RepositoryInterface|null $lockedRepository
  589. * @return Pool
  590. */
  591. private function createPool($withDevReqs, RepositoryInterface $lockedRepository = null)
  592. {
  593. if ($this->update) {
  594. $minimumStability = $this->package->getMinimumStability();
  595. $stabilityFlags = $this->package->getStabilityFlags();
  596. $requires = $this->package->getRequires();
  597. if ($withDevReqs) {
  598. $requires = array_merge($requires, $this->package->getDevRequires());
  599. }
  600. } else {
  601. $minimumStability = $this->locker->getMinimumStability();
  602. $stabilityFlags = $this->locker->getStabilityFlags();
  603. $requires = array();
  604. foreach ($lockedRepository->getPackages() as $package) {
  605. $constraint = new Constraint('=', $package->getVersion());
  606. $constraint->setPrettyString($package->getPrettyVersion());
  607. $requires[$package->getName()] = $constraint;
  608. }
  609. }
  610. $rootConstraints = array();
  611. foreach ($requires as $req => $constraint) {
  612. // skip platform requirements from the root package to avoid filtering out existing platform packages
  613. if ($this->ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  614. continue;
  615. }
  616. if ($constraint instanceof Link) {
  617. $rootConstraints[$req] = $constraint->getConstraint();
  618. } else {
  619. $rootConstraints[$req] = $constraint;
  620. }
  621. }
  622. return new Pool($minimumStability, $stabilityFlags, $rootConstraints);
  623. }
  624. /**
  625. * @return DefaultPolicy
  626. */
  627. private function createPolicy()
  628. {
  629. $preferStable = null;
  630. $preferLowest = null;
  631. if (!$this->update) {
  632. $preferStable = $this->locker->getPreferStable();
  633. $preferLowest = $this->locker->getPreferLowest();
  634. }
  635. // old lock file without prefer stable/lowest will return null
  636. // so in this case we use the composer.json info
  637. if (null === $preferStable) {
  638. $preferStable = $this->preferStable || $this->package->getPreferStable();
  639. }
  640. if (null === $preferLowest) {
  641. $preferLowest = $this->preferLowest;
  642. }
  643. return new DefaultPolicy($preferStable, $preferLowest);
  644. }
  645. /**
  646. * @param RootPackageInterface $rootPackage
  647. * @param PlatformRepository $platformRepo
  648. * @return Request
  649. */
  650. private function createRequest(RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
  651. {
  652. $request = new Request();
  653. $constraint = new Constraint('=', $rootPackage->getVersion());
  654. $constraint->setPrettyString($rootPackage->getPrettyVersion());
  655. $request->install($rootPackage->getName(), $constraint);
  656. $fixedPackages = $platformRepo->getPackages();
  657. if ($this->additionalInstalledRepository) {
  658. $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
  659. $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
  660. }
  661. // fix the version of all platform packages + additionally installed packages
  662. // to prevent the solver trying to remove or update those
  663. $provided = $rootPackage->getProvides();
  664. foreach ($fixedPackages as $package) {
  665. $constraint = new Constraint('=', $package->getVersion());
  666. $constraint->setPrettyString($package->getPrettyVersion());
  667. // skip platform packages that are provided by the root package
  668. if ($package->getRepository() !== $platformRepo
  669. || !isset($provided[$package->getName()])
  670. || !$provided[$package->getName()]->getConstraint()->matches($constraint)
  671. ) {
  672. $request->fix($package->getName(), $constraint);
  673. }
  674. }
  675. return $request;
  676. }
  677. /**
  678. * @param WritableRepositoryInterface $localRepo
  679. * @param Pool $pool
  680. * @param PolicyInterface $policy
  681. * @param array $repositories
  682. * @param RepositoryInterface $installedRepo
  683. * @param RepositoryInterface $lockedRepository
  684. * @param bool $withDevReqs
  685. * @param string $task
  686. * @param array|null $operations
  687. * @return array
  688. */
  689. private function processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, $withDevReqs, $task, array $operations = null)
  690. {
  691. if ($task === 'force-updates' && null === $operations) {
  692. throw new \InvalidArgumentException('Missing operations argument');
  693. }
  694. if ($task === 'force-links') {
  695. $operations = array();
  696. }
  697. if ($this->update && $this->updateWhitelist) {
  698. $currentPackages = $this->getCurrentPackages($withDevReqs, $installedRepo);
  699. }
  700. foreach ($localRepo->getCanonicalPackages() as $package) {
  701. // skip non-dev packages
  702. if (!$package->isDev()) {
  703. continue;
  704. }
  705. // skip packages that will be updated/uninstalled
  706. foreach ($operations as $operation) {
  707. if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
  708. || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package))
  709. ) {
  710. continue 2;
  711. }
  712. }
  713. if ($this->update) {
  714. // skip package if the whitelist is enabled and it is not in it
  715. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  716. // check if non-updateable packages are out of date compared to the lock file to ensure we don't corrupt it
  717. foreach ($currentPackages as $curPackage) {
  718. if ($curPackage->isDev() && $curPackage->getName() === $package->getName() && $curPackage->getVersion() === $package->getVersion()) {
  719. if ($task === 'force-links') {
  720. $package->setRequires($curPackage->getRequires());
  721. $package->setConflicts($curPackage->getConflicts());
  722. $package->setProvides($curPackage->getProvides());
  723. $package->setReplaces($curPackage->getReplaces());
  724. } elseif ($task === 'force-updates') {
  725. if (($curPackage->getSourceReference() && $curPackage->getSourceReference() !== $package->getSourceReference())
  726. || ($curPackage->getDistReference() && $curPackage->getDistReference() !== $package->getDistReference())
  727. ) {
  728. $operations[] = new UpdateOperation($package, $curPackage);
  729. }
  730. }
  731. break;
  732. }
  733. }
  734. continue;
  735. }
  736. // find similar packages (name/version) in all repositories
  737. $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion()));
  738. foreach ($matches as $index => $match) {
  739. // skip local packages
  740. if (!in_array($match->getRepository(), $repositories, true)) {
  741. unset($matches[$index]);
  742. continue;
  743. }
  744. // skip providers/replacers
  745. if ($match->getName() !== $package->getName()) {
  746. unset($matches[$index]);
  747. continue;
  748. }
  749. $matches[$index] = $match->getId();
  750. }
  751. // select preferred package according to policy rules
  752. if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) {
  753. $newPackage = $pool->literalToPackage($matches[0]);
  754. if ($task === 'force-links' && $newPackage) {
  755. $package->setRequires($newPackage->getRequires());
  756. $package->setConflicts($newPackage->getConflicts());
  757. $package->setProvides($newPackage->getProvides());
  758. $package->setReplaces($newPackage->getReplaces());
  759. }
  760. if ($task === 'force-updates' && $newPackage && (
  761. (($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference())
  762. || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference())
  763. )
  764. )) {
  765. $operations[] = new UpdateOperation($package, $newPackage);
  766. }
  767. }
  768. if ($task === 'force-updates') {
  769. // force installed package to update to referenced version in root package if it does not match the installed version
  770. $references = $this->package->getReferences();
  771. if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) {
  772. // changing the source ref to update to will be handled in the operations loop below
  773. $operations[] = new UpdateOperation($package, clone $package);
  774. }
  775. }
  776. } else {
  777. // force update to locked version if it does not match the installed version
  778. foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) {
  779. if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) {
  780. if ($task === 'force-links') {
  781. $package->setRequires($lockedPackage->getRequires());
  782. $package->setConflicts($lockedPackage->getConflicts());
  783. $package->setProvides($lockedPackage->getProvides());
  784. $package->setReplaces($lockedPackage->getReplaces());
  785. } elseif ($task === 'force-updates') {
  786. if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference())
  787. || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference())
  788. ) {
  789. $operations[] = new UpdateOperation($package, $lockedPackage);
  790. }
  791. }
  792. break;
  793. }
  794. }
  795. }
  796. }
  797. return $operations;
  798. }
  799. /**
  800. * Loads the most "current" list of packages that are installed meaning from lock ideally or from installed repo as fallback
  801. * @param bool $withDevReqs
  802. * @param RepositoryInterface $installedRepo
  803. * @return array
  804. */
  805. private function getCurrentPackages($withDevReqs, $installedRepo)
  806. {
  807. if ($this->locker->isLocked()) {
  808. try {
  809. return $this->locker->getLockedRepository($withDevReqs)->getPackages();
  810. } catch (\RuntimeException $e) {
  811. // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
  812. return $this->locker->getLockedRepository()->getPackages();
  813. }
  814. }
  815. return $installedRepo->getPackages();
  816. }
  817. /**
  818. * @return array
  819. */
  820. private function getRootAliases()
  821. {
  822. if ($this->update) {
  823. $aliases = $this->package->getAliases();
  824. } else {
  825. $aliases = $this->locker->getAliases();
  826. }
  827. $normalizedAliases = array();
  828. foreach ($aliases as $alias) {
  829. $normalizedAliases[$alias['package']][$alias['version']] = array(
  830. 'alias' => $alias['alias'],
  831. 'alias_normalized' => $alias['alias_normalized'],
  832. );
  833. }
  834. return $normalizedAliases;
  835. }
  836. /**
  837. * @param Pool $pool
  838. * @param PolicyInterface $policy
  839. * @param WritableRepositoryInterface $localRepo
  840. * @param array $repositories
  841. */
  842. private function processPackageUrls($pool, $policy, $localRepo, $repositories)
  843. {
  844. if (!$this->update) {
  845. return;
  846. }
  847. foreach ($localRepo->getCanonicalPackages() as $package) {
  848. // find similar packages (name/version) in all repositories
  849. $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion()));
  850. foreach ($matches as $index => $match) {
  851. // skip local packages
  852. if (!in_array($match->getRepository(), $repositories, true)) {
  853. unset($matches[$index]);
  854. continue;
  855. }
  856. // skip providers/replacers
  857. if ($match->getName() !== $package->getName()) {
  858. unset($matches[$index]);
  859. continue;
  860. }
  861. $matches[$index] = $match->getId();
  862. }
  863. // select preferred package according to policy rules
  864. if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) {
  865. $newPackage = $pool->literalToPackage($matches[0]);
  866. // update the dist and source URLs
  867. $sourceUrl = $package->getSourceUrl();
  868. $newSourceUrl = $newPackage->getSourceUrl();
  869. if ($sourceUrl !== $newSourceUrl) {
  870. $package->setSourceType($newPackage->getSourceType());
  871. $package->setSourceUrl($newSourceUrl);
  872. $package->setSourceReference($newPackage->getSourceReference());
  873. }
  874. // only update dist url for github/bitbucket dists as they use a combination of dist url + dist reference to install
  875. // but for other urls this is ambiguous and could result in bad outcomes
  876. if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com)/}', $newPackage->getDistUrl())) {
  877. $package->setDistUrl($newPackage->getDistUrl());
  878. }
  879. }
  880. }
  881. }
  882. /**
  883. * @param PlatformRepository $platformRepo
  884. * @param array $aliases
  885. */
  886. private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases)
  887. {
  888. foreach ($aliases as $package => $versions) {
  889. foreach ($versions as $version => $alias) {
  890. $packages = $platformRepo->findPackages($package, $version);
  891. foreach ($packages as $package) {
  892. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  893. $aliasPackage->setRootPackageAlias(true);
  894. $platformRepo->addPackage($aliasPackage);
  895. }
  896. }
  897. }
  898. }
  899. /**
  900. * @param PackageInterface $package
  901. * @return bool
  902. */
  903. private function isUpdateable(PackageInterface $package)
  904. {
  905. if (!$this->updateWhitelist) {
  906. throw new \LogicException('isUpdateable should only be called when a whitelist is present');
  907. }
  908. foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
  909. $patternRegexp = $this->packageNameToRegexp($whiteListedPattern);
  910. if (preg_match($patternRegexp, $package->getName())) {
  911. return true;
  912. }
  913. }
  914. return false;
  915. }
  916. /**
  917. * Build a regexp from a package name, expanding * globs as required
  918. *
  919. * @param string $whiteListedPattern
  920. * @return string
  921. */
  922. private function packageNameToRegexp($whiteListedPattern)
  923. {
  924. $cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern));
  925. return "{^" . $cleanedWhiteListedPattern . "$}i";
  926. }
  927. /**
  928. * @param array $links
  929. * @return array
  930. */
  931. private function extractPlatformRequirements($links)
  932. {
  933. $platformReqs = array();
  934. foreach ($links as $link) {
  935. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  936. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  937. }
  938. }
  939. return $platformReqs;
  940. }
  941. /**
  942. * Adds all dependencies of the update whitelist to the whitelist, too.
  943. *
  944. * Packages which are listed as requirements in the root package will be
  945. * skipped including their dependencies, unless they are listed in the
  946. * update whitelist themselves.
  947. *
  948. * @param RepositoryInterface $localRepo
  949. * @param bool $devMode
  950. * @param array $rootRequires An array of links to packages in require of the root package
  951. * @param array $rootDevRequires An array of links to packages in require-dev of the root package
  952. */
  953. private function whitelistUpdateDependencies($localRepo, $devMode, array $rootRequires, array $rootDevRequires)
  954. {
  955. if (!$this->updateWhitelist) {
  956. return;
  957. }
  958. $requiredPackageNames = array();
  959. foreach (array_merge($rootRequires, $rootDevRequires) as $require) {
  960. $requiredPackageNames[] = $require->getTarget();
  961. }
  962. if ($devMode) {
  963. $rootRequires = array_merge($rootRequires, $rootDevRequires);
  964. }
  965. $skipPackages = array();
  966. foreach ($rootRequires as $require) {
  967. $skipPackages[$require->getTarget()] = true;
  968. }
  969. $pool = new Pool;
  970. $pool->addRepository($localRepo);
  971. $seen = array();
  972. $rootRequiredPackageNames = array_keys($rootRequires);
  973. foreach ($this->updateWhitelist as $packageName => $void) {
  974. $packageQueue = new \SplQueue;
  975. $depPackages = $pool->whatProvides($packageName);
  976. $nameMatchesRequiredPackage = in_array($packageName, $requiredPackageNames, true);
  977. // check if the name is a glob pattern that did not match directly
  978. if (!$nameMatchesRequiredPackage) {
  979. $whitelistPatternRegexp = $this->packageNameToRegexp($packageName);
  980. foreach ($rootRequiredPackageNames as $rootRequiredPackageName) {
  981. if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) {
  982. $nameMatchesRequiredPackage = true;
  983. break;
  984. }
  985. }
  986. }
  987. if (count($depPackages) == 0 && !$nameMatchesRequiredPackage && !in_array($packageName, array('nothing', 'lock'))) {
  988. $this->io->writeError('<warning>Package "' . $packageName . '" listed for update is not installed. Ignoring.</warning>');
  989. }
  990. foreach ($depPackages as $depPackage) {
  991. $packageQueue->enqueue($depPackage);
  992. }
  993. while (!$packageQueue->isEmpty()) {
  994. $package = $packageQueue->dequeue();
  995. if (isset($seen[$package->getId()])) {
  996. continue;
  997. }
  998. $seen[$package->getId()] = true;
  999. $this->updateWhitelist[$package->getName()] = true;
  1000. if (!$this->whitelistDependencies) {
  1001. continue;
  1002. }
  1003. $requires = $package->getRequires();
  1004. foreach ($requires as $require) {
  1005. $requirePackages = $pool->whatProvides($require->getTarget());
  1006. foreach ($requirePackages as $requirePackage) {
  1007. if (isset($this->updateWhitelist[$requirePackage->getName()])) {
  1008. continue;
  1009. }
  1010. if (isset($skipPackages[$requirePackage->getName()])) {
  1011. $this->io->writeError('<warning>Dependency "' . $requirePackage->getName() . '" is also a root requirement, but is not explicitly whitelisted. Ignoring.</warning>');
  1012. continue;
  1013. }
  1014. $packageQueue->enqueue($requirePackage);
  1015. }
  1016. }
  1017. }
  1018. }
  1019. }
  1020. /**
  1021. * Replace local repositories with InstalledArrayRepository instances
  1022. *
  1023. * This is to prevent any accidental modification of the existing repos on disk
  1024. *
  1025. * @param RepositoryMana…

Large files files are truncated, but you can click here to view the full file