Installer.php 68 KB

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