Installer.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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\Pool;
  19. use Composer\DependencyResolver\Request;
  20. use Composer\DependencyResolver\Rule;
  21. use Composer\DependencyResolver\Solver;
  22. use Composer\DependencyResolver\SolverProblemsException;
  23. use Composer\Downloader\DownloadManager;
  24. use Composer\EventDispatcher\EventDispatcher;
  25. use Composer\Installer\InstallationManager;
  26. use Composer\Config;
  27. use Composer\Installer\NoopInstaller;
  28. use Composer\IO\IOInterface;
  29. use Composer\Json\JsonFile;
  30. use Composer\Package\AliasPackage;
  31. use Composer\Package\Link;
  32. use Composer\Package\LinkConstraint\VersionConstraint;
  33. use Composer\Package\Locker;
  34. use Composer\Package\PackageInterface;
  35. use Composer\Package\RootPackageInterface;
  36. use Composer\Repository\CompositeRepository;
  37. use Composer\Repository\InstalledArrayRepository;
  38. use Composer\Repository\InstalledFilesystemRepository;
  39. use Composer\Repository\PlatformRepository;
  40. use Composer\Repository\RepositoryInterface;
  41. use Composer\Repository\RepositoryManager;
  42. use Composer\Script\ScriptEvents;
  43. /**
  44. * @author Jordi Boggiano <j.boggiano@seld.be>
  45. * @author Beau Simensen <beau@dflydev.com>
  46. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  47. * @author Nils Adermann <naderman@naderman.de>
  48. */
  49. class Installer
  50. {
  51. /**
  52. * @var IOInterface
  53. */
  54. protected $io;
  55. /**
  56. * @var Config
  57. */
  58. protected $config;
  59. /**
  60. * @var RootPackageInterface
  61. */
  62. protected $package;
  63. /**
  64. * @var DownloadManager
  65. */
  66. protected $downloadManager;
  67. /**
  68. * @var RepositoryManager
  69. */
  70. protected $repositoryManager;
  71. /**
  72. * @var Locker
  73. */
  74. protected $locker;
  75. /**
  76. * @var InstallationManager
  77. */
  78. protected $installationManager;
  79. /**
  80. * @var EventDispatcher
  81. */
  82. protected $eventDispatcher;
  83. /**
  84. * @var AutoloadGenerator
  85. */
  86. protected $autoloadGenerator;
  87. protected $preferSource = false;
  88. protected $preferDist = false;
  89. protected $optimizeAutoloader = false;
  90. protected $devMode = false;
  91. protected $dryRun = false;
  92. protected $verbose = false;
  93. protected $update = false;
  94. protected $runScripts = true;
  95. protected $updateWhitelist = null;
  96. protected $whitelistDependencies = false;
  97. /**
  98. * @var array
  99. */
  100. protected $suggestedPackages;
  101. /**
  102. * @var RepositoryInterface
  103. */
  104. protected $additionalInstalledRepository;
  105. /**
  106. * Constructor
  107. *
  108. * @param IOInterface $io
  109. * @param Config $config
  110. * @param RootPackageInterface $package
  111. * @param DownloadManager $downloadManager
  112. * @param RepositoryManager $repositoryManager
  113. * @param Locker $locker
  114. * @param InstallationManager $installationManager
  115. * @param EventDispatcher $eventDispatcher
  116. * @param AutoloadGenerator $autoloadGenerator
  117. */
  118. public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
  119. {
  120. $this->io = $io;
  121. $this->config = $config;
  122. $this->package = $package;
  123. $this->downloadManager = $downloadManager;
  124. $this->repositoryManager = $repositoryManager;
  125. $this->locker = $locker;
  126. $this->installationManager = $installationManager;
  127. $this->eventDispatcher = $eventDispatcher;
  128. $this->autoloadGenerator = $autoloadGenerator;
  129. }
  130. /**
  131. * Run installation (or update)
  132. *
  133. * @return int 0 on success or a positive error code on failure
  134. */
  135. public function run()
  136. {
  137. if ($this->dryRun) {
  138. $this->verbose = true;
  139. $this->runScripts = false;
  140. $this->installationManager->addInstaller(new NoopInstaller);
  141. $this->mockLocalRepositories($this->repositoryManager);
  142. }
  143. // TODO remove this BC feature at some point
  144. // purge old require-dev packages to avoid conflicts with the new way of handling dev requirements
  145. $devRepo = new InstalledFilesystemRepository(new JsonFile($this->config->get('vendor-dir').'/composer/installed_dev.json'));
  146. if ($devRepo->getPackages()) {
  147. $this->io->write('<warning>BC Notice: Removing old dev packages to migrate to the new require-dev handling.</warning>');
  148. foreach ($devRepo->getPackages() as $package) {
  149. if ($this->installationManager->isPackageInstalled($devRepo, $package)) {
  150. $this->installationManager->uninstall($devRepo, new UninstallOperation($package));
  151. }
  152. }
  153. unlink($this->config->get('vendor-dir').'/composer/installed_dev.json');
  154. }
  155. unset($devRepo, $package);
  156. // end BC
  157. if ($this->runScripts) {
  158. // dispatch pre event
  159. $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
  160. $this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
  161. }
  162. $this->downloadManager->setPreferSource($this->preferSource);
  163. $this->downloadManager->setPreferDist($this->preferDist);
  164. // clone root package to have one in the installed repo that does not require anything
  165. // we don't want it to be uninstallable, but its requirements should not conflict
  166. // with the lock file for example
  167. $installedRootPackage = clone $this->package;
  168. $installedRootPackage->setRequires(array());
  169. $installedRootPackage->setDevRequires(array());
  170. // create installed repo, this contains all local packages + platform packages (php & extensions)
  171. $localRepo = $this->repositoryManager->getLocalRepository();
  172. $platformRepo = new PlatformRepository();
  173. $repos = array(
  174. $localRepo,
  175. new InstalledArrayRepository(array($installedRootPackage)),
  176. $platformRepo,
  177. );
  178. $installedRepo = new CompositeRepository($repos);
  179. if ($this->additionalInstalledRepository) {
  180. $installedRepo->addRepository($this->additionalInstalledRepository);
  181. }
  182. $aliases = $this->getRootAliases();
  183. $this->aliasPlatformPackages($platformRepo, $aliases);
  184. try {
  185. $this->suggestedPackages = array();
  186. $res = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode);
  187. if ($res !== 0) {
  188. return $res;
  189. }
  190. } catch (\Exception $e) {
  191. $this->installationManager->notifyInstalls();
  192. throw $e;
  193. }
  194. $this->installationManager->notifyInstalls();
  195. // output suggestions
  196. foreach ($this->suggestedPackages as $suggestion) {
  197. $target = $suggestion['target'];
  198. foreach ($installedRepo->getPackages() as $package) {
  199. if (in_array($target, $package->getNames())) {
  200. continue 2;
  201. }
  202. }
  203. $this->io->write($suggestion['source'].' suggests installing '.$suggestion['target'].' ('.$suggestion['reason'].')');
  204. }
  205. if (!$this->dryRun) {
  206. // write lock
  207. if ($this->update || !$this->locker->isLocked()) {
  208. $localRepo->reload();
  209. // if this is not run in dev mode and the root has dev requires, the lock must
  210. // contain null to prevent dev installs from a non-dev lock
  211. $devPackages = ($this->devMode || !$this->package->getDevRequires()) ? array() : null;
  212. // split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
  213. if ($this->devMode && $this->package->getDevRequires()) {
  214. $policy = $this->createPolicy();
  215. $pool = $this->createPool(true);
  216. $pool->addRepository($installedRepo, $aliases);
  217. // creating requirements request
  218. $request = $this->createRequest($pool, $this->package, $platformRepo);
  219. $request->updateAll();
  220. foreach ($this->package->getRequires() as $link) {
  221. $request->install($link->getTarget(), $link->getConstraint());
  222. }
  223. $solver = new Solver($policy, $pool, $installedRepo);
  224. $ops = $solver->solve($request);
  225. foreach ($ops as $op) {
  226. if ($op->getJobType() === 'uninstall') {
  227. $devPackages[] = $op->getPackage();
  228. }
  229. }
  230. }
  231. $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
  232. $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
  233. $updatedLock = $this->locker->setLockData(
  234. array_diff($localRepo->getCanonicalPackages(), (array) $devPackages),
  235. $devPackages,
  236. $platformReqs,
  237. $platformDevReqs,
  238. $aliases,
  239. $this->package->getMinimumStability(),
  240. $this->package->getStabilityFlags()
  241. );
  242. if ($updatedLock) {
  243. $this->io->write('<info>Writing lock file</info>');
  244. }
  245. }
  246. // write autoloader
  247. if ($this->optimizeAutoloader) {
  248. $this->io->write('<info>Generating optimized autoload files</info>');
  249. } else {
  250. $this->io->write('<info>Generating autoload files</info>');
  251. }
  252. $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
  253. if ($this->runScripts) {
  254. // dispatch post event
  255. $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
  256. $this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
  257. }
  258. }
  259. return 0;
  260. }
  261. protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $withDevReqs)
  262. {
  263. // init vars
  264. $lockedRepository = null;
  265. $repositories = null;
  266. // initialize locker to create aliased packages
  267. $installFromLock = false;
  268. if (!$this->update && $this->locker->isLocked()) {
  269. $installFromLock = true;
  270. try {
  271. $lockedRepository = $this->locker->getLockedRepository($withDevReqs);
  272. } catch (\RuntimeException $e) {
  273. // if there are dev requires, then we really can not install
  274. if ($this->package->getDevRequires()) {
  275. throw $e;
  276. }
  277. // no require-dev in composer.json and the lock file was created with no dev info, so skip them
  278. $lockedRepository = $this->locker->getLockedRepository();
  279. }
  280. }
  281. $this->whitelistUpdateDependencies(
  282. $localRepo,
  283. $withDevReqs,
  284. $this->package->getRequires(),
  285. $this->package->getDevRequires()
  286. );
  287. $this->io->write('<info>Loading composer repositories with package information</info>');
  288. // creating repository pool
  289. $policy = $this->createPolicy();
  290. $pool = $this->createPool($withDevReqs);
  291. $pool->addRepository($installedRepo, $aliases);
  292. if ($installFromLock) {
  293. $pool->addRepository($lockedRepository, $aliases);
  294. }
  295. if (!$installFromLock) {
  296. $repositories = $this->repositoryManager->getRepositories();
  297. foreach ($repositories as $repository) {
  298. $pool->addRepository($repository, $aliases);
  299. }
  300. }
  301. // creating requirements request
  302. $request = $this->createRequest($pool, $this->package, $platformRepo);
  303. if (!$installFromLock) {
  304. // remove unstable packages from the localRepo if they don't match the current stability settings
  305. $removedUnstablePackages = array();
  306. foreach ($localRepo->getPackages() as $package) {
  307. if (
  308. !$pool->isPackageAcceptable($package->getNames(), $package->getStability())
  309. && $this->installationManager->isPackageInstalled($localRepo, $package)
  310. ) {
  311. $removedUnstablePackages[$package->getName()] = true;
  312. $request->remove($package->getName(), new VersionConstraint('=', $package->getVersion()));
  313. }
  314. }
  315. }
  316. if ($this->update) {
  317. $this->io->write('<info>Updating dependencies'.($withDevReqs?' (including require-dev)':'').'</info>');
  318. $request->updateAll();
  319. if ($withDevReqs) {
  320. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  321. } else {
  322. $links = $this->package->getRequires();
  323. }
  324. foreach ($links as $link) {
  325. $request->install($link->getTarget(), $link->getConstraint());
  326. }
  327. // if the updateWhitelist is enabled, packages not in it are also fixed
  328. // to the version specified in the lock, or their currently installed version
  329. if ($this->updateWhitelist) {
  330. if ($this->locker->isLocked()) {
  331. try {
  332. $currentPackages = $this->locker->getLockedRepository($withDevReqs)->getPackages();
  333. } catch (\RuntimeException $e) {
  334. // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
  335. $currentPackages = $this->locker->getLockedRepository()->getPackages();
  336. }
  337. } else {
  338. $currentPackages = $installedRepo->getPackages();
  339. }
  340. // collect packages to fixate from root requirements as well as installed packages
  341. $candidates = array();
  342. foreach ($links as $link) {
  343. $candidates[$link->getTarget()] = true;
  344. }
  345. foreach ($localRepo->getPackages() as $package) {
  346. $candidates[$package->getName()] = true;
  347. }
  348. // fix them to the version in lock (or currently installed) if they are not updateable
  349. foreach ($candidates as $candidate => $dummy) {
  350. foreach ($currentPackages as $curPackage) {
  351. if ($curPackage->getName() === $candidate) {
  352. if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
  353. $constraint = new VersionConstraint('=', $curPackage->getVersion());
  354. $request->install($curPackage->getName(), $constraint);
  355. }
  356. break;
  357. }
  358. }
  359. }
  360. }
  361. } elseif ($installFromLock) {
  362. $this->io->write('<info>Installing dependencies'.($withDevReqs?' (including require-dev)':'').' from lock file</info>');
  363. if (!$this->locker->isFresh()) {
  364. $this->io->write('<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>');
  365. }
  366. foreach ($lockedRepository->getPackages() as $package) {
  367. $version = $package->getVersion();
  368. if (isset($aliases[$package->getName()][$version])) {
  369. $version = $aliases[$package->getName()][$version]['alias_normalized'];
  370. }
  371. $constraint = new VersionConstraint('=', $version);
  372. $constraint->setPrettyString($package->getPrettyVersion());
  373. $request->install($package->getName(), $constraint);
  374. }
  375. foreach ($this->locker->getPlatformRequirements($withDevReqs) as $link) {
  376. $request->install($link->getTarget(), $link->getConstraint());
  377. }
  378. } else {
  379. $this->io->write('<info>Installing dependencies'.($withDevReqs?' (including require-dev)':'').'</info>');
  380. if ($withDevReqs) {
  381. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  382. } else {
  383. $links = $this->package->getRequires();
  384. }
  385. foreach ($links as $link) {
  386. $request->install($link->getTarget(), $link->getConstraint());
  387. }
  388. }
  389. // force dev packages to have the latest links if we update or install from a (potentially new) lock
  390. $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-links');
  391. // solve dependencies
  392. $solver = new Solver($policy, $pool, $installedRepo);
  393. try {
  394. $operations = $solver->solve($request);
  395. } catch (SolverProblemsException $e) {
  396. $this->io->write('<error>Your requirements could not be resolved to an installable set of packages.</error>');
  397. $this->io->write($e->getMessage());
  398. return max(1, $e->getCode());
  399. }
  400. // force dev packages to be updated if we update or install from a (potentially new) lock
  401. $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-updates', $operations);
  402. // execute operations
  403. if (!$operations) {
  404. $this->io->write('Nothing to install or update');
  405. }
  406. $operations = $this->movePluginsToFront($operations);
  407. foreach ($operations as $operation) {
  408. // collect suggestions
  409. if ('install' === $operation->getJobType()) {
  410. foreach ($operation->getPackage()->getSuggests() as $target => $reason) {
  411. $this->suggestedPackages[] = array(
  412. 'source' => $operation->getPackage()->getPrettyName(),
  413. 'target' => $target,
  414. 'reason' => $reason,
  415. );
  416. }
  417. }
  418. $event = 'Composer\Script\ScriptEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType());
  419. if (defined($event) && $this->runScripts) {
  420. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
  421. }
  422. // not installing from lock, force dev packages' references if they're in root package refs
  423. if (!$installFromLock) {
  424. $package = null;
  425. if ('update' === $operation->getJobType()) {
  426. $package = $operation->getTargetPackage();
  427. } elseif ('install' === $operation->getJobType()) {
  428. $package = $operation->getPackage();
  429. }
  430. if ($package && $package->isDev()) {
  431. $references = $this->package->getReferences();
  432. if (isset($references[$package->getName()])) {
  433. $package->setSourceReference($references[$package->getName()]);
  434. $package->setDistReference($references[$package->getName()]);
  435. }
  436. }
  437. }
  438. // output non-alias ops in dry run, output alias ops in debug verbosity
  439. if ($this->dryRun && false === strpos($operation->getJobType(), 'Alias')) {
  440. $this->io->write(' - ' . $operation);
  441. $this->io->write('');
  442. } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
  443. $this->io->write(' - ' . $operation);
  444. $this->io->write('');
  445. }
  446. $this->installationManager->execute($localRepo, $operation);
  447. // output reasons why the operation was ran, only for install/update operations
  448. if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) {
  449. $reason = $operation->getReason();
  450. if ($reason instanceof Rule) {
  451. switch ($reason->getReason()) {
  452. case Rule::RULE_JOB_INSTALL:
  453. $this->io->write(' REASON: Required by root: '.$reason->getRequiredPackage());
  454. $this->io->write('');
  455. break;
  456. case Rule::RULE_PACKAGE_REQUIRES:
  457. $this->io->write(' REASON: '.$reason->getPrettyString());
  458. $this->io->write('');
  459. break;
  460. }
  461. }
  462. }
  463. $event = 'Composer\Script\ScriptEvents::POST_PACKAGE_'.strtoupper($operation->getJobType());
  464. if (defined($event) && $this->runScripts) {
  465. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
  466. }
  467. if (!$this->dryRun) {
  468. $localRepo->write();
  469. }
  470. }
  471. return 0;
  472. }
  473. /**
  474. * Workaround: if your packages depend on plugins, we must be sure
  475. * that those are installed / updated first; else it would lead to packages
  476. * being installed multiple times in different folders, when running Composer
  477. * twice.
  478. *
  479. * While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
  480. * it at least fixes the symptoms and makes usage of composer possible (again)
  481. * in such scenarios.
  482. *
  483. * @param OperationInterface[] $operations
  484. * @return OperationInterface[] reordered operation list
  485. */
  486. private function movePluginsToFront(array $operations)
  487. {
  488. $installerOps = array();
  489. foreach ($operations as $idx => $op) {
  490. if ($op instanceof InstallOperation) {
  491. $package = $op->getPackage();
  492. } elseif ($op instanceof UpdateOperation) {
  493. $package = $op->getTargetPackage();
  494. } else {
  495. continue;
  496. }
  497. if ($package->getRequires() === array() && ($package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer')) {
  498. $installerOps[] = $op;
  499. unset($operations[$idx]);
  500. }
  501. }
  502. return array_merge($installerOps, $operations);
  503. }
  504. private function createPool($withDevReqs)
  505. {
  506. $minimumStability = $this->package->getMinimumStability();
  507. $stabilityFlags = $this->package->getStabilityFlags();
  508. if (!$this->update && $this->locker->isLocked()) {
  509. $minimumStability = $this->locker->getMinimumStability();
  510. $stabilityFlags = $this->locker->getStabilityFlags();
  511. }
  512. $requires = $this->package->getRequires();
  513. if ($withDevReqs) {
  514. $requires = array_merge($requires, $this->package->getDevRequires());
  515. }
  516. $rootConstraints = array();
  517. foreach ($requires as $req => $constraint) {
  518. $rootConstraints[$req] = $constraint->getConstraint();
  519. }
  520. return new Pool($minimumStability, $stabilityFlags, $rootConstraints);
  521. }
  522. private function createPolicy()
  523. {
  524. return new DefaultPolicy($this->package->getPreferStable());
  525. }
  526. private function createRequest(Pool $pool, RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
  527. {
  528. $request = new Request($pool);
  529. $constraint = new VersionConstraint('=', $rootPackage->getVersion());
  530. $constraint->setPrettyString($rootPackage->getPrettyVersion());
  531. $request->install($rootPackage->getName(), $constraint);
  532. $fixedPackages = $platformRepo->getPackages();
  533. if ($this->additionalInstalledRepository) {
  534. $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
  535. $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
  536. }
  537. // fix the version of all platform packages + additionally installed packages
  538. // to prevent the solver trying to remove or update those
  539. $provided = $rootPackage->getProvides();
  540. foreach ($fixedPackages as $package) {
  541. $constraint = new VersionConstraint('=', $package->getVersion());
  542. $constraint->setPrettyString($package->getPrettyVersion());
  543. // skip platform packages that are provided by the root package
  544. if ($package->getRepository() !== $platformRepo
  545. || !isset($provided[$package->getName()])
  546. || !$provided[$package->getName()]->getConstraint()->matches($constraint)
  547. ) {
  548. $request->install($package->getName(), $constraint);
  549. }
  550. }
  551. return $request;
  552. }
  553. private function processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, $task, array $operations = null)
  554. {
  555. if ($task === 'force-updates' && null === $operations) {
  556. throw new \InvalidArgumentException('Missing operations argument');
  557. }
  558. if ($task === 'force-links') {
  559. $operations = array();
  560. }
  561. foreach ($localRepo->getCanonicalPackages() as $package) {
  562. // skip non-dev packages
  563. if (!$package->isDev()) {
  564. continue;
  565. }
  566. // skip packages that will be updated/uninstalled
  567. foreach ($operations as $operation) {
  568. if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
  569. || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package))
  570. ) {
  571. continue 2;
  572. }
  573. }
  574. // force update to locked version if it does not match the installed version
  575. if ($installFromLock) {
  576. foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) {
  577. if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) {
  578. if ($task === 'force-links') {
  579. $package->setRequires($lockedPackage->getRequires());
  580. $package->setConflicts($lockedPackage->getConflicts());
  581. $package->setProvides($lockedPackage->getProvides());
  582. $package->setReplaces($lockedPackage->getReplaces());
  583. } elseif ($task === 'force-updates') {
  584. if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference())
  585. || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference())
  586. ) {
  587. $operations[] = new UpdateOperation($package, $lockedPackage);
  588. }
  589. }
  590. break;
  591. }
  592. }
  593. } else {
  594. // force update to latest on update
  595. if ($this->update) {
  596. // skip package if the whitelist is enabled and it is not in it
  597. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  598. continue;
  599. }
  600. // find similar packages (name/version) in all repositories
  601. $matches = $pool->whatProvides($package->getName(), new VersionConstraint('=', $package->getVersion()));
  602. foreach ($matches as $index => $match) {
  603. // skip local packages
  604. if (!in_array($match->getRepository(), $repositories, true)) {
  605. unset($matches[$index]);
  606. continue;
  607. }
  608. // skip providers/replacers
  609. if ($match->getName() !== $package->getName()) {
  610. unset($matches[$index]);
  611. continue;
  612. }
  613. $matches[$index] = $match->getId();
  614. }
  615. // select prefered package according to policy rules
  616. if ($matches && $matches = $policy->selectPreferedPackages($pool, array(), $matches)) {
  617. $newPackage = $pool->literalToPackage($matches[0]);
  618. if ($task === 'force-links' && $newPackage) {
  619. $package->setRequires($newPackage->getRequires());
  620. $package->setConflicts($newPackage->getConflicts());
  621. $package->setProvides($newPackage->getProvides());
  622. $package->setReplaces($newPackage->getReplaces());
  623. }
  624. if ($task === 'force-updates' && $newPackage && (
  625. (($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference())
  626. || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference())
  627. )
  628. )) {
  629. $operations[] = new UpdateOperation($package, $newPackage);
  630. }
  631. }
  632. }
  633. if ($task === 'force-updates') {
  634. // force installed package to update to referenced version if it does not match the installed version
  635. $references = $this->package->getReferences();
  636. if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) {
  637. // changing the source ref to update to will be handled in the operations loop below
  638. $operations[] = new UpdateOperation($package, clone $package);
  639. }
  640. }
  641. }
  642. }
  643. return $operations;
  644. }
  645. private function getRootAliases()
  646. {
  647. if (!$this->update && $this->locker->isLocked()) {
  648. $aliases = $this->locker->getAliases();
  649. } else {
  650. $aliases = $this->package->getAliases();
  651. }
  652. $normalizedAliases = array();
  653. foreach ($aliases as $alias) {
  654. $normalizedAliases[$alias['package']][$alias['version']] = array(
  655. 'alias' => $alias['alias'],
  656. 'alias_normalized' => $alias['alias_normalized']
  657. );
  658. }
  659. return $normalizedAliases;
  660. }
  661. private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases)
  662. {
  663. foreach ($aliases as $package => $versions) {
  664. foreach ($versions as $version => $alias) {
  665. $packages = $platformRepo->findPackages($package, $version);
  666. foreach ($packages as $package) {
  667. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  668. $aliasPackage->setRootPackageAlias(true);
  669. $platformRepo->addPackage($aliasPackage);
  670. }
  671. }
  672. }
  673. }
  674. private function isUpdateable(PackageInterface $package)
  675. {
  676. if (!$this->updateWhitelist) {
  677. throw new \LogicException('isUpdateable should only be called when a whitelist is present');
  678. }
  679. foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
  680. $cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern));
  681. if (preg_match("{^".$cleanedWhiteListedPattern."$}i", $package->getName())) {
  682. return true;
  683. }
  684. }
  685. return false;
  686. }
  687. private function extractPlatformRequirements($links)
  688. {
  689. $platformReqs = array();
  690. foreach ($links as $link) {
  691. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  692. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  693. }
  694. }
  695. return $platformReqs;
  696. }
  697. /**
  698. * Adds all dependencies of the update whitelist to the whitelist, too.
  699. *
  700. * Packages which are listed as requirements in the root package will be
  701. * skipped including their dependencies, unless they are listed in the
  702. * update whitelist themselves.
  703. *
  704. * @param RepositoryInterface $localRepo
  705. * @param boolean $devMode
  706. * @param array $rootRequires An array of links to packages in require of the root package
  707. * @param array $rootDevRequires An array of links to packages in require-dev of the root package
  708. */
  709. private function whitelistUpdateDependencies($localRepo, $devMode, array $rootRequires, array $rootDevRequires)
  710. {
  711. if (!$this->updateWhitelist) {
  712. return;
  713. }
  714. $requiredPackageNames = array();
  715. foreach (array_merge($rootRequires, $rootDevRequires) as $require) {
  716. $requiredPackageNames[] = $require->getTarget();
  717. }
  718. if ($devMode) {
  719. $rootRequires = array_merge($rootRequires, $rootDevRequires);
  720. }
  721. $skipPackages = array();
  722. foreach ($rootRequires as $require) {
  723. $skipPackages[$require->getTarget()] = true;
  724. }
  725. $pool = new Pool;
  726. $pool->addRepository($localRepo);
  727. $seen = array();
  728. foreach ($this->updateWhitelist as $packageName => $void) {
  729. $packageQueue = new \SplQueue;
  730. $depPackages = $pool->whatProvides($packageName);
  731. if (count($depPackages) == 0 && !in_array($packageName, $requiredPackageNames) && !in_array($packageName, array('nothing', 'lock'))) {
  732. $this->io->write('<warning>Package "' . $packageName . '" listed for update is not installed. Ignoring.</warning>');
  733. }
  734. foreach ($depPackages as $depPackage) {
  735. $packageQueue->enqueue($depPackage);
  736. }
  737. while (!$packageQueue->isEmpty()) {
  738. $package = $packageQueue->dequeue();
  739. if (isset($seen[$package->getId()])) {
  740. continue;
  741. }
  742. $seen[$package->getId()] = true;
  743. $this->updateWhitelist[$package->getName()] = true;
  744. if (!$this->whitelistDependencies) {
  745. continue;
  746. }
  747. $requires = $package->getRequires();
  748. foreach ($requires as $require) {
  749. $requirePackages = $pool->whatProvides($require->getTarget());
  750. foreach ($requirePackages as $requirePackage) {
  751. if (isset($skipPackages[$requirePackage->getName()])) {
  752. continue;
  753. }
  754. $packageQueue->enqueue($requirePackage);
  755. }
  756. }
  757. }
  758. }
  759. }
  760. /**
  761. * Replace local repositories with InstalledArrayRepository instances
  762. *
  763. * This is to prevent any accidental modification of the existing repos on disk
  764. *
  765. * @param RepositoryManager $rm
  766. */
  767. private function mockLocalRepositories(RepositoryManager $rm)
  768. {
  769. $packages = array();
  770. foreach ($rm->getLocalRepository()->getPackages() as $package) {
  771. $packages[(string) $package] = clone $package;
  772. }
  773. foreach ($packages as $key => $package) {
  774. if ($package instanceof AliasPackage) {
  775. $alias = (string) $package->getAliasOf();
  776. $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion());
  777. }
  778. }
  779. $rm->setLocalRepository(
  780. new InstalledArrayRepository($packages)
  781. );
  782. }
  783. /**
  784. * Create Installer
  785. *
  786. * @param IOInterface $io
  787. * @param Composer $composer
  788. * @return Installer
  789. */
  790. public static function create(IOInterface $io, Composer $composer)
  791. {
  792. return new static(
  793. $io,
  794. $composer->getConfig(),
  795. $composer->getPackage(),
  796. $composer->getDownloadManager(),
  797. $composer->getRepositoryManager(),
  798. $composer->getLocker(),
  799. $composer->getInstallationManager(),
  800. $composer->getEventDispatcher(),
  801. $composer->getAutoloadGenerator()
  802. );
  803. }
  804. public function setAdditionalInstalledRepository(RepositoryInterface $additionalInstalledRepository)
  805. {
  806. $this->additionalInstalledRepository = $additionalInstalledRepository;
  807. return $this;
  808. }
  809. /**
  810. * Whether to run in drymode or not
  811. *
  812. * @param boolean $dryRun
  813. * @return Installer
  814. */
  815. public function setDryRun($dryRun = true)
  816. {
  817. $this->dryRun = (boolean) $dryRun;
  818. return $this;
  819. }
  820. /**
  821. * prefer source installation
  822. *
  823. * @param boolean $preferSource
  824. * @return Installer
  825. */
  826. public function setPreferSource($preferSource = true)
  827. {
  828. $this->preferSource = (boolean) $preferSource;
  829. return $this;
  830. }
  831. /**
  832. * prefer dist installation
  833. *
  834. * @param boolean $preferDist
  835. * @return Installer
  836. */
  837. public function setPreferDist($preferDist = true)
  838. {
  839. $this->preferDist = (boolean) $preferDist;
  840. return $this;
  841. }
  842. /**
  843. * Whether or not generated autoloader are optimized
  844. *
  845. * @param bool $optimizeAutoloader
  846. * @return Installer
  847. */
  848. public function setOptimizeAutoloader($optimizeAutoloader = false)
  849. {
  850. $this->optimizeAutoloader = (boolean) $optimizeAutoloader;
  851. return $this;
  852. }
  853. /**
  854. * update packages
  855. *
  856. * @param boolean $update
  857. * @return Installer
  858. */
  859. public function setUpdate($update = true)
  860. {
  861. $this->update = (boolean) $update;
  862. return $this;
  863. }
  864. /**
  865. * enables dev packages
  866. *
  867. * @param boolean $devMode
  868. * @return Installer
  869. */
  870. public function setDevMode($devMode = true)
  871. {
  872. $this->devMode = (boolean) $devMode;
  873. return $this;
  874. }
  875. /**
  876. * set whether to run scripts or not
  877. *
  878. * @param boolean $runScripts
  879. * @return Installer
  880. */
  881. public function setRunScripts($runScripts = true)
  882. {
  883. $this->runScripts = (boolean) $runScripts;
  884. return $this;
  885. }
  886. /**
  887. * set the config instance
  888. *
  889. * @param Config $config
  890. * @return Installer
  891. */
  892. public function setConfig(Config $config)
  893. {
  894. $this->config = $config;
  895. return $this;
  896. }
  897. /**
  898. * run in verbose mode
  899. *
  900. * @param boolean $verbose
  901. * @return Installer
  902. */
  903. public function setVerbose($verbose = true)
  904. {
  905. $this->verbose = (boolean) $verbose;
  906. return $this;
  907. }
  908. /**
  909. * restrict the update operation to a few packages, all other packages
  910. * that are already installed will be kept at their current version
  911. *
  912. * @param array $packages
  913. * @return Installer
  914. */
  915. public function setUpdateWhitelist(array $packages)
  916. {
  917. $this->updateWhitelist = array_flip(array_map('strtolower', $packages));
  918. return $this;
  919. }
  920. /**
  921. * Should dependencies of whitelisted packages be updated recursively?
  922. *
  923. * @param boolean $updateDependencies
  924. * @return Installer
  925. */
  926. public function setWhitelistDependencies($updateDependencies = true)
  927. {
  928. $this->whitelistDependencies = (boolean) $updateDependencies;
  929. return $this;
  930. }
  931. /**
  932. * Disables plugins.
  933. *
  934. * Call this if you want to ensure that third-party code never gets
  935. * executed. The default is to automatically install, and execute
  936. * custom third-party installers.
  937. *
  938. * @return Installer
  939. */
  940. public function disablePlugins()
  941. {
  942. $this->installationManager->disablePlugins();
  943. return $this;
  944. }
  945. }