Installer.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  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. if ('install' === $operation->getJobType()) {
  476. $this->suggestedPackagesReporter->addSuggestionsFromPackage($operation->getPackage());
  477. }
  478. // updating, force dev packages' references if they're in root package refs
  479. if ($this->update) {
  480. $package = null;
  481. if ('update' === $operation->getJobType()) {
  482. $package = $operation->getTargetPackage();
  483. } elseif ('install' === $operation->getJobType()) {
  484. $package = $operation->getPackage();
  485. }
  486. if ($package && $package->isDev()) {
  487. $references = $this->package->getReferences();
  488. if (isset($references[$package->getName()])) {
  489. $this->updateInstallReferences($package, $references[$package->getName()]);
  490. }
  491. }
  492. if ('update' === $operation->getJobType()
  493. && $operation->getTargetPackage()->isDev()
  494. && $operation->getTargetPackage()->getVersion() === $operation->getInitialPackage()->getVersion()
  495. && (!$operation->getTargetPackage()->getSourceReference() || $operation->getTargetPackage()->getSourceReference() === $operation->getInitialPackage()->getSourceReference())
  496. && (!$operation->getTargetPackage()->getDistReference() || $operation->getTargetPackage()->getDistReference() === $operation->getInitialPackage()->getDistReference())
  497. ) {
  498. $this->io->writeError(' - Skipping update of '. $operation->getTargetPackage()->getPrettyName().' to the same reference-locked version', true, IOInterface::DEBUG);
  499. $this->io->writeError('', true, IOInterface::DEBUG);
  500. continue;
  501. }
  502. }
  503. $event = 'Composer\Installer\PackageEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType());
  504. if (defined($event) && $this->runScripts) {
  505. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
  506. }
  507. // output non-alias ops when not executing operations (i.e. dry run), output alias ops in debug verbosity
  508. if (!$this->executeOperations && false === strpos($operation->getJobType(), 'Alias')) {
  509. $this->io->writeError(' - ' . $operation);
  510. } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
  511. $this->io->writeError(' - ' . $operation);
  512. }
  513. $this->installationManager->execute($localRepo, $operation);
  514. // output reasons why the operation was ran, only for install/update operations
  515. if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) {
  516. $reason = $operation->getReason();
  517. if ($reason instanceof Rule) {
  518. switch ($reason->getReason()) {
  519. case Rule::RULE_JOB_INSTALL:
  520. $this->io->writeError(' REASON: Required by the root package: '.$reason->getPrettyString($pool));
  521. $this->io->writeError('');
  522. break;
  523. case Rule::RULE_PACKAGE_REQUIRES:
  524. $this->io->writeError(' REASON: '.$reason->getPrettyString($pool));
  525. $this->io->writeError('');
  526. break;
  527. }
  528. }
  529. }
  530. $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($operation->getJobType());
  531. if (defined($event) && $this->runScripts) {
  532. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
  533. }
  534. if ($this->executeOperations || $this->writeLock) {
  535. $localRepo->write();
  536. }
  537. }
  538. if ($this->executeOperations) {
  539. // force source/dist urls to be updated for all packages
  540. $this->processPackageUrls($pool, $policy, $localRepo, $repositories);
  541. $localRepo->write();
  542. }
  543. return array(0, $devPackages);
  544. }
  545. /**
  546. * Extracts the dev packages out of the localRepo
  547. *
  548. * This works by faking the operations so we can see what the dev packages
  549. * would be at the end of the operation execution. This lets us then remove
  550. * the dev packages from the list of operations accordingly if we are in a
  551. * --no-dev install or update.
  552. *
  553. * @return array
  554. */
  555. private function extractDevPackages(array $operations, RepositoryInterface $localRepo, PlatformRepository $platformRepo, array $aliases)
  556. {
  557. if (!$this->package->getDevRequires()) {
  558. return array();
  559. }
  560. // fake-apply all operations to this clone of the local repo so we see the complete set of package we would end up with
  561. $tempLocalRepo = clone $localRepo;
  562. foreach ($operations as $operation) {
  563. switch ($operation->getJobType()) {
  564. case 'install':
  565. case 'markAliasInstalled':
  566. if (!$tempLocalRepo->hasPackage($operation->getPackage())) {
  567. $tempLocalRepo->addPackage(clone $operation->getPackage());
  568. }
  569. break;
  570. case 'uninstall':
  571. case 'markAliasUninstalled':
  572. $tempLocalRepo->removePackage($operation->getPackage());
  573. break;
  574. case 'update':
  575. $tempLocalRepo->removePackage($operation->getInitialPackage());
  576. if (!$tempLocalRepo->hasPackage($operation->getTargetPackage())) {
  577. $tempLocalRepo->addPackage(clone $operation->getTargetPackage());
  578. }
  579. break;
  580. default:
  581. throw new \LogicException('Unknown type: '.$operation->getJobType());
  582. }
  583. }
  584. // we have to reload the local repo to handle aliases properly
  585. // but as it is not persisted on disk we use a loader/dumper
  586. // to reload it in memory
  587. $localRepo = new InstalledArrayRepository(array());
  588. $loader = new ArrayLoader(null, true);
  589. $dumper = new ArrayDumper();
  590. foreach ($tempLocalRepo->getCanonicalPackages() as $pkg) {
  591. $localRepo->addPackage($loader->load($dumper->dump($pkg)));
  592. }
  593. unset($tempLocalRepo, $loader, $dumper);
  594. $policy = $this->createPolicy();
  595. $pool = $this->createPool();
  596. $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo);
  597. $pool->addRepository($installedRepo, $aliases);
  598. // creating requirements request without dev requirements
  599. $request = $this->createRequest($this->package, $platformRepo);
  600. $request->updateAll();
  601. foreach ($this->package->getRequires() as $link) {
  602. $request->install($link->getTarget(), $link->getConstraint());
  603. }
  604. // solve deps to see which get removed
  605. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request);
  606. $solver = new Solver($policy, $pool, $installedRepo, $this->io);
  607. $ops = $solver->solve($request, $this->ignorePlatformReqs);
  608. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops);
  609. $devPackages = array();
  610. foreach ($ops as $op) {
  611. if ($op->getJobType() === 'uninstall') {
  612. $devPackages[] = $op->getPackage();
  613. }
  614. }
  615. return $devPackages;
  616. }
  617. /**
  618. * @return OperationInterface[] filtered operations, dev packages are uninstalled and all operations on them ignored
  619. */
  620. private function filterDevPackageOperations(array $devPackages, array $operations, RepositoryInterface $localRepo)
  621. {
  622. $finalOps = array();
  623. $packagesToSkip = array();
  624. foreach ($devPackages as $pkg) {
  625. $packagesToSkip[$pkg->getName()] = true;
  626. if ($installedDevPkg = $localRepo->findPackage($pkg->getName(), '*')) {
  627. if ($installedDevPkg instanceof AliasPackage) {
  628. $finalOps[] = new MarkAliasUninstalledOperation($installedDevPkg, 'non-dev install removing it');
  629. $installedDevPkg = $installedDevPkg->getAliasOf();
  630. }
  631. $finalOps[] = new UninstallOperation($installedDevPkg, 'non-dev install removing it');
  632. }
  633. }
  634. // skip operations applied on dev packages
  635. foreach ($operations as $op) {
  636. $package = $op->getJobType() === 'update' ? $op->getTargetPackage() : $op->getPackage();
  637. if (isset($packagesToSkip[$package->getName()])) {
  638. continue;
  639. }
  640. $finalOps[] = $op;
  641. }
  642. return $finalOps;
  643. }
  644. /**
  645. * Workaround: if your packages depend on plugins, we must be sure
  646. * that those are installed / updated first; else it would lead to packages
  647. * being installed multiple times in different folders, when running Composer
  648. * twice.
  649. *
  650. * While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
  651. * it at least fixes the symptoms and makes usage of composer possible (again)
  652. * in such scenarios.
  653. *
  654. * @param OperationInterface[] $operations
  655. * @return OperationInterface[] reordered operation list
  656. */
  657. private function movePluginsToFront(array $operations)
  658. {
  659. $pluginsNoDeps = array();
  660. $pluginsWithDeps = array();
  661. $pluginRequires = array();
  662. foreach (array_reverse($operations, true) as $idx => $op) {
  663. if ($op instanceof InstallOperation) {
  664. $package = $op->getPackage();
  665. } elseif ($op instanceof UpdateOperation) {
  666. $package = $op->getTargetPackage();
  667. } else {
  668. continue;
  669. }
  670. // is this package a plugin?
  671. $isPlugin = $package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer';
  672. // is this a plugin or a dependency of a plugin?
  673. if ($isPlugin || count(array_intersect($package->getNames(), $pluginRequires))) {
  674. // get the package's requires, but filter out any platform requirements or 'composer-plugin-api'
  675. $requires = array_filter(array_keys($package->getRequires()), function ($req) {
  676. return $req !== 'composer-plugin-api' && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req);
  677. });
  678. // is this a plugin with no meaningful dependencies?
  679. if ($isPlugin && !count($requires)) {
  680. // plugins with no dependencies go to the very front
  681. array_unshift($pluginsNoDeps, $op);
  682. } else {
  683. // capture the requirements for this package so those packages will be moved up as well
  684. $pluginRequires = array_merge($pluginRequires, $requires);
  685. // move the operation to the front
  686. array_unshift($pluginsWithDeps, $op);
  687. }
  688. unset($operations[$idx]);
  689. }
  690. }
  691. return array_merge($pluginsNoDeps, $pluginsWithDeps, $operations);
  692. }
  693. /**
  694. * Removals of packages should be executed before installations in
  695. * case two packages resolve to the same path (due to custom installers)
  696. *
  697. * @param OperationInterface[] $operations
  698. * @return OperationInterface[] reordered operation list
  699. */
  700. private function moveUninstallsToFront(array $operations)
  701. {
  702. $uninstOps = array();
  703. foreach ($operations as $idx => $op) {
  704. if ($op instanceof UninstallOperation) {
  705. $uninstOps[] = $op;
  706. unset($operations[$idx]);
  707. }
  708. }
  709. return array_merge($uninstOps, $operations);
  710. }
  711. /**
  712. * @return RepositoryInterface
  713. */
  714. private function createInstalledRepo(RepositoryInterface $localRepo, PlatformRepository $platformRepo)
  715. {
  716. // clone root package to have one in the installed repo that does not require anything
  717. // we don't want it to be uninstallable, but its requirements should not conflict
  718. // with the lock file for example
  719. $installedRootPackage = clone $this->package;
  720. $installedRootPackage->setRequires(array());
  721. $installedRootPackage->setDevRequires(array());
  722. $repos = array(
  723. $localRepo,
  724. new InstalledArrayRepository(array($installedRootPackage)),
  725. $platformRepo,
  726. );
  727. $installedRepo = new CompositeRepository($repos);
  728. if ($this->additionalInstalledRepository) {
  729. $installedRepo->addRepository($this->additionalInstalledRepository);
  730. }
  731. return $installedRepo;
  732. }
  733. /**
  734. * @param RepositoryInterface|null $lockedRepository
  735. * @return Pool
  736. */
  737. private function createPool(RepositoryInterface $lockedRepository = null)
  738. {
  739. if ($this->update) {
  740. $minimumStability = $this->package->getMinimumStability();
  741. $stabilityFlags = $this->package->getStabilityFlags();
  742. $requires = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  743. } else {
  744. $minimumStability = $this->locker->getMinimumStability();
  745. $stabilityFlags = $this->locker->getStabilityFlags();
  746. $requires = array();
  747. foreach ($lockedRepository->getPackages() as $package) {
  748. $constraint = new Constraint('=', $package->getVersion());
  749. $constraint->setPrettyString($package->getPrettyVersion());
  750. $requires[$package->getName()] = $constraint;
  751. }
  752. }
  753. $rootConstraints = array();
  754. foreach ($requires as $req => $constraint) {
  755. // skip platform requirements from the root package to avoid filtering out existing platform packages
  756. if ($this->ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  757. continue;
  758. }
  759. if ($constraint instanceof Link) {
  760. $rootConstraints[$req] = $constraint->getConstraint();
  761. } else {
  762. $rootConstraints[$req] = $constraint;
  763. }
  764. }
  765. return new Pool($minimumStability, $stabilityFlags, $rootConstraints);
  766. }
  767. /**
  768. * @return DefaultPolicy
  769. */
  770. private function createPolicy()
  771. {
  772. $preferStable = null;
  773. $preferLowest = null;
  774. if (!$this->update) {
  775. $preferStable = $this->locker->getPreferStable();
  776. $preferLowest = $this->locker->getPreferLowest();
  777. }
  778. // old lock file without prefer stable/lowest will return null
  779. // so in this case we use the composer.json info
  780. if (null === $preferStable) {
  781. $preferStable = $this->preferStable || $this->package->getPreferStable();
  782. }
  783. if (null === $preferLowest) {
  784. $preferLowest = $this->preferLowest;
  785. }
  786. return new DefaultPolicy($preferStable, $preferLowest);
  787. }
  788. /**
  789. * @param RootPackageInterface $rootPackage
  790. * @param PlatformRepository $platformRepo
  791. * @return Request
  792. */
  793. private function createRequest(RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
  794. {
  795. $request = new Request();
  796. $constraint = new Constraint('=', $rootPackage->getVersion());
  797. $constraint->setPrettyString($rootPackage->getPrettyVersion());
  798. $request->install($rootPackage->getName(), $constraint);
  799. $fixedPackages = $platformRepo->getPackages();
  800. if ($this->additionalInstalledRepository) {
  801. $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
  802. $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
  803. }
  804. // fix the version of all platform packages + additionally installed packages
  805. // to prevent the solver trying to remove or update those
  806. $provided = $rootPackage->getProvides();
  807. foreach ($fixedPackages as $package) {
  808. $constraint = new Constraint('=', $package->getVersion());
  809. $constraint->setPrettyString($package->getPrettyVersion());
  810. // skip platform packages that are provided by the root package
  811. if ($package->getRepository() !== $platformRepo
  812. || !isset($provided[$package->getName()])
  813. || !$provided[$package->getName()]->getConstraint()->matches($constraint)
  814. ) {
  815. $request->fix($package->getName(), $constraint);
  816. }
  817. }
  818. return $request;
  819. }
  820. /**
  821. * @param WritableRepositoryInterface $localRepo
  822. * @param Pool $pool
  823. * @param PolicyInterface $policy
  824. * @param array $repositories
  825. * @param RepositoryInterface $installedRepo
  826. * @param RepositoryInterface $lockedRepository
  827. * @param string $task
  828. * @param array|null $operations
  829. * @return array
  830. */
  831. private function processDevPackages($localRepo, $pool, $policy, $repositories, $installedRepo, $lockedRepository, $task, array $operations = null)
  832. {
  833. if ($task === 'force-updates' && null === $operations) {
  834. throw new \InvalidArgumentException('Missing operations argument');
  835. }
  836. if ($task === 'force-links') {
  837. $operations = array();
  838. }
  839. if ($this->update && $this->updateWhitelist) {
  840. $currentPackages = $this->getCurrentPackages($installedRepo);
  841. }
  842. foreach ($localRepo->getCanonicalPackages() as $package) {
  843. // skip non-dev packages
  844. if (!$package->isDev()) {
  845. continue;
  846. }
  847. // skip packages that will be updated/uninstalled
  848. foreach ($operations as $operation) {
  849. if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
  850. || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package))
  851. ) {
  852. continue 2;
  853. }
  854. }
  855. if ($this->update) {
  856. // skip package if the whitelist is enabled and it is not in it
  857. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  858. // check if non-updateable packages are out of date compared to the lock file to ensure we don't corrupt it
  859. foreach ($currentPackages as $curPackage) {
  860. if ($curPackage->isDev() && $curPackage->getName() === $package->getName() && $curPackage->getVersion() === $package->getVersion()) {
  861. if ($task === 'force-links') {
  862. $package->setRequires($curPackage->getRequires());
  863. $package->setConflicts($curPackage->getConflicts());
  864. $package->setProvides($curPackage->getProvides());
  865. $package->setReplaces($curPackage->getReplaces());
  866. } elseif ($task === 'force-updates') {
  867. if (($curPackage->getSourceReference() && $curPackage->getSourceReference() !== $package->getSourceReference())
  868. || ($curPackage->getDistReference() && $curPackage->getDistReference() !== $package->getDistReference())
  869. ) {
  870. $operations[] = new UpdateOperation($package, $curPackage);
  871. }
  872. }
  873. break;
  874. }
  875. }
  876. continue;
  877. }
  878. // find similar packages (name/version) in all repositories
  879. $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion()));
  880. foreach ($matches as $index => $match) {
  881. // skip local packages
  882. if (!in_array($match->getRepository(), $repositories, true)) {
  883. unset($matches[$index]);
  884. continue;
  885. }
  886. // skip providers/replacers
  887. if ($match->getName() !== $package->getName()) {
  888. unset($matches[$index]);
  889. continue;
  890. }
  891. $matches[$index] = $match->getId();
  892. }
  893. // select preferred package according to policy rules
  894. if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) {
  895. $newPackage = $pool->literalToPackage($matches[0]);
  896. if ($task === 'force-links' && $newPackage) {
  897. $package->setRequires($newPackage->getRequires());
  898. $package->setConflicts($newPackage->getConflicts());
  899. $package->setProvides($newPackage->getProvides());
  900. $package->setReplaces($newPackage->getReplaces());
  901. }
  902. if ($task === 'force-updates' && $newPackage && ($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference())
  903. || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference())) {
  904. $operations[] = new UpdateOperation($package, $newPackage);
  905. continue;
  906. }
  907. }
  908. if ($task === 'force-updates') {
  909. // force installed package to update to referenced version in root package if it does not match the installed version
  910. $references = $this->package->getReferences();
  911. if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) {
  912. // changing the source ref to update to will be handled in the operations loop
  913. $operations[] = new UpdateOperation($package, clone $package);
  914. }
  915. }
  916. } else {
  917. // force update to locked version if it does not match the installed version
  918. foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) {
  919. if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) {
  920. if ($task === 'force-links') {
  921. $package->setRequires($lockedPackage->getRequires());
  922. $package->setConflicts($lockedPackage->getConflicts());
  923. $package->setProvides($lockedPackage->getProvides());
  924. $package->setReplaces($lockedPackage->getReplaces());
  925. } elseif ($task === 'force-updates') {
  926. if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference())
  927. || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference())
  928. ) {
  929. $operations[] = new UpdateOperation($package, $lockedPackage);
  930. }
  931. }
  932. break;
  933. }
  934. }
  935. }
  936. }
  937. return $operations;
  938. }
  939. /**
  940. * Loads the most "current" list of packages that are installed meaning from lock ideally or from installed repo as fallback
  941. * @param RepositoryInterface $installedRepo
  942. * @return array
  943. */
  944. private function getCurrentPackages($installedRepo)
  945. {
  946. if ($this->locker->isLocked()) {
  947. try {
  948. return $this->locker->getLockedRepository(true)->getPackages();
  949. } catch (\RuntimeException $e) {
  950. // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
  951. return $this->locker->getLockedRepository()->getPackages();
  952. }
  953. }
  954. return $installedRepo->getPackages();
  955. }
  956. /**
  957. * @return array
  958. */
  959. private function getRootAliases()
  960. {
  961. if ($this->update) {
  962. $aliases = $this->package->getAliases();
  963. } else {
  964. $aliases = $this->locker->getAliases();
  965. }
  966. $normalizedAliases = array();
  967. foreach ($aliases as $alias) {
  968. $normalizedAliases[$alias['package']][$alias['version']] = array(
  969. 'alias' => $alias['alias'],
  970. 'alias_normalized' => $alias['alias_normalized'],
  971. );
  972. }
  973. return $normalizedAliases;
  974. }
  975. /**
  976. * @param Pool $pool
  977. * @param PolicyInterface $policy
  978. * @param WritableRepositoryInterface $localRepo
  979. * @param array $repositories
  980. */
  981. private function processPackageUrls($pool, $policy, $localRepo, $repositories)
  982. {
  983. if (!$this->update) {
  984. return;
  985. }
  986. $rootRefs = $this->package->getReferences();
  987. foreach ($localRepo->getCanonicalPackages() as $package) {
  988. // find similar packages (name/version) in all repositories
  989. $matches = $pool->whatProvides($package->getName(), new Constraint('=', $package->getVersion()));
  990. foreach ($matches as $index => $match) {
  991. // skip local packages
  992. if (!in_array($match->getRepository(), $repositories, true)) {
  993. unset($matches[$index]);
  994. continue;
  995. }
  996. // skip providers/replacers
  997. if ($match->getName() !== $package->getName()) {
  998. unset($matches[$index]);
  999. continue;
  1000. }
  1001. $matches[$index] = $match->getId();
  1002. }
  1003. // select preferred package according to policy rules
  1004. if ($matches && $matches = $policy->selectPreferredPackages($pool, array(), $matches)) {
  1005. $newPackage = $pool->literalToPackage($matches[0]);
  1006. // update the dist and source URLs
  1007. $sourceUrl = $package->getSourceUrl();
  1008. $newSourceUrl = $newPackage->getSourceUrl();
  1009. $newReference = $newPackage->getSourceReference();
  1010. if ($package->isDev() && isset($rootRefs[$package->getName()]) && $package->getSourceReference() === $rootRefs[$package->getName()]) {
  1011. $newReference = $rootRefs[$package->getName()];
  1012. }
  1013. $this->updatePackageUrl($package, $newSourceUrl, $newPackage->getSourceType(), $newReference, $newPackage->getDistUrl());
  1014. if ($package instanceof CompletePackage && $newPackage instanceof CompletePackage) {
  1015. $package->setAbandoned($newPackage->getReplacementPackage() ?: $newPackage->isAbandoned());
  1016. }
  1017. $package->setDistMirrors($newPackage->getDistMirrors());
  1018. $package->setSourceMirrors($newPackage->getSourceMirrors());
  1019. }
  1020. }
  1021. }
  1022. private function updatePackageUrl(PackageInterface $package, $sourceUrl, $sourceType, $sourceReference, $distUrl)
  1023. {
  1024. $oldSourceRef = $package->getSourceReference();
  1025. if ($package->getSourceUrl() !== $sourceUrl) {
  1026. $package->setSourceType($sourceType);
  1027. $package->setSourceUrl($sourceUrl);
  1028. $package->setSourceReference($sourceReference);
  1029. }
  1030. // only update dist url for github/bitbucket/gitlab dists as they use a combination of dist url + dist reference to install
  1031. // but for other urls this is ambiguous and could result in bad outcomes
  1032. if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i', $distUrl)) {
  1033. $package->setDistUrl($distUrl);
  1034. $this->updateInstallReferences($package, $sourceReference);
  1035. }
  1036. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  1037. $this->updateInstallReferences($package, $oldSourceRef);
  1038. }
  1039. }
  1040. private function updateInstallReferences(PackageInterface $package, $reference)
  1041. {
  1042. if (!$reference) {
  1043. return;
  1044. }
  1045. $package->setSourceReference($reference);
  1046. if (preg_match('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i', $package->getDistUrl())) {
  1047. $package->setDistReference($reference);
  1048. $package->setDistUrl(preg_replace('{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i', $reference, $package->getDistUrl()));
  1049. } elseif ($package->getDistReference()) { // update the dist reference if there was one, but if none was provided ignore it
  1050. $package->setDistReference($reference);
  1051. }
  1052. }
  1053. /**
  1054. * @param PlatformRepository $platformRepo
  1055. * @param array $aliases
  1056. */
  1057. private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases)
  1058. {
  1059. foreach ($aliases as $package => $versions) {
  1060. foreach ($versions as $version => $alias) {
  1061. $packages = $platformRepo->findPackages($package, $version);
  1062. foreach ($packages as $package) {
  1063. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  1064. $aliasPackage->setRootPackageAlias(true);
  1065. $platformRepo->addPackage($aliasPackage);
  1066. }
  1067. }
  1068. }
  1069. }
  1070. /**
  1071. * @param PackageInterface $package
  1072. * @return bool
  1073. */
  1074. private function isUpdateable(PackageInterface $package)
  1075. {
  1076. if (!$this->updateWhitelist) {
  1077. throw new \LogicException('isUpdateable should only be called when a whitelist is present');
  1078. }
  1079. foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
  1080. $patternRegexp = $this->packageNameToRegexp($whiteListedPattern);
  1081. if (preg_match($patternRegexp, $package->getName())) {
  1082. return true;
  1083. }
  1084. }
  1085. return false;
  1086. }
  1087. /**
  1088. * Build a regexp from a package name, expanding * globs as required
  1089. *
  1090. * @param string $whiteListedPattern
  1091. * @return string
  1092. */
  1093. private function packageNameToRegexp($whiteListedPattern)
  1094. {
  1095. $cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern));
  1096. return "{^" . $cleanedWhiteListedPattern . "$}i";
  1097. }
  1098. /**
  1099. * @param array $links
  1100. * @return array
  1101. */
  1102. private function extractPlatformRequirements($links)
  1103. {
  1104. $platformReqs = array();
  1105. foreach ($links as $link) {
  1106. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  1107. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  1108. }
  1109. }
  1110. return $platformReqs;
  1111. }
  1112. /**
  1113. * Adds all dependencies of the update whitelist to the whitelist, too.
  1114. *
  1115. * Packages which are listed as requirements in the root package will be
  1116. * skipped including their dependencies, unless they are listed in the
  1117. * update whitelist themselves or $whitelistAllDependencies is true.
  1118. *
  1119. * @param RepositoryInterface $localOrLockRepo Use the locked repo if available, otherwise installed repo will do
  1120. * As we want the most accurate package list to work with, and installed
  1121. * repo might be empty but locked repo will always be current.
  1122. * @param array $rootRequires An array of links to packages in require of the root package
  1123. * @param array $rootDevRequires An array of links to packages in require-dev of the root package
  1124. */
  1125. private function whitelistUpdateDependencies($localOrLockRepo, array $rootRequires, array $rootDevRequires)
  1126. {
  1127. if (!$this->updateWhitelist) {
  1128. return;
  1129. }
  1130. $rootRequires = array_merge($rootRequires, $rootDevRequires);
  1131. $requiredPackageNames = array();
  1132. foreach ($rootRequires as $require) {
  1133. $requiredPackageNames[] = $require->getTarget();
  1134. }
  1135. $skipPackages = array();
  1136. if (!$this->whitelistAllDependencies) {
  1137. foreach ($rootRequires as $require) {
  1138. $skipPackages[$require->getTarget()] = true;
  1139. }
  1140. }
  1141. $pool = new Pool('dev');
  1142. $pool->addRepository($localOrLockRepo);
  1143. $seen = array();
  1144. $rootRequiredPackageNames = array_keys($rootRequires);
  1145. foreach ($this->updateWhitelist as $packageName => $void) {
  1146. $packageQueue = new \SplQueue;
  1147. $depPackages = $pool->whatProvides($packageName);
  1148. $nameMatchesRequiredPackage = in_array($packageName, $requiredPackageNames, true);
  1149. // check if the name is a glob pattern that did not match directly
  1150. if (!$nameMatchesRequiredPackage) {
  1151. $whitelistPatternRegexp = $this->packageNameToRegexp($packageName);
  1152. foreach ($rootRequiredPackageNames as $rootRequiredPackageName) {
  1153. if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) {
  1154. $nameMatchesRequiredPackage = true;
  1155. break;
  1156. }
  1157. }
  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[$package->getId()])) {
  1168. continue;
  1169. }
  1170. $seen[$package->getId()] = true;
  1171. $this->updateWhitelist[$package->getName()] = true;
  1172. if (!$this->whitelistDependencies && !$this->whitelistAllDependencies) {
  1173. continue;
  1174. }
  1175. $requires = $package->getRequires();
  1176. foreach ($requires as $require) {
  1177. $requirePackages = $pool->whatProvides($require->getTarget());
  1178. foreach ($requirePackages as $requirePackage) {
  1179. if (isset($this->updateWhitelist[$requirePackage->getName()])) {
  1180. continue;
  1181. }
  1182. if (isset($skipPackages[$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. * @deprecated use setWhitelistTransitiveDependencies instead
  1434. */
  1435. public function setWhitelistDependencies($updateDependencies = true)
  1436. {
  1437. return $this->setWhitelistTransitiveDependencies($updateDependencies);
  1438. }
  1439. /**
  1440. * Should dependencies of whitelisted packages (but not direct dependencies) be updated?
  1441. *
  1442. * This will NOT whitelist any dependencies that are also directly defined
  1443. * in the root package.
  1444. *
  1445. * @param bool $updateTransitiveDependencies
  1446. * @return Installer
  1447. */
  1448. public function setWhitelistTransitiveDependencies($updateTransitiveDependencies = true)
  1449. {
  1450. $this->whitelistDependencies = (bool) $updateTransitiveDependencies;
  1451. return $this;
  1452. }
  1453. /**
  1454. * Should all dependencies of whitelisted packages be updated recursively?
  1455. *
  1456. * This will whitelist any dependencies of the whitelisted packages, including
  1457. * those defined in the root package.
  1458. *
  1459. * @param bool $updateAllDependencies
  1460. * @return Installer
  1461. */
  1462. public function setWhitelistAllDependencies($updateAllDependencies = true)
  1463. {
  1464. $this->whitelistAllDependencies = (bool) $updateAllDependencies;
  1465. return $this;
  1466. }
  1467. /**
  1468. * Should packages be preferred in a stable version when updating?
  1469. *
  1470. * @param bool $preferStable
  1471. * @return Installer
  1472. */
  1473. public function setPreferStable($preferStable = true)
  1474. {
  1475. $this->preferStable = (bool) $preferStable;
  1476. return $this;
  1477. }
  1478. /**
  1479. * Should packages be preferred in a lowest version when updating?
  1480. *
  1481. * @param bool $preferLowest
  1482. * @return Installer
  1483. */
  1484. public function setPreferLowest($preferLowest = true)
  1485. {
  1486. $this->preferLowest = (bool) $preferLowest;
  1487. return $this;
  1488. }
  1489. /**
  1490. * Should the lock file be updated when updating?
  1491. *
  1492. * This is disabled implicitly when enabling dryRun
  1493. *
  1494. * @param bool $writeLock
  1495. * @return Installer
  1496. */
  1497. public function setWriteLock($writeLock = true)
  1498. {
  1499. $this->writeLock = (bool) $writeLock;
  1500. return $this;
  1501. }
  1502. /**
  1503. * Should the operations (package install, update and removal) be executed on disk?
  1504. *
  1505. * This is disabled implicitly when enabling dryRun
  1506. *
  1507. * @param bool $executeOperations
  1508. * @return Installer
  1509. */
  1510. public function setExecuteOperations($executeOperations = true)
  1511. {
  1512. $this->executeOperations = (bool) $executeOperations;
  1513. return $this;
  1514. }
  1515. /**
  1516. * Should suggestions be skipped?
  1517. *
  1518. * @param bool $skipSuggest
  1519. * @return Installer
  1520. */
  1521. public function setSkipSuggest($skipSuggest = true)
  1522. {
  1523. $this->skipSuggest = (bool) $skipSuggest;
  1524. return $this;
  1525. }
  1526. /**
  1527. * Disables plugins.
  1528. *
  1529. * Call this if you want to ensure that third-party code never gets
  1530. * executed. The default is to automatically install, and execute
  1531. * custom third-party installers.
  1532. *
  1533. * @return Installer
  1534. */
  1535. public function disablePlugins()
  1536. {
  1537. $this->installationManager->disablePlugins();
  1538. return $this;
  1539. }
  1540. /**
  1541. * @param SuggestedPackagesReporter $suggestedPackagesReporter
  1542. * @return Installer
  1543. */
  1544. public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter)
  1545. {
  1546. $this->suggestedPackagesReporter = $suggestedPackagesReporter;
  1547. return $this;
  1548. }
  1549. }