Installer.php 66 KB

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