Installer.php 65 KB

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