Installer.php 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  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\MarkAliasUninstalledOperation;
  18. use Composer\DependencyResolver\Operation\OperationInterface;
  19. use Composer\DependencyResolver\PolicyInterface;
  20. use Composer\DependencyResolver\Pool;
  21. use Composer\DependencyResolver\Request;
  22. use Composer\DependencyResolver\Rule;
  23. use Composer\DependencyResolver\Solver;
  24. use Composer\DependencyResolver\SolverProblemsException;
  25. use Composer\Downloader\DownloadManager;
  26. use Composer\EventDispatcher\EventDispatcher;
  27. use Composer\Installer\InstallationManager;
  28. use Composer\Installer\InstallerEvents;
  29. use Composer\Installer\NoopInstaller;
  30. use Composer\Installer\SuggestedPackagesReporter;
  31. use Composer\IO\IOInterface;
  32. use Composer\Package\AliasPackage;
  33. use Composer\Package\BasePackage;
  34. use Composer\Package\CompletePackage;
  35. use Composer\Package\Link;
  36. use Composer\Package\Loader\ArrayLoader;
  37. use Composer\Package\Dumper\ArrayDumper;
  38. use Composer\Repository\RepositorySet;
  39. use Composer\Semver\Constraint\Constraint;
  40. use Composer\Package\Locker;
  41. use Composer\Package\PackageInterface;
  42. use Composer\Package\RootPackageInterface;
  43. use Composer\Repository\CompositeRepository;
  44. use Composer\Repository\InstalledArrayRepository;
  45. use Composer\Repository\PlatformRepository;
  46. use Composer\Repository\RepositoryInterface;
  47. use Composer\Repository\RepositoryManager;
  48. use Composer\Repository\WritableRepositoryInterface;
  49. use Composer\Script\ScriptEvents;
  50. /**
  51. * @author Jordi Boggiano <j.boggiano@seld.be>
  52. * @author Beau Simensen <beau@dflydev.com>
  53. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  54. * @author Nils Adermann <naderman@naderman.de>
  55. */
  56. class Installer
  57. {
  58. /**
  59. * @var IOInterface
  60. */
  61. protected $io;
  62. /**
  63. * @var Config
  64. */
  65. protected $config;
  66. /**
  67. * @var RootPackageInterface
  68. */
  69. protected $package;
  70. /**
  71. * @var DownloadManager
  72. */
  73. protected $downloadManager;
  74. /**
  75. * @var RepositoryManager
  76. */
  77. protected $repositoryManager;
  78. /**
  79. * @var Locker
  80. */
  81. protected $locker;
  82. /**
  83. * @var InstallationManager
  84. */
  85. protected $installationManager;
  86. /**
  87. * @var EventDispatcher
  88. */
  89. protected $eventDispatcher;
  90. /**
  91. * @var AutoloadGenerator
  92. */
  93. protected $autoloadGenerator;
  94. protected $preferSource = false;
  95. protected $preferDist = false;
  96. protected $optimizeAutoloader = false;
  97. protected $classMapAuthoritative = false;
  98. protected $apcuAutoloader = false;
  99. protected $devMode = false;
  100. protected $dryRun = false;
  101. protected $verbose = false;
  102. protected $update = false;
  103. protected $dumpAutoloader = true;
  104. protected $runScripts = true;
  105. protected $ignorePlatformReqs = false;
  106. protected $preferStable = false;
  107. protected $preferLowest = false;
  108. protected $skipSuggest = false;
  109. protected $writeLock = true;
  110. protected $executeOperations = true;
  111. /**
  112. * Array of package names/globs flagged for update
  113. *
  114. * @var array|null
  115. */
  116. protected $updateWhitelist = null;
  117. protected $whitelistTransitiveDependencies = false;
  118. protected $whitelistAllDependencies = false;
  119. /**
  120. * @var SuggestedPackagesReporter
  121. */
  122. protected $suggestedPackagesReporter;
  123. /**
  124. * @var RepositoryInterface
  125. */
  126. protected $additionalInstalledRepository;
  127. /**
  128. * Constructor
  129. *
  130. * @param IOInterface $io
  131. * @param Config $config
  132. * @param RootPackageInterface $package
  133. * @param DownloadManager $downloadManager
  134. * @param RepositoryManager $repositoryManager
  135. * @param Locker $locker
  136. * @param InstallationManager $installationManager
  137. * @param EventDispatcher $eventDispatcher
  138. * @param AutoloadGenerator $autoloadGenerator
  139. */
  140. public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
  141. {
  142. $this->io = $io;
  143. $this->config = $config;
  144. $this->package = $package;
  145. $this->downloadManager = $downloadManager;
  146. $this->repositoryManager = $repositoryManager;
  147. $this->locker = $locker;
  148. $this->installationManager = $installationManager;
  149. $this->eventDispatcher = $eventDispatcher;
  150. $this->autoloadGenerator = $autoloadGenerator;
  151. }
  152. /**
  153. * Run installation (or update)
  154. *
  155. * @throws \Exception
  156. * @return int 0 on success or a positive error code on failure
  157. */
  158. public function run()
  159. {
  160. // Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands
  161. // of PHP objects, the GC can spend quite some time walking the tree of references looking
  162. // for stuff to collect while there is nothing to collect. This slows things down dramatically
  163. // and turning it off results in much better performance. Do not try this at home however.
  164. gc_collect_cycles();
  165. gc_disable();
  166. // Force update if there is no lock file present
  167. if (!$this->update && !$this->locker->isLocked()) {
  168. $this->update = true;
  169. }
  170. if ($this->dryRun) {
  171. $this->verbose = true;
  172. $this->runScripts = false;
  173. $this->executeOperations = false;
  174. $this->writeLock = false;
  175. $this->dumpAutoloader = false;
  176. $this->installationManager->addInstaller(new NoopInstaller);
  177. $this->mockLocalRepositories($this->repositoryManager);
  178. }
  179. if ($this->runScripts) {
  180. $devMode = (int) $this->devMode;
  181. putenv("COMPOSER_DEV_MODE=$devMode");
  182. // dispatch pre event
  183. $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
  184. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  185. }
  186. $this->downloadManager->setPreferSource($this->preferSource);
  187. $this->downloadManager->setPreferDist($this->preferDist);
  188. // create installed repo, this contains all local packages + platform packages (php & extensions)
  189. $localRepo = $this->repositoryManager->getLocalRepository();
  190. if ($this->update) {
  191. $platformOverrides = $this->config->get('platform') ?: array();
  192. } else {
  193. $platformOverrides = $this->locker->getPlatformOverrides();
  194. }
  195. $platformRepo = new PlatformRepository(array(), $platformOverrides);
  196. $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo);
  197. $aliases = $this->getRootAliases();
  198. $this->aliasPlatformPackages($platformRepo, $aliases);
  199. if (!$this->suggestedPackagesReporter) {
  200. $this->suggestedPackagesReporter = new SuggestedPackagesReporter($this->io);
  201. }
  202. try {
  203. list($res, $devPackages) = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases);
  204. if ($res !== 0) {
  205. return $res;
  206. }
  207. } catch (\Exception $e) {
  208. if ($this->executeOperations) {
  209. $this->installationManager->notifyInstalls($this->io);
  210. }
  211. throw $e;
  212. }
  213. if ($this->executeOperations) {
  214. $this->installationManager->notifyInstalls($this->io);
  215. }
  216. // output suggestions if we're in dev mode
  217. if ($this->devMode && !$this->skipSuggest) {
  218. $this->suggestedPackagesReporter->output($installedRepo);
  219. }
  220. # Find abandoned packages and warn user
  221. foreach ($localRepo->getPackages() as $package) {
  222. if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
  223. continue;
  224. }
  225. $replacement = is_string($package->getReplacementPackage())
  226. ? 'Use ' . $package->getReplacementPackage() . ' instead'
  227. : 'No replacement was suggested';
  228. $this->io->writeError(
  229. sprintf(
  230. "<warning>Package %s is abandoned, you should avoid using it. %s.</warning>",
  231. $package->getPrettyName(),
  232. $replacement
  233. )
  234. );
  235. }
  236. // write lock
  237. if ($this->update && $this->writeLock) {
  238. $localRepo->reload();
  239. $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
  240. $platformDevReqs = $this->extractPlatformRequirements($this->package->getDevRequires());
  241. $updatedLock = $this->locker->setLockData(
  242. array_diff($localRepo->getCanonicalPackages(), $devPackages),
  243. $devPackages,
  244. $platformReqs,
  245. $platformDevReqs,
  246. $aliases,
  247. $this->package->getMinimumStability(),
  248. $this->package->getStabilityFlags(),
  249. $this->preferStable || $this->package->getPreferStable(),
  250. $this->preferLowest,
  251. $this->config->get('platform') ?: array()
  252. );
  253. if ($updatedLock) {
  254. $this->io->writeError('<info>Writing lock file</info>');
  255. }
  256. }
  257. if ($this->dumpAutoloader) {
  258. // write autoloader
  259. if ($this->optimizeAutoloader) {
  260. $this->io->writeError('<info>Generating optimized autoload files</info>');
  261. } else {
  262. $this->io->writeError('<info>Generating autoload files</info>');
  263. }
  264. $this->autoloadGenerator->setDevMode($this->devMode);
  265. $this->autoloadGenerator->setClassMapAuthoritative($this->classMapAuthoritative);
  266. $this->autoloadGenerator->setApcu($this->apcuAutoloader);
  267. $this->autoloadGenerator->setRunScripts($this->runScripts);
  268. $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
  269. }
  270. if ($this->executeOperations) {
  271. // force binaries re-generation in case they are missing
  272. foreach ($localRepo->getPackages() as $package) {
  273. $this->installationManager->ensureBinariesPresence($package);
  274. }
  275. $vendorDir = $this->config->get('vendor-dir');
  276. if (is_dir($vendorDir)) {
  277. // suppress errors as this fails sometimes on OSX for no apparent reason
  278. // see https://github.com/composer/composer/issues/4070#issuecomment-129792748
  279. @touch($vendorDir);
  280. }
  281. }
  282. if ($this->runScripts) {
  283. // dispatch post event
  284. $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
  285. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  286. }
  287. // re-enable GC except on HHVM which triggers a warning here
  288. if (!defined('HHVM_VERSION')) {
  289. gc_enable();
  290. }
  291. return 0;
  292. }
  293. /**
  294. * @param RepositoryInterface $localRepo
  295. * @param RepositoryInterface $installedRepo
  296. * @param PlatformRepository $platformRepo
  297. * @param array $aliases
  298. * @return array [int, PackageInterfaces[]|null] with the exit code and an array of dev packages on update, or null on install
  299. */
  300. protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases)
  301. {
  302. // init vars
  303. $lockedRepository = null;
  304. $repositories = null;
  305. // initialize locked repo if we are installing from lock or in a partial update
  306. // and a lock file is present as we need to force install non-whitelisted lock file
  307. // packages in that case
  308. if (!$this->update || (!empty($this->updateWhitelist) && $this->locker->isLocked())) {
  309. try {
  310. $lockedRepository = $this->locker->getLockedRepository($this->devMode);
  311. } catch (\RuntimeException $e) {
  312. // if there are dev requires, then we really can not install
  313. if ($this->package->getDevRequires()) {
  314. throw $e;
  315. }
  316. // no require-dev in composer.json and the lock file was created with no dev info, so skip them
  317. $lockedRepository = $this->locker->getLockedRepository();
  318. }
  319. }
  320. $this->whitelistUpdateDependencies(
  321. $lockedRepository ?: $localRepo,
  322. $this->package->getRequires(),
  323. $this->package->getDevRequires()
  324. );
  325. $this->io->writeError('<info>Loading composer repositories with package information</info>');
  326. // creating repository set
  327. $policy = $this->createPolicy();
  328. $repositorySet = $this->createRepositorySet($aliases, $this->update ? null : $lockedRepository);
  329. $repositorySet->addRepository($installedRepo);
  330. if ($this->update) {
  331. $repositories = $this->repositoryManager->getRepositories();
  332. foreach ($repositories as $repository) {
  333. $repositorySet->addRepository($repository);
  334. }
  335. }
  336. // Add the locked repository after the others in case we are doing a
  337. // partial update so missing packages can be found there still.
  338. // For installs from lock it's the only one added so it is first
  339. if ($lockedRepository) {
  340. $repositorySet->addRepository($lockedRepository);
  341. }
  342. // creating requirements request
  343. $request = $this->createRequest($this->package, $platformRepo);
  344. if ($this->update) {
  345. // remove unstable packages from the localRepo if they don't match the current stability settings
  346. $removedUnstablePackages = array();
  347. foreach ($localRepo->getPackages() as $package) {
  348. if (
  349. !$repositorySet->isPackageAcceptable($package->getNames(), $package->getStability())
  350. && $this->installationManager->isPackageInstalled($localRepo, $package)
  351. ) {
  352. $removedUnstablePackages[$package->getName()] = true;
  353. $request->remove($package->getName(), new Constraint('=', $package->getVersion()));
  354. }
  355. }
  356. $this->io->writeError('<info>Updating dependencies'.($this->devMode ? ' (including require-dev)' : '').'</info>');
  357. $request->updateAll();
  358. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  359. foreach ($links as $link) {
  360. $request->install($link->getTarget(), $link->getConstraint());
  361. }
  362. // if the updateWhitelist is enabled, packages not in it are also fixed
  363. // to the version specified in the lock, or their currently installed version
  364. if ($this->updateWhitelist) {
  365. $currentPackages = $this->getCurrentPackages($installedRepo);
  366. // collect packages to fixate from root requirements as well as installed packages
  367. $candidates = array();
  368. foreach ($links as $link) {
  369. $candidates[$link->getTarget()] = true;
  370. $rootRequires[$link->getTarget()] = $link;
  371. }
  372. foreach ($currentPackages as $package) {
  373. $candidates[$package->getName()] = true;
  374. }
  375. // fix them to the version in lock (or currently installed) if they are not updateable
  376. foreach ($candidates as $candidate => $dummy) {
  377. foreach ($currentPackages as $curPackage) {
  378. if ($curPackage->getName() === $candidate) {
  379. if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
  380. $constraint = new Constraint('=', $curPackage->getVersion());
  381. $description = $this->locker->isLocked() ? '(locked at' : '(installed at';
  382. $requiredAt = isset($rootRequires[$candidate]) ? ', required as ' . $rootRequires[$candidate]->getPrettyConstraint() : '';
  383. $constraint->setPrettyString($description . ' ' . $curPackage->getPrettyVersion() . $requiredAt . ')');
  384. $request->install($curPackage->getName(), $constraint);
  385. }
  386. break;
  387. }
  388. }
  389. }
  390. }
  391. } else {
  392. $this->io->writeError('<info>Installing dependencies'.($this->devMode ? ' (including require-dev)' : '').' from lock file</info>');
  393. if (!$this->locker->isFresh()) {
  394. $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);
  395. }
  396. foreach ($lockedRepository->getPackages() as $package) {
  397. $version = $package->getVersion();
  398. if (isset($aliases[$package->getName()][$version])) {
  399. $version = $aliases[$package->getName()][$version]['alias_normalized'];
  400. }
  401. $constraint = new Constraint('=', $version);
  402. $constraint->setPrettyString($package->getPrettyVersion());
  403. $request->install($package->getName(), $constraint);
  404. }
  405. foreach ($this->locker->getPlatformRequirements($this->devMode) as $link) {
  406. $request->install($link->getTarget(), $link->getConstraint());
  407. }
  408. }
  409. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $this->devMode, $policy, $repositorySet, $installedRepo, $request);
  410. $pool = $repositorySet->createPool($request);
  411. // force dev packages to have the latest links if we update or install from a (potentially new) lock
  412. $this->processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, 'force-links');
  413. // solve dependencies
  414. $solver = new Solver($policy, $pool, $installedRepo, $this->io);
  415. try {
  416. $operations = $solver->solve($request, $this->ignorePlatformReqs);
  417. } catch (SolverProblemsException $e) {
  418. $this->io->writeError('<error>Your requirements could not be resolved to an installable set of packages.</error>', true, IOInterface::QUIET);
  419. $this->io->writeError($e->getMessage());
  420. if ($this->update && !$this->devMode) {
  421. $this->io->writeError('<warning>Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.</warning>', true, IOInterface::QUIET);
  422. }
  423. return array(max(1, $e->getCode()), array());
  424. }
  425. // force dev packages to be updated if we update or install from a (potentially new) lock
  426. $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, 'force-updates', $operations);
  427. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $this->devMode, $policy, $repositorySet, $installedRepo, $request, $operations);
  428. $this->io->writeError("Analyzed ".count($pool)." packages to resolve dependencies", true, IOInterface::VERBOSE);
  429. $this->io->writeError("Analyzed ".$solver->getRuleSetSize()." rules to resolve dependencies", true, IOInterface::VERBOSE);
  430. // execute operations
  431. if (!$operations) {
  432. $this->io->writeError('Nothing to install or update');
  433. }
  434. $operations = $this->movePluginsToFront($operations);
  435. $operations = $this->moveUninstallsToFront($operations);
  436. // extract dev packages and mark them to be skipped if it's a --no-dev install or update
  437. // we also force them to be uninstalled if they are present in the local repo
  438. if ($this->update) {
  439. $devPackages = $this->extractDevPackages($operations, $localRepo, $platformRepo, $aliases);
  440. if (!$this->devMode) {
  441. $operations = $this->filterDevPackageOperations($devPackages, $operations, $localRepo);
  442. }
  443. } else {
  444. $devPackages = null;
  445. }
  446. if ($operations) {
  447. $installs = $updates = $uninstalls = array();
  448. foreach ($operations as $operation) {
  449. if ($operation instanceof InstallOperation) {
  450. $installs[] = $operation->getPackage()->getPrettyName().':'.$operation->getPackage()->getFullPrettyVersion();
  451. } elseif ($operation instanceof UpdateOperation) {
  452. $updates[] = $operation->getTargetPackage()->getPrettyName().':'.$operation->getTargetPackage()->getFullPrettyVersion();
  453. } elseif ($operation instanceof UninstallOperation) {
  454. $uninstalls[] = $operation->getPackage()->getPrettyName();
  455. }
  456. }
  457. $this->io->writeError(sprintf(
  458. "<info>Package operations: %d install%s, %d update%s, %d removal%s</info>",
  459. count($installs),
  460. 1 === count($installs) ? '' : 's',
  461. count($updates),
  462. 1 === count($updates) ? '' : 's',
  463. count($uninstalls),
  464. 1 === count($uninstalls) ? '' : 's'
  465. ));
  466. if ($installs) {
  467. $this->io->writeError("Installs: ".implode(', ', $installs), true, IOInterface::VERBOSE);
  468. }
  469. if ($updates) {
  470. $this->io->writeError("Updates: ".implode(', ', $updates), true, IOInterface::VERBOSE);
  471. }
  472. if ($uninstalls) {
  473. $this->io->writeError("Removals: ".implode(', ', $uninstalls), true, IOInterface::VERBOSE);
  474. }
  475. }
  476. foreach ($operations as $operation) {
  477. // collect suggestions
  478. $jobType = $operation->getJobType();
  479. if ('install' === $jobType) {
  480. $this->suggestedPackagesReporter->addSuggestionsFromPackage($operation->getPackage());
  481. }
  482. // updating, force dev packages' references if they're in root package refs
  483. if ($this->update) {
  484. $package = null;
  485. if ('update' === $jobType) {
  486. $package = $operation->getTargetPackage();
  487. } elseif ('install' === $jobType) {
  488. $package = $operation->getPackage();
  489. }
  490. if ($package && $package->isDev()) {
  491. $references = $this->package->getReferences();
  492. if (isset($references[$package->getName()])) {
  493. $this->updateInstallReferences($package, $references[$package->getName()]);
  494. }
  495. }
  496. if ('update' === $jobType) {
  497. $targetPackage = $operation->getTargetPackage();
  498. if ($targetPackage->isDev()) {
  499. $initialPackage = $operation->getInitialPackage();
  500. if ($targetPackage->getVersion() === $initialPackage->getVersion()
  501. && (!$targetPackage->getSourceReference() || $targetPackage->getSourceReference() === $initialPackage->getSourceReference())
  502. && (!$targetPackage->getDistReference() || $targetPackage->getDistReference() === $initialPackage->getDistReference())
  503. ) {
  504. $this->io->writeError(' - Skipping update of ' . $targetPackage->getPrettyName() . ' to the same reference-locked version', true, IOInterface::DEBUG);
  505. $this->io->writeError('', true, IOInterface::DEBUG);
  506. continue;
  507. }
  508. }
  509. }
  510. }
  511. $event = 'Composer\Installer\PackageEvents::PRE_PACKAGE_'.strtoupper($jobType);
  512. if (defined($event) && $this->runScripts) {
  513. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $repositorySet, $installedRepo, $request, $operations, $operation);
  514. }
  515. // output non-alias ops when not executing operations (i.e. dry run), output alias ops in debug verbosity
  516. if (!$this->executeOperations && false === strpos($operation->getJobType(), 'Alias')) {
  517. $this->io->writeError(' - ' . $operation);
  518. } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
  519. $this->io->writeError(' - ' . $operation);
  520. }
  521. $this->installationManager->execute($localRepo, $operation);
  522. // output reasons why the operation was ran, only for install/update operations
  523. if ($this->verbose && $this->io->isVeryVerbose() && in_array($jobType, array('install', 'update'))) {
  524. $reason = $operation->getReason();
  525. if ($reason instanceof Rule) {
  526. switch ($reason->getReason()) {
  527. case Rule::RULE_JOB_INSTALL:
  528. $this->io->writeError(' REASON: Required by the root package: '.$reason->getPrettyString($pool));
  529. $this->io->writeError('');
  530. break;
  531. case Rule::RULE_PACKAGE_REQUIRES:
  532. $this->io->writeError(' REASON: '.$reason->getPrettyString($pool));
  533. $this->io->writeError('');
  534. break;
  535. }
  536. }
  537. }
  538. if ($this->executeOperations || $this->writeLock) {
  539. $localRepo->write();
  540. }
  541. $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($jobType);
  542. if (defined($event) && $this->runScripts) {
  543. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $repositorySet, $installedRepo, $request, $operations, $operation);
  544. }
  545. }
  546. if ($this->executeOperations) {
  547. // force source/dist urls to be updated for all packages
  548. $this->processPackageUrls($pool, $policy, $localRepo, $repositories);
  549. $localRepo->write();
  550. }
  551. return array(0, $devPackages);
  552. }
  553. /**
  554. * Extracts the dev packages out of the localRepo
  555. *
  556. * This works by faking the operations so we can see what the dev packages
  557. * would be at the end of the operation execution. This lets us then remove
  558. * the dev packages from the list of operations accordingly if we are in a
  559. * --no-dev install or update.
  560. *
  561. * @return array
  562. */
  563. private function extractDevPackages(array $operations, RepositoryInterface $localRepo, PlatformRepository $platformRepo, array $aliases)
  564. {
  565. if (!$this->package->getDevRequires()) {
  566. return array();
  567. }
  568. // fake-apply all operations to this clone of the local repo so we see the complete set of package we would end up with
  569. $tempLocalRepo = clone $localRepo;
  570. foreach ($operations as $operation) {
  571. switch ($operation->getJobType()) {
  572. case 'install':
  573. case 'markAliasInstalled':
  574. if (!$tempLocalRepo->hasPackage($operation->getPackage())) {
  575. $tempLocalRepo->addPackage(clone $operation->getPackage());
  576. }
  577. break;
  578. case 'uninstall':
  579. case 'markAliasUninstalled':
  580. $tempLocalRepo->removePackage($operation->getPackage());
  581. break;
  582. case 'update':
  583. $tempLocalRepo->removePackage($operation->getInitialPackage());
  584. if (!$tempLocalRepo->hasPackage($operation->getTargetPackage())) {
  585. $tempLocalRepo->addPackage(clone $operation->getTargetPackage());
  586. }
  587. break;
  588. default:
  589. throw new \LogicException('Unknown type: '.$operation->getJobType());
  590. }
  591. }
  592. // we have to reload the local repo to handle aliases properly
  593. // but as it is not persisted on disk we use a loader/dumper
  594. // to reload it in memory
  595. $localRepo = new InstalledArrayRepository(array());
  596. $loader = new ArrayLoader(null, true);
  597. $dumper = new ArrayDumper();
  598. foreach ($tempLocalRepo->getCanonicalPackages() as $pkg) {
  599. $localRepo->addPackage($loader->load($dumper->dump($pkg)));
  600. }
  601. unset($tempLocalRepo, $loader, $dumper);
  602. $policy = $this->createPolicy();
  603. $repositorySet = $this->createRepositorySet($aliases);
  604. $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo);
  605. $repositorySet->addRepository($installedRepo);
  606. // creating requirements request without dev requirements
  607. $request = $this->createRequest($this->package, $platformRepo);
  608. $request->updateAll();
  609. foreach ($this->package->getRequires() as $link) {
  610. $request->install($link->getTarget(), $link->getConstraint());
  611. }
  612. // solve deps to see which get removed
  613. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $repositorySet, $installedRepo, $request);
  614. $solver = new Solver($policy, $repositorySet->createPool($request), $installedRepo, $this->io);
  615. $ops = $solver->solve($request, $this->ignorePlatformReqs);
  616. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $repositorySet, $installedRepo, $request, $ops);
  617. $devPackages = array();
  618. foreach ($ops as $op) {
  619. if ($op->getJobType() === 'uninstall') {
  620. $devPackages[] = $op->getPackage();
  621. }
  622. }
  623. return $devPackages;
  624. }
  625. /**
  626. * @return OperationInterface[] filtered operations, dev packages are uninstalled and all operations on them ignored
  627. */
  628. private function filterDevPackageOperations(array $devPackages, array $operations, RepositoryInterface $localRepo)
  629. {
  630. $finalOps = array();
  631. $packagesToSkip = array();
  632. foreach ($devPackages as $pkg) {
  633. $packagesToSkip[$pkg->getName()] = true;
  634. if ($installedDevPkg = $localRepo->findPackage($pkg->getName(), '*')) {
  635. if ($installedDevPkg instanceof AliasPackage) {
  636. $finalOps[] = new MarkAliasUninstalledOperation($installedDevPkg, 'non-dev install removing it');
  637. $installedDevPkg = $installedDevPkg->getAliasOf();
  638. }
  639. $finalOps[] = new UninstallOperation($installedDevPkg, 'non-dev install removing it');
  640. }
  641. }
  642. // skip operations applied on dev packages
  643. foreach ($operations as $op) {
  644. $package = $op->getJobType() === 'update' ? $op->getTargetPackage() : $op->getPackage();
  645. if (isset($packagesToSkip[$package->getName()])) {
  646. continue;
  647. }
  648. $finalOps[] = $op;
  649. }
  650. return $finalOps;
  651. }
  652. /**
  653. * Workaround: if your packages depend on plugins, we must be sure
  654. * that those are installed / updated first; else it would lead to packages
  655. * being installed multiple times in different folders, when running Composer
  656. * twice.
  657. *
  658. * While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
  659. * it at least fixes the symptoms and makes usage of composer possible (again)
  660. * in such scenarios.
  661. *
  662. * @param OperationInterface[] $operations
  663. * @return OperationInterface[] reordered operation list
  664. */
  665. private function movePluginsToFront(array $operations)
  666. {
  667. $pluginsNoDeps = array();
  668. $pluginsWithDeps = array();
  669. $pluginRequires = array();
  670. foreach (array_reverse($operations, true) as $idx => $op) {
  671. if ($op instanceof InstallOperation) {
  672. $package = $op->getPackage();
  673. } elseif ($op instanceof UpdateOperation) {
  674. $package = $op->getTargetPackage();
  675. } else {
  676. continue;
  677. }
  678. // is this package a plugin?
  679. $isPlugin = $package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer';
  680. // is this a plugin or a dependency of a plugin?
  681. if ($isPlugin || count(array_intersect($package->getNames(), $pluginRequires))) {
  682. // get the package's requires, but filter out any platform requirements or 'composer-plugin-api'
  683. $requires = array_filter(array_keys($package->getRequires()), function ($req) {
  684. return $req !== 'composer-plugin-api' && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req);
  685. });
  686. // is this a plugin with no meaningful dependencies?
  687. if ($isPlugin && !count($requires)) {
  688. // plugins with no dependencies go to the very front
  689. array_unshift($pluginsNoDeps, $op);
  690. } else {
  691. // capture the requirements for this package so those packages will be moved up as well
  692. $pluginRequires = array_merge($pluginRequires, $requires);
  693. // move the operation to the front
  694. array_unshift($pluginsWithDeps, $op);
  695. }
  696. unset($operations[$idx]);
  697. }
  698. }
  699. return array_merge($pluginsNoDeps, $pluginsWithDeps, $operations);
  700. }
  701. /**
  702. * Removals of packages should be executed before installations in
  703. * case two packages resolve to the same path (due to custom installers)
  704. *
  705. * @param OperationInterface[] $operations
  706. * @return OperationInterface[] reordered operation list
  707. */
  708. private function moveUninstallsToFront(array $operations)
  709. {
  710. $uninstOps = array();
  711. foreach ($operations as $idx => $op) {
  712. if ($op instanceof UninstallOperation) {
  713. $uninstOps[] = $op;
  714. unset($operations[$idx]);
  715. }
  716. }
  717. return array_merge($uninstOps, $operations);
  718. }
  719. /**
  720. * @return RepositoryInterface
  721. */
  722. private function createInstalledRepo(RepositoryInterface $localRepo, PlatformRepository $platformRepo)
  723. {
  724. // clone root package to have one in the installed repo that does not require anything
  725. // we don't want it to be uninstallable, but its requirements should not conflict
  726. // with the lock file for example
  727. $installedRootPackage = clone $this->package;
  728. $installedRootPackage->setRequires(array());
  729. $installedRootPackage->setDevRequires(array());
  730. $repos = array(
  731. $localRepo,
  732. new InstalledArrayRepository(array($installedRootPackage)),
  733. $platformRepo,
  734. );
  735. $installedRepo = new CompositeRepository($repos);
  736. if ($this->additionalInstalledRepository) {
  737. $installedRepo->addRepository($this->additionalInstalledRepository);
  738. }
  739. return $installedRepo;
  740. }
  741. /**
  742. * @param array $rootAliases
  743. * @param RepositoryInterface|null $lockedRepository
  744. * @return RepositorySet
  745. */
  746. private function createRepositorySet(array $rootAliases = array(), $lockedRepository = null)
  747. {
  748. if ($this->update) {
  749. $minimumStability = $this->package->getMinimumStability();
  750. $stabilityFlags = $this->package->getStabilityFlags();
  751. $requires = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  752. } else {
  753. $minimumStability = $this->locker->getMinimumStability();
  754. $stabilityFlags = $this->locker->getStabilityFlags();
  755. $requires = array();
  756. foreach ($lockedRepository->getPackages() as $package) {
  757. $constraint = new Constraint('=', $package->getVersion());
  758. $constraint->setPrettyString($package->getPrettyVersion());
  759. $requires[$package->getName()] = $constraint;
  760. }
  761. }
  762. $rootConstraints = array();
  763. foreach ($requires as $req => $constraint) {
  764. // skip platform requirements from the root package to avoid filtering out existing platform packages
  765. if ($this->ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  766. continue;
  767. }
  768. if ($constraint instanceof Link) {
  769. $rootConstraints[$req] = $constraint->getConstraint();
  770. } else {
  771. $rootConstraints[$req] = $constraint;
  772. }
  773. }
  774. return new RepositorySet($rootAliases, $minimumStability, $stabilityFlags, $rootConstraints);
  775. }
  776. /**
  777. * @return DefaultPolicy
  778. */
  779. private function createPolicy()
  780. {
  781. $preferStable = null;
  782. $preferLowest = null;
  783. if (!$this->update) {
  784. $preferStable = $this->locker->getPreferStable();
  785. $preferLowest = $this->locker->getPreferLowest();
  786. }
  787. // old lock file without prefer stable/lowest will return null
  788. // so in this case we use the composer.json info
  789. if (null === $preferStable) {
  790. $preferStable = $this->preferStable || $this->package->getPreferStable();
  791. }
  792. if (null === $preferLowest) {
  793. $preferLowest = $this->preferLowest;
  794. }
  795. return new DefaultPolicy($preferStable, $preferLowest);
  796. }
  797. /**
  798. * @param RootPackageInterface $rootPackage
  799. * @param PlatformRepository $platformRepo
  800. * @return Request
  801. */
  802. private function createRequest(RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
  803. {
  804. $request = new Request();
  805. $constraint = new Constraint('=', $rootPackage->getVersion());
  806. $constraint->setPrettyString($rootPackage->getPrettyVersion());
  807. $request->install($rootPackage->getName(), $constraint);
  808. $fixedPackages = $platformRepo->getPackages();
  809. if ($this->additionalInstalledRepository) {
  810. $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
  811. $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
  812. }
  813. // fix the version of all platform packages + additionally installed packages
  814. // to prevent the solver trying to remove or update those
  815. $provided = $rootPackage->getProvides();
  816. foreach ($fixedPackages as $package) {
  817. $constraint = new Constraint('=', $package->getVersion());
  818. $constraint->setPrettyString($package->getPrettyVersion());
  819. // skip platform packages that are provided by the root package
  820. if ($package->getRepository() !== $platformRepo
  821. || !isset($provided[$package->getName()])
  822. || !$provided[$package->getName()]->getConstraint()->matches($constraint)
  823. ) {
  824. $request->fix($package->getName(), $constraint);
  825. }
  826. }
  827. return $request;
  828. }
  829. /**
  830. * @param WritableRepositoryInterface $localRepo
  831. * @param Pool $pool
  832. * @param PolicyInterface $policy
  833. * @param array $repositories
  834. * @param RepositoryInterface $installedRepo
  835. * @param RepositoryInterface $lockedRepository
  836. * @param string $task
  837. * @param array|null $operations
  838. * @return array
  839. */
  840. private function processDevPackages($localRepo, Pool $pool, $policy, $repositories, $installedRepo, $lockedRepository, $task, array $operations = null)
  841. {
  842. if ($task === 'force-updates' && null === $operations) {
  843. throw new \InvalidArgumentException('Missing operations argument');
  844. }
  845. if ($task === 'force-links') {
  846. $operations = array();
  847. }
  848. if ($this->update && $this->updateWhitelist) {
  849. $currentPackages = $this->getCurrentPackages($installedRepo);
  850. }
  851. foreach ($localRepo->getCanonicalPackages() as $package) {
  852. // skip non-dev packages
  853. if (!$package->isDev()) {
  854. continue;
  855. }
  856. // skip packages that will be updated/uninstalled
  857. foreach ($operations as $operation) {
  858. if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
  859. || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package))
  860. ) {
  861. continue 2;
  862. }
  863. }
  864. if ($this->update) {
  865. // skip package if the whitelist is enabled and it is not in it
  866. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  867. // check if non-updateable packages are out of date compared to the lock file to ensure we don't corrupt it
  868. foreach ($currentPackages as $curPackage) {
  869. if ($curPackage->isDev() && $curPackage->getName() === $package->getName() && $curPackage->getVersion() === $package->getVersion()) {
  870. if ($task === 'force-links') {
  871. $package->setRequires($curPackage->getRequires());
  872. $package->setConflicts($curPackage->getConflicts());
  873. $package->setProvides($curPackage->getProvides());
  874. $package->setReplaces($curPackage->getReplaces());
  875. } elseif ($task === 'force-updates') {
  876. if (($curPackage->getSourceReference() && $curPackage->getSourceReference() !== $package->getSourceReference())
  877. || ($curPackage->getDistReference() && $curPackage->getDistReference() !== $package->getDistReference())
  878. ) {
  879. $operations[] = new UpdateOperation($package, $curPackage);
  880. }
  881. }
  882. break;
  883. }
  884. }
  885. continue;
  886. }
  887. // find similar packages (name/version) in all repositories
  888. $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion()), true);
  889. foreach ($matches as $index => $match) {
  890. // skip local packages
  891. if (!in_array($match->getRepository(), $repositories, true)) {
  892. unset($matches[$index]);
  893. continue;
  894. }
  895. $matches[$index] = $match->getId();
  896. }
  897. // select preferred package according to policy rules
  898. if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) {
  899. $newPackage = $pool->literalToPackage($matches[0]);
  900. if ($task === 'force-links' && $newPackage) {
  901. $package->setRequires($newPackage->getRequires());
  902. $package->setConflicts($newPackage->getConflicts());
  903. $package->setProvides($newPackage->getProvides());
  904. $package->setReplaces($newPackage->getReplaces());
  905. }
  906. if (
  907. $task === 'force-updates'
  908. && $newPackage
  909. && (
  910. ($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference())
  911. || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference())
  912. )
  913. ) {
  914. $operations[] = new UpdateOperation($package, $newPackage);
  915. continue;
  916. }
  917. }
  918. if ($task === 'force-updates') {
  919. // force installed package to update to referenced version in root package if it does not match the installed version
  920. $references = $this->package->getReferences();
  921. if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) {
  922. // changing the source ref to update to will be handled in the operations loop
  923. $operations[] = new UpdateOperation($package, clone $package);
  924. }
  925. }
  926. } else {
  927. // force update to locked version if it does not match the installed version
  928. foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) {
  929. if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) {
  930. if ($task === 'force-links') {
  931. $package->setRequires($lockedPackage->getRequires());
  932. $package->setConflicts($lockedPackage->getConflicts());
  933. $package->setProvides($lockedPackage->getProvides());
  934. $package->setReplaces($lockedPackage->getReplaces());
  935. } elseif ($task === 'force-updates') {
  936. if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference())
  937. || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference())
  938. ) {
  939. $operations[] = new UpdateOperation($package, $lockedPackage);
  940. }
  941. }
  942. break;
  943. }
  944. }
  945. }
  946. }
  947. return $operations;
  948. }
  949. /**
  950. * Loads the most "current" list of packages that are installed meaning from lock ideally or from installed repo as fallback
  951. * @param RepositoryInterface $installedRepo
  952. * @return array
  953. */
  954. private function getCurrentPackages($installedRepo)
  955. {
  956. if ($this->locker->isLocked()) {
  957. try {
  958. return $this->locker->getLockedRepository(true)->getPackages();
  959. } catch (\RuntimeException $e) {
  960. // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
  961. return $this->locker->getLockedRepository()->getPackages();
  962. }
  963. }
  964. return $installedRepo->getPackages();
  965. }
  966. /**
  967. * @return array
  968. */
  969. private function getRootAliases()
  970. {
  971. if ($this->update) {
  972. $aliases = $this->package->getAliases();
  973. } else {
  974. $aliases = $this->locker->getAliases();
  975. }
  976. $normalizedAliases = array();
  977. foreach ($aliases as $alias) {
  978. $normalizedAliases[$alias['package']][$alias['version']] = array(
  979. 'alias' => $alias['alias'],
  980. 'alias_normalized' => $alias['alias_normalized'],
  981. );
  982. }
  983. return $normalizedAliases;
  984. }
  985. /**
  986. * @param Pool $pool
  987. * @param PolicyInterface $policy
  988. * @param WritableRepositoryInterface $localRepo
  989. * @param array $repositories
  990. */
  991. private function processPackageUrls(Pool $pool, $policy, $localRepo, $repositories)
  992. {
  993. if (!$this->update) {
  994. return;
  995. }
  996. $rootRefs = $this->package->getReferences();
  997. foreach ($localRepo->getCanonicalPackages() as $package) {
  998. // find similar packages (name/version) in pool
  999. $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion()), true);
  1000. foreach ($matches as $index => $match) {
  1001. // skip local packages
  1002. if (!in_array($match->getRepository(), $repositories, true)) {
  1003. unset($matches[$index]);
  1004. continue;
  1005. }
  1006. $matches[$index] = $match->getId();
  1007. }
  1008. // select preferred package according to policy rules
  1009. if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) {
  1010. $newPackage = $pool->literalToPackage($matches[0]);
  1011. // update the dist and source URLs
  1012. $sourceUrl = $package->getSourceUrl();
  1013. $newSourceUrl = $newPackage->getSourceUrl();
  1014. $newReference = $newPackage->getSourceReference();
  1015. if ($package->isDev() && isset($rootRefs[$package->getName()]) && $package->getSourceReference() === $rootRefs[$package->getName()]) {
  1016. $newReference = $rootRefs[$package->getName()];
  1017. }
  1018. $this->updatePackageUrl($package, $newSourceUrl, $newPackage->getSourceType(), $newReference, $newPackage->getDistUrl());
  1019. if ($package instanceof CompletePackage && $newPackage instanceof CompletePackage) {
  1020. $package->setAbandoned($newPackage->getReplacementPackage() ?: $newPackage->isAbandoned());
  1021. }
  1022. $package->setDistMirrors($newPackage->getDistMirrors());
  1023. $package->setSourceMirrors($newPackage->getSourceMirrors());
  1024. }
  1025. }
  1026. }
  1027. private function updatePackageUrl(PackageInterface $package, $sourceUrl, $sourceType, $sourceReference, $distUrl)
  1028. {
  1029. $oldSourceRef = $package->getSourceReference();
  1030. if ($package->getSourceUrl() !== $sourceUrl) {
  1031. $package->setSourceType($sourceType);
  1032. $package->setSourceUrl($sourceUrl);
  1033. $package->setSourceReference($sourceReference);
  1034. }
  1035. // only update dist url for github/bitbucket/gitlab dists as they use a combination of dist url + dist reference to install
  1036. // but for other urls this is ambiguous and could result in bad outcomes
  1037. if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i', $distUrl)) {
  1038. $package->setDistUrl($distUrl);
  1039. $this->updateInstallReferences($package, $sourceReference);
  1040. }
  1041. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  1042. $this->updateInstallReferences($package, $oldSourceRef);
  1043. }
  1044. }
  1045. private function updateInstallReferences(PackageInterface $package, $reference)
  1046. {
  1047. if (!$reference) {
  1048. return;
  1049. }
  1050. $package->setSourceReference($reference);
  1051. if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i', $package->getDistUrl())) {
  1052. $package->setDistReference($reference);
  1053. $package->setDistUrl(preg_replace('{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i', $reference, $package->getDistUrl()));
  1054. } elseif ($package->getDistReference()) { // update the dist reference if there was one, but if none was provided ignore it
  1055. $package->setDistReference($reference);
  1056. }
  1057. }
  1058. /**
  1059. * @param PlatformRepository $platformRepo
  1060. * @param array $aliases
  1061. */
  1062. private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases)
  1063. {
  1064. foreach ($aliases as $package => $versions) {
  1065. foreach ($versions as $version => $alias) {
  1066. $packages = $platformRepo->findPackages($package, $version);
  1067. foreach ($packages as $package) {
  1068. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  1069. $aliasPackage->setRootPackageAlias(true);
  1070. $platformRepo->addPackage($aliasPackage);
  1071. }
  1072. }
  1073. }
  1074. }
  1075. /**
  1076. * @param PackageInterface $package
  1077. * @return bool
  1078. */
  1079. private function isUpdateable(PackageInterface $package)
  1080. {
  1081. if (!$this->updateWhitelist) {
  1082. throw new \LogicException('isUpdateable should only be called when a whitelist is present');
  1083. }
  1084. foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
  1085. $patternRegexp = BasePackage::packageNameToRegexp($whiteListedPattern);
  1086. if (preg_match($patternRegexp, $package->getName())) {
  1087. return true;
  1088. }
  1089. }
  1090. return false;
  1091. }
  1092. /**
  1093. * @param array $links
  1094. * @return array
  1095. */
  1096. private function extractPlatformRequirements($links)
  1097. {
  1098. $platformReqs = array();
  1099. foreach ($links as $link) {
  1100. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  1101. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  1102. }
  1103. }
  1104. return $platformReqs;
  1105. }
  1106. /**
  1107. * Adds all dependencies of the update whitelist to the whitelist, too.
  1108. *
  1109. * Packages which are listed as requirements in the root package will be
  1110. * skipped including their dependencies, unless they are listed in the
  1111. * update whitelist themselves or $whitelistAllDependencies is true.
  1112. *
  1113. * @param RepositoryInterface $localOrLockRepo Use the locked repo if available, otherwise installed repo will do
  1114. * As we want the most accurate package list to work with, and installed
  1115. * repo might be empty but locked repo will always be current.
  1116. * @param array $rootRequires An array of links to packages in require of the root package
  1117. * @param array $rootDevRequires An array of links to packages in require-dev of the root package
  1118. */
  1119. private function whitelistUpdateDependencies($localOrLockRepo, array $rootRequires, array $rootDevRequires)
  1120. {
  1121. if (!$this->updateWhitelist) {
  1122. return;
  1123. }
  1124. $rootRequires = array_merge($rootRequires, $rootDevRequires);
  1125. $skipPackages = array();
  1126. if (!$this->whitelistAllDependencies) {
  1127. foreach ($rootRequires as $require) {
  1128. $skipPackages[$require->getTarget()] = true;
  1129. }
  1130. }
  1131. $repositorySet = new RepositorySet(array(), 'dev');
  1132. $repositorySet->addRepository($localOrLockRepo);
  1133. $seen = array();
  1134. $rootRequiredPackageNames = array_keys($rootRequires);
  1135. foreach ($this->updateWhitelist as $packageName => $void) {
  1136. $packageQueue = new \SplQueue;
  1137. $depPackages = $repositorySet->findPackages($packageName, null, false);
  1138. $matchesByPattern = array();
  1139. // check if the name is a glob pattern that did not match directly
  1140. if (empty($depPackages)) {
  1141. // add any installed package matching the whitelisted name/pattern
  1142. $whitelistPatternSearchRegexp = BasePackage::packageNameToRegexp($packageName, '^%s$');
  1143. foreach ($localOrLockRepo->search($whitelistPatternSearchRegexp) as $installedPackage) {
  1144. $matchesByPattern[] = $repositorySet->findPackages($installedPackage['name'], null, false);
  1145. }
  1146. // add root requirements which match the whitelisted name/pattern
  1147. $whitelistPatternRegexp = BasePackage::packageNameToRegexp($packageName);
  1148. foreach ($rootRequiredPackageNames as $rootRequiredPackageName) {
  1149. if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) {
  1150. $nameMatchesRequiredPackage = true;
  1151. break;
  1152. }
  1153. }
  1154. }
  1155. if (!empty($matchesByPattern)) {
  1156. $depPackages = array_merge($depPackages, call_user_func_array('array_merge', $matchesByPattern));
  1157. }
  1158. if (count($depPackages) == 0 && !$nameMatchesRequiredPackage && !in_array($packageName, array('nothing', 'lock', 'mirrors'))) {
  1159. $this->io->writeError('<warning>Package "' . $packageName . '" listed for update is not installed. Ignoring.</warning>');
  1160. }
  1161. foreach ($depPackages as $depPackage) {
  1162. $packageQueue->enqueue($depPackage);
  1163. }
  1164. while (!$packageQueue->isEmpty()) {
  1165. $package = $packageQueue->dequeue();
  1166. if (isset($seen[spl_object_hash($package)])) {
  1167. continue;
  1168. }
  1169. $seen[spl_object_hash($package)] = true;
  1170. $this->updateWhitelist[$package->getName()] = true;
  1171. if (!$this->whitelistTransitiveDependencies && !$this->whitelistAllDependencies) {
  1172. continue;
  1173. }
  1174. $requires = $package->getRequires();
  1175. foreach ($requires as $require) {
  1176. $requirePackages = $repositorySet->findPackages($require->getTarget(), null, false);
  1177. foreach ($requirePackages as $requirePackage) {
  1178. if (isset($this->updateWhitelist[$requirePackage->getName()])) {
  1179. continue;
  1180. }
  1181. if (isset($skipPackages[$requirePackage->getName()]) && !preg_match(BasePackage::packageNameToRegexp($packageName), $requirePackage->getName())) {
  1182. $this->io->writeError('<warning>Dependency "' . $requirePackage->getName() . '" is also a root requirement, but is not explicitly whitelisted. Ignoring.</warning>');
  1183. continue;
  1184. }
  1185. $packageQueue->enqueue($requirePackage);
  1186. }
  1187. }
  1188. }
  1189. }
  1190. }
  1191. /**
  1192. * Replace local repositories with InstalledArrayRepository instances
  1193. *
  1194. * This is to prevent any accidental modification of the existing repos on disk
  1195. *
  1196. * @param RepositoryManager $rm
  1197. */
  1198. private function mockLocalRepositories(RepositoryManager $rm)
  1199. {
  1200. $packages = array();
  1201. foreach ($rm->getLocalRepository()->getPackages() as $package) {
  1202. $packages[(string) $package] = clone $package;
  1203. }
  1204. foreach ($packages as $key => $package) {
  1205. if ($package instanceof AliasPackage) {
  1206. $alias = (string) $package->getAliasOf();
  1207. $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion());
  1208. }
  1209. }
  1210. $rm->setLocalRepository(
  1211. new InstalledArrayRepository($packages)
  1212. );
  1213. }
  1214. /**
  1215. * Create Installer
  1216. *
  1217. * @param IOInterface $io
  1218. * @param Composer $composer
  1219. * @return Installer
  1220. */
  1221. public static function create(IOInterface $io, Composer $composer)
  1222. {
  1223. return new static(
  1224. $io,
  1225. $composer->getConfig(),
  1226. $composer->getPackage(),
  1227. $composer->getDownloadManager(),
  1228. $composer->getRepositoryManager(),
  1229. $composer->getLocker(),
  1230. $composer->getInstallationManager(),
  1231. $composer->getEventDispatcher(),
  1232. $composer->getAutoloadGenerator()
  1233. );
  1234. }
  1235. /**
  1236. * @param RepositoryInterface $additionalInstalledRepository
  1237. * @return $this
  1238. */
  1239. public function setAdditionalInstalledRepository(RepositoryInterface $additionalInstalledRepository)
  1240. {
  1241. $this->additionalInstalledRepository = $additionalInstalledRepository;
  1242. return $this;
  1243. }
  1244. /**
  1245. * Whether to run in drymode or not
  1246. *
  1247. * @param bool $dryRun
  1248. * @return Installer
  1249. */
  1250. public function setDryRun($dryRun = true)
  1251. {
  1252. $this->dryRun = (bool) $dryRun;
  1253. return $this;
  1254. }
  1255. /**
  1256. * Checks, if this is a dry run (simulation mode).
  1257. *
  1258. * @return bool
  1259. */
  1260. public function isDryRun()
  1261. {
  1262. return $this->dryRun;
  1263. }
  1264. /**
  1265. * prefer source installation
  1266. *
  1267. * @param bool $preferSource
  1268. * @return Installer
  1269. */
  1270. public function setPreferSource($preferSource = true)
  1271. {
  1272. $this->preferSource = (bool) $preferSource;
  1273. return $this;
  1274. }
  1275. /**
  1276. * prefer dist installation
  1277. *
  1278. * @param bool $preferDist
  1279. * @return Installer
  1280. */
  1281. public function setPreferDist($preferDist = true)
  1282. {
  1283. $this->preferDist = (bool) $preferDist;
  1284. return $this;
  1285. }
  1286. /**
  1287. * Whether or not generated autoloader are optimized
  1288. *
  1289. * @param bool $optimizeAutoloader
  1290. * @return Installer
  1291. */
  1292. public function setOptimizeAutoloader($optimizeAutoloader = false)
  1293. {
  1294. $this->optimizeAutoloader = (bool) $optimizeAutoloader;
  1295. if (!$this->optimizeAutoloader) {
  1296. // Force classMapAuthoritative off when not optimizing the
  1297. // autoloader
  1298. $this->setClassMapAuthoritative(false);
  1299. }
  1300. return $this;
  1301. }
  1302. /**
  1303. * Whether or not generated autoloader considers the class map
  1304. * authoritative.
  1305. *
  1306. * @param bool $classMapAuthoritative
  1307. * @return Installer
  1308. */
  1309. public function setClassMapAuthoritative($classMapAuthoritative = false)
  1310. {
  1311. $this->classMapAuthoritative = (bool) $classMapAuthoritative;
  1312. if ($this->classMapAuthoritative) {
  1313. // Force optimizeAutoloader when classmap is authoritative
  1314. $this->setOptimizeAutoloader(true);
  1315. }
  1316. return $this;
  1317. }
  1318. /**
  1319. * Whether or not generated autoloader considers APCu caching.
  1320. *
  1321. * @param bool $apcuAutoloader
  1322. * @return Installer
  1323. */
  1324. public function setApcuAutoloader($apcuAutoloader = false)
  1325. {
  1326. $this->apcuAutoloader = (bool) $apcuAutoloader;
  1327. return $this;
  1328. }
  1329. /**
  1330. * update packages
  1331. *
  1332. * @param bool $update
  1333. * @return Installer
  1334. */
  1335. public function setUpdate($update = true)
  1336. {
  1337. $this->update = (bool) $update;
  1338. return $this;
  1339. }
  1340. /**
  1341. * enables dev packages
  1342. *
  1343. * @param bool $devMode
  1344. * @return Installer
  1345. */
  1346. public function setDevMode($devMode = true)
  1347. {
  1348. $this->devMode = (bool) $devMode;
  1349. return $this;
  1350. }
  1351. /**
  1352. * set whether to run autoloader or not
  1353. *
  1354. * This is disabled implicitly when enabling dryRun
  1355. *
  1356. * @param bool $dumpAutoloader
  1357. * @return Installer
  1358. */
  1359. public function setDumpAutoloader($dumpAutoloader = true)
  1360. {
  1361. $this->dumpAutoloader = (bool) $dumpAutoloader;
  1362. return $this;
  1363. }
  1364. /**
  1365. * set whether to run scripts or not
  1366. *
  1367. * This is disabled implicitly when enabling dryRun
  1368. *
  1369. * @param bool $runScripts
  1370. * @return Installer
  1371. */
  1372. public function setRunScripts($runScripts = true)
  1373. {
  1374. $this->runScripts = (bool) $runScripts;
  1375. return $this;
  1376. }
  1377. /**
  1378. * set the config instance
  1379. *
  1380. * @param Config $config
  1381. * @return Installer
  1382. */
  1383. public function setConfig(Config $config)
  1384. {
  1385. $this->config = $config;
  1386. return $this;
  1387. }
  1388. /**
  1389. * run in verbose mode
  1390. *
  1391. * @param bool $verbose
  1392. * @return Installer
  1393. */
  1394. public function setVerbose($verbose = true)
  1395. {
  1396. $this->verbose = (bool) $verbose;
  1397. return $this;
  1398. }
  1399. /**
  1400. * Checks, if running in verbose mode.
  1401. *
  1402. * @return bool
  1403. */
  1404. public function isVerbose()
  1405. {
  1406. return $this->verbose;
  1407. }
  1408. /**
  1409. * set ignore Platform Package requirements
  1410. *
  1411. * @param bool $ignorePlatformReqs
  1412. * @return Installer
  1413. */
  1414. public function setIgnorePlatformRequirements($ignorePlatformReqs = false)
  1415. {
  1416. $this->ignorePlatformReqs = (bool) $ignorePlatformReqs;
  1417. return $this;
  1418. }
  1419. /**
  1420. * restrict the update operation to a few packages, all other packages
  1421. * that are already installed will be kept at their current version
  1422. *
  1423. * @param array $packages
  1424. * @return Installer
  1425. */
  1426. public function setUpdateWhitelist(array $packages)
  1427. {
  1428. $this->updateWhitelist = array_flip(array_map('strtolower', $packages));
  1429. return $this;
  1430. }
  1431. /**
  1432. * Should dependencies of whitelisted packages (but not direct dependencies) be updated?
  1433. *
  1434. * This will NOT whitelist any dependencies that are also directly defined
  1435. * in the root package.
  1436. *
  1437. * @param bool $updateTransitiveDependencies
  1438. * @return Installer
  1439. */
  1440. public function setWhitelistTransitiveDependencies($updateTransitiveDependencies = true)
  1441. {
  1442. $this->whitelistTransitiveDependencies = (bool) $updateTransitiveDependencies;
  1443. return $this;
  1444. }
  1445. /**
  1446. * Should all dependencies of whitelisted packages be updated recursively?
  1447. *
  1448. * This will whitelist any dependencies of the whitelisted packages, including
  1449. * those defined in the root package.
  1450. *
  1451. * @param bool $updateAllDependencies
  1452. * @return Installer
  1453. */
  1454. public function setWhitelistAllDependencies($updateAllDependencies = true)
  1455. {
  1456. $this->whitelistAllDependencies = (bool) $updateAllDependencies;
  1457. return $this;
  1458. }
  1459. /**
  1460. * Should packages be preferred in a stable version when updating?
  1461. *
  1462. * @param bool $preferStable
  1463. * @return Installer
  1464. */
  1465. public function setPreferStable($preferStable = true)
  1466. {
  1467. $this->preferStable = (bool) $preferStable;
  1468. return $this;
  1469. }
  1470. /**
  1471. * Should packages be preferred in a lowest version when updating?
  1472. *
  1473. * @param bool $preferLowest
  1474. * @return Installer
  1475. */
  1476. public function setPreferLowest($preferLowest = true)
  1477. {
  1478. $this->preferLowest = (bool) $preferLowest;
  1479. return $this;
  1480. }
  1481. /**
  1482. * Should the lock file be updated when updating?
  1483. *
  1484. * This is disabled implicitly when enabling dryRun
  1485. *
  1486. * @param bool $writeLock
  1487. * @return Installer
  1488. */
  1489. public function setWriteLock($writeLock = true)
  1490. {
  1491. $this->writeLock = (bool) $writeLock;
  1492. return $this;
  1493. }
  1494. /**
  1495. * Should the operations (package install, update and removal) be executed on disk?
  1496. *
  1497. * This is disabled implicitly when enabling dryRun
  1498. *
  1499. * @param bool $executeOperations
  1500. * @return Installer
  1501. */
  1502. public function setExecuteOperations($executeOperations = true)
  1503. {
  1504. $this->executeOperations = (bool) $executeOperations;
  1505. return $this;
  1506. }
  1507. /**
  1508. * Should suggestions be skipped?
  1509. *
  1510. * @param bool $skipSuggest
  1511. * @return Installer
  1512. */
  1513. public function setSkipSuggest($skipSuggest = true)
  1514. {
  1515. $this->skipSuggest = (bool) $skipSuggest;
  1516. return $this;
  1517. }
  1518. /**
  1519. * Disables plugins.
  1520. *
  1521. * Call this if you want to ensure that third-party code never gets
  1522. * executed. The default is to automatically install, and execute
  1523. * custom third-party installers.
  1524. *
  1525. * @return Installer
  1526. */
  1527. public function disablePlugins()
  1528. {
  1529. $this->installationManager->disablePlugins();
  1530. return $this;
  1531. }
  1532. /**
  1533. * @param SuggestedPackagesReporter $suggestedPackagesReporter
  1534. * @return Installer
  1535. */
  1536. public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter)
  1537. {
  1538. $this->suggestedPackagesReporter = $suggestedPackagesReporter;
  1539. return $this;
  1540. }
  1541. }