Installer.php 68 KB

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