Installer.php 68 KB

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