Installer.php 44 KB

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