Installer.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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\Pool;
  19. use Composer\DependencyResolver\Request;
  20. use Composer\DependencyResolver\Rule;
  21. use Composer\DependencyResolver\Solver;
  22. use Composer\DependencyResolver\SolverProblemsException;
  23. use Composer\Downloader\DownloadManager;
  24. use Composer\EventDispatcher\EventDispatcher;
  25. use Composer\Installer\InstallationManager;
  26. use Composer\Installer\InstallerEvents;
  27. use Composer\Installer\NoopInstaller;
  28. use Composer\IO\IOInterface;
  29. use Composer\Json\JsonFile;
  30. use Composer\Package\AliasPackage;
  31. use Composer\Package\CompletePackage;
  32. use Composer\Package\Link;
  33. use Composer\Package\LinkConstraint\VersionConstraint;
  34. use Composer\Package\Locker;
  35. use Composer\Package\PackageInterface;
  36. use Composer\Package\RootPackageInterface;
  37. use Composer\Repository\CompositeRepository;
  38. use Composer\Repository\InstalledArrayRepository;
  39. use Composer\Repository\InstalledFilesystemRepository;
  40. use Composer\Repository\PlatformRepository;
  41. use Composer\Repository\RepositoryInterface;
  42. use Composer\Repository\RepositoryManager;
  43. use Composer\Script\ScriptEvents;
  44. /**
  45. * @author Jordi Boggiano <j.boggiano@seld.be>
  46. * @author Beau Simensen <beau@dflydev.com>
  47. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  48. * @author Nils Adermann <naderman@naderman.de>
  49. */
  50. class Installer
  51. {
  52. /**
  53. * @var IOInterface
  54. */
  55. protected $io;
  56. /**
  57. * @var Config
  58. */
  59. protected $config;
  60. /**
  61. * @var RootPackageInterface
  62. */
  63. protected $package;
  64. /**
  65. * @var DownloadManager
  66. */
  67. protected $downloadManager;
  68. /**
  69. * @var RepositoryManager
  70. */
  71. protected $repositoryManager;
  72. /**
  73. * @var Locker
  74. */
  75. protected $locker;
  76. /**
  77. * @var InstallationManager
  78. */
  79. protected $installationManager;
  80. /**
  81. * @var EventDispatcher
  82. */
  83. protected $eventDispatcher;
  84. /**
  85. * @var AutoloadGenerator
  86. */
  87. protected $autoloadGenerator;
  88. protected $preferSource = false;
  89. protected $preferDist = false;
  90. protected $optimizeAutoloader = false;
  91. protected $devMode = false;
  92. protected $dryRun = false;
  93. protected $verbose = false;
  94. protected $update = false;
  95. protected $runScripts = true;
  96. protected $ignorePlatformReqs = false;
  97. /**
  98. * Array of package names/globs flagged for update
  99. *
  100. * @var array|null
  101. */
  102. protected $updateWhitelist = null;
  103. protected $whitelistDependencies = false;
  104. /**
  105. * @var array
  106. */
  107. protected $suggestedPackages;
  108. /**
  109. * @var RepositoryInterface
  110. */
  111. protected $additionalInstalledRepository;
  112. /**
  113. * Constructor
  114. *
  115. * @param IOInterface $io
  116. * @param Config $config
  117. * @param RootPackageInterface $package
  118. * @param DownloadManager $downloadManager
  119. * @param RepositoryManager $repositoryManager
  120. * @param Locker $locker
  121. * @param InstallationManager $installationManager
  122. * @param EventDispatcher $eventDispatcher
  123. * @param AutoloadGenerator $autoloadGenerator
  124. */
  125. public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
  126. {
  127. $this->io = $io;
  128. $this->config = $config;
  129. $this->package = $package;
  130. $this->downloadManager = $downloadManager;
  131. $this->repositoryManager = $repositoryManager;
  132. $this->locker = $locker;
  133. $this->installationManager = $installationManager;
  134. $this->eventDispatcher = $eventDispatcher;
  135. $this->autoloadGenerator = $autoloadGenerator;
  136. }
  137. /**
  138. * Run installation (or update)
  139. *
  140. * @return int 0 on success or a positive error code on failure
  141. *
  142. * @throws \Exception
  143. */
  144. public function run()
  145. {
  146. gc_disable();
  147. if ($this->dryRun) {
  148. $this->verbose = true;
  149. $this->runScripts = false;
  150. $this->installationManager->addInstaller(new NoopInstaller);
  151. $this->mockLocalRepositories($this->repositoryManager);
  152. }
  153. // TODO remove this BC feature at some point
  154. // purge old require-dev packages to avoid conflicts with the new way of handling dev requirements
  155. $devRepo = new InstalledFilesystemRepository(new JsonFile($this->config->get('vendor-dir').'/composer/installed_dev.json'));
  156. if ($devRepo->getPackages()) {
  157. $this->io->write('<warning>BC Notice: Removing old dev packages to migrate to the new require-dev handling.</warning>');
  158. foreach ($devRepo->getPackages() as $package) {
  159. if ($this->installationManager->isPackageInstalled($devRepo, $package)) {
  160. $this->installationManager->uninstall($devRepo, new UninstallOperation($package));
  161. }
  162. }
  163. unlink($this->config->get('vendor-dir').'/composer/installed_dev.json');
  164. }
  165. unset($devRepo, $package);
  166. // end BC
  167. if ($this->runScripts) {
  168. // dispatch pre event
  169. $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
  170. $this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
  171. }
  172. $this->downloadManager->setPreferSource($this->preferSource);
  173. $this->downloadManager->setPreferDist($this->preferDist);
  174. // clone root package to have one in the installed repo that does not require anything
  175. // we don't want it to be uninstallable, but its requirements should not conflict
  176. // with the lock file for example
  177. $installedRootPackage = clone $this->package;
  178. $installedRootPackage->setRequires(array());
  179. $installedRootPackage->setDevRequires(array());
  180. // create installed repo, this contains all local packages + platform packages (php & extensions)
  181. $localRepo = $this->repositoryManager->getLocalRepository();
  182. $platformRepo = new PlatformRepository();
  183. $repos = array(
  184. $localRepo,
  185. new InstalledArrayRepository(array($installedRootPackage)),
  186. $platformRepo,
  187. );
  188. $installedRepo = new CompositeRepository($repos);
  189. if ($this->additionalInstalledRepository) {
  190. $installedRepo->addRepository($this->additionalInstalledRepository);
  191. }
  192. $aliases = $this->getRootAliases();
  193. $this->aliasPlatformPackages($platformRepo, $aliases);
  194. try {
  195. $this->suggestedPackages = array();
  196. $res = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode);
  197. if ($res !== 0) {
  198. return $res;
  199. }
  200. } catch (\Exception $e) {
  201. $this->installationManager->notifyInstalls();
  202. throw $e;
  203. }
  204. $this->installationManager->notifyInstalls();
  205. // output suggestions if we're in dev mode
  206. if ($this->devMode) {
  207. foreach ($this->suggestedPackages as $suggestion) {
  208. $target = $suggestion['target'];
  209. foreach ($installedRepo->getPackages() as $package) {
  210. if (in_array($target, $package->getNames())) {
  211. continue 2;
  212. }
  213. }
  214. $this->io->write($suggestion['source'].' suggests installing '.$suggestion['target'].' ('.$suggestion['reason'].')');
  215. }
  216. }
  217. # Find abandoned packages and warn user
  218. foreach ($localRepo->getPackages() as $package) {
  219. if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
  220. continue;
  221. }
  222. $replacement = (is_string($package->getReplacementPackage()))
  223. ? 'Use ' . $package->getReplacementPackage() . ' instead'
  224. : 'No replacement was suggested';
  225. $this->io->write(
  226. sprintf(
  227. "<error>Package %s is abandoned, you should avoid using it. %s.</error>",
  228. $package->getPrettyName(),
  229. $replacement
  230. )
  231. );
  232. }
  233. if (!$this->dryRun) {
  234. // write lock
  235. if ($this->update || !$this->locker->isLocked()) {
  236. $localRepo->reload();
  237. // if this is not run in dev mode and the root has dev requires, the lock must
  238. // contain null to prevent dev installs from a non-dev lock
  239. $devPackages = ($this->devMode || !$this->package->getDevRequires()) ? array() : null;
  240. // split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
  241. if ($this->devMode && $this->package->getDevRequires()) {
  242. $policy = $this->createPolicy();
  243. $pool = $this->createPool(true);
  244. $pool->addRepository($installedRepo, $aliases);
  245. // creating requirements request
  246. $request = $this->createRequest($pool, $this->package, $platformRepo);
  247. $request->updateAll();
  248. foreach ($this->package->getRequires() as $link) {
  249. $request->install($link->getTarget(), $link->getConstraint());
  250. }
  251. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $policy, $pool, $installedRepo, $request);
  252. $solver = new Solver($policy, $pool, $installedRepo);
  253. $ops = $solver->solve($request, $this->ignorePlatformReqs);
  254. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $policy, $pool, $installedRepo, $request, $ops);
  255. foreach ($ops as $op) {
  256. if ($op->getJobType() === 'uninstall') {
  257. $devPackages[] = $op->getPackage();
  258. }
  259. }
  260. }
  261. $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
  262. $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
  263. $updatedLock = $this->locker->setLockData(
  264. array_diff($localRepo->getCanonicalPackages(), (array) $devPackages),
  265. $devPackages,
  266. $platformReqs,
  267. $platformDevReqs,
  268. $aliases,
  269. $this->package->getMinimumStability(),
  270. $this->package->getStabilityFlags(),
  271. $this->package->getPreferStable()
  272. );
  273. if ($updatedLock) {
  274. $this->io->write('<info>Writing lock file</info>');
  275. }
  276. }
  277. // write autoloader
  278. if ($this->optimizeAutoloader) {
  279. $this->io->write('<info>Generating optimized autoload files</info>');
  280. } else {
  281. $this->io->write('<info>Generating autoload files</info>');
  282. }
  283. $this->autoloadGenerator->setDevMode($this->devMode);
  284. $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
  285. if ($this->runScripts) {
  286. // dispatch post event
  287. $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
  288. $this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
  289. }
  290. $vendorDir = $this->config->get('vendor-dir');
  291. if (is_dir($vendorDir)) {
  292. touch($vendorDir);
  293. }
  294. }
  295. return 0;
  296. }
  297. protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $withDevReqs)
  298. {
  299. // init vars
  300. $lockedRepository = null;
  301. $repositories = null;
  302. // initialize locker to create aliased packages
  303. $installFromLock = false;
  304. if (!$this->update && $this->locker->isLocked()) {
  305. $installFromLock = true;
  306. try {
  307. $lockedRepository = $this->locker->getLockedRepository($withDevReqs);
  308. } catch (\RuntimeException $e) {
  309. // if there are dev requires, then we really can not install
  310. if ($this->package->getDevRequires()) {
  311. throw $e;
  312. }
  313. // no require-dev in composer.json and the lock file was created with no dev info, so skip them
  314. $lockedRepository = $this->locker->getLockedRepository();
  315. }
  316. }
  317. $this->whitelistUpdateDependencies(
  318. $localRepo,
  319. $withDevReqs,
  320. $this->package->getRequires(),
  321. $this->package->getDevRequires()
  322. );
  323. $this->io->write('<info>Loading composer repositories with package information</info>');
  324. // creating repository pool
  325. $policy = $this->createPolicy();
  326. $pool = $this->createPool($withDevReqs);
  327. $pool->addRepository($installedRepo, $aliases);
  328. if ($installFromLock) {
  329. $pool->addRepository($lockedRepository, $aliases);
  330. }
  331. if (!$installFromLock) {
  332. $repositories = $this->repositoryManager->getRepositories();
  333. foreach ($repositories as $repository) {
  334. $pool->addRepository($repository, $aliases);
  335. }
  336. }
  337. // creating requirements request
  338. $request = $this->createRequest($pool, $this->package, $platformRepo);
  339. if (!$installFromLock) {
  340. // remove unstable packages from the localRepo if they don't match the current stability settings
  341. $removedUnstablePackages = array();
  342. foreach ($localRepo->getPackages() as $package) {
  343. if (
  344. !$pool->isPackageAcceptable($package->getNames(), $package->getStability())
  345. && $this->installationManager->isPackageInstalled($localRepo, $package)
  346. ) {
  347. $removedUnstablePackages[$package->getName()] = true;
  348. $request->remove($package->getName(), new VersionConstraint('=', $package->getVersion()));
  349. }
  350. }
  351. }
  352. if ($this->update) {
  353. $this->io->write('<info>Updating dependencies'.($withDevReqs ? ' (including require-dev)' : '').'</info>');
  354. $request->updateAll();
  355. if ($withDevReqs) {
  356. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  357. } else {
  358. $links = $this->package->getRequires();
  359. }
  360. foreach ($links as $link) {
  361. $request->install($link->getTarget(), $link->getConstraint());
  362. }
  363. // if the updateWhitelist is enabled, packages not in it are also fixed
  364. // to the version specified in the lock, or their currently installed version
  365. if ($this->updateWhitelist) {
  366. if ($this->locker->isLocked()) {
  367. try {
  368. $currentPackages = $this->locker->getLockedRepository($withDevReqs)->getPackages();
  369. } catch (\RuntimeException $e) {
  370. // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
  371. $currentPackages = $this->locker->getLockedRepository()->getPackages();
  372. }
  373. } else {
  374. $currentPackages = $installedRepo->getPackages();
  375. }
  376. // collect packages to fixate from root requirements as well as installed packages
  377. $candidates = array();
  378. foreach ($links as $link) {
  379. $candidates[$link->getTarget()] = true;
  380. }
  381. foreach ($localRepo->getPackages() as $package) {
  382. $candidates[$package->getName()] = true;
  383. }
  384. // fix them to the version in lock (or currently installed) if they are not updateable
  385. foreach ($candidates as $candidate => $dummy) {
  386. foreach ($currentPackages as $curPackage) {
  387. if ($curPackage->getName() === $candidate) {
  388. if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
  389. $constraint = new VersionConstraint('=', $curPackage->getVersion());
  390. $request->install($curPackage->getName(), $constraint);
  391. }
  392. break;
  393. }
  394. }
  395. }
  396. }
  397. } elseif ($installFromLock) {
  398. $this->io->write('<info>Installing dependencies'.($withDevReqs ? ' (including require-dev)' : '').' from lock file</info>');
  399. if (!$this->locker->isFresh()) {
  400. $this->io->write('<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>');
  401. }
  402. foreach ($lockedRepository->getPackages() as $package) {
  403. $version = $package->getVersion();
  404. if (isset($aliases[$package->getName()][$version])) {
  405. $version = $aliases[$package->getName()][$version]['alias_normalized'];
  406. }
  407. $constraint = new VersionConstraint('=', $version);
  408. $constraint->setPrettyString($package->getPrettyVersion());
  409. $request->install($package->getName(), $constraint);
  410. }
  411. foreach ($this->locker->getPlatformRequirements($withDevReqs) as $link) {
  412. $request->install($link->getTarget(), $link->getConstraint());
  413. }
  414. } else {
  415. $this->io->write('<info>Installing dependencies'.($withDevReqs ? ' (including require-dev)' : '').'</info>');
  416. if ($withDevReqs) {
  417. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  418. } else {
  419. $links = $this->package->getRequires();
  420. }
  421. foreach ($links as $link) {
  422. $request->install($link->getTarget(), $link->getConstraint());
  423. }
  424. }
  425. // force dev packages to have the latest links if we update or install from a (potentially new) lock
  426. $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-links');
  427. // solve dependencies
  428. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $policy, $pool, $installedRepo, $request);
  429. $solver = new Solver($policy, $pool, $installedRepo);
  430. try {
  431. $operations = $solver->solve($request, $this->ignorePlatformReqs);
  432. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $policy, $pool, $installedRepo, $request, $operations);
  433. } catch (SolverProblemsException $e) {
  434. $this->io->write('<error>Your requirements could not be resolved to an installable set of packages.</error>');
  435. $this->io->write($e->getMessage());
  436. return max(1, $e->getCode());
  437. }
  438. // force dev packages to be updated if we update or install from a (potentially new) lock
  439. $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-updates', $operations);
  440. // execute operations
  441. if (!$operations) {
  442. $this->io->write('Nothing to install or update');
  443. }
  444. $operations = $this->movePluginsToFront($operations);
  445. $operations = $this->moveUninstallsToFront($operations);
  446. foreach ($operations as $operation) {
  447. // collect suggestions
  448. if ('install' === $operation->getJobType()) {
  449. foreach ($operation->getPackage()->getSuggests() as $target => $reason) {
  450. $this->suggestedPackages[] = array(
  451. 'source' => $operation->getPackage()->getPrettyName(),
  452. 'target' => $target,
  453. 'reason' => $reason,
  454. );
  455. }
  456. }
  457. // not installing from lock, force dev packages' references if they're in root package refs
  458. if (!$installFromLock) {
  459. $package = null;
  460. if ('update' === $operation->getJobType()) {
  461. $package = $operation->getTargetPackage();
  462. } elseif ('install' === $operation->getJobType()) {
  463. $package = $operation->getPackage();
  464. }
  465. if ($package && $package->isDev()) {
  466. $references = $this->package->getReferences();
  467. if (isset($references[$package->getName()])) {
  468. $package->setSourceReference($references[$package->getName()]);
  469. $package->setDistReference($references[$package->getName()]);
  470. }
  471. }
  472. if ('update' === $operation->getJobType()
  473. && $operation->getTargetPackage()->isDev()
  474. && $operation->getTargetPackage()->getVersion() === $operation->getInitialPackage()->getVersion()
  475. && $operation->getTargetPackage()->getSourceReference() === $operation->getInitialPackage()->getSourceReference()
  476. ) {
  477. if ($this->io->isDebug()) {
  478. $this->io->write(' - Skipping update of '. $operation->getTargetPackage()->getPrettyName().' to the same reference-locked version');
  479. $this->io->write('');
  480. }
  481. continue;
  482. }
  483. }
  484. $event = 'Composer\Script\ScriptEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType());
  485. if (defined($event) && $this->runScripts) {
  486. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
  487. }
  488. // output non-alias ops in dry run, output alias ops in debug verbosity
  489. if ($this->dryRun && false === strpos($operation->getJobType(), 'Alias')) {
  490. $this->io->write(' - ' . $operation);
  491. $this->io->write('');
  492. } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
  493. $this->io->write(' - ' . $operation);
  494. $this->io->write('');
  495. }
  496. $this->installationManager->execute($localRepo, $operation);
  497. // output reasons why the operation was ran, only for install/update operations
  498. if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) {
  499. $reason = $operation->getReason();
  500. if ($reason instanceof Rule) {
  501. switch ($reason->getReason()) {
  502. case Rule::RULE_JOB_INSTALL:
  503. $this->io->write(' REASON: Required by root: '.$reason->getPrettyString($pool));
  504. $this->io->write('');
  505. break;
  506. case Rule::RULE_PACKAGE_REQUIRES:
  507. $this->io->write(' REASON: '.$reason->getPrettyString($pool));
  508. $this->io->write('');
  509. break;
  510. }
  511. }
  512. }
  513. $event = 'Composer\Script\ScriptEvents::POST_PACKAGE_'.strtoupper($operation->getJobType());
  514. if (defined($event) && $this->runScripts) {
  515. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
  516. }
  517. if (!$this->dryRun) {
  518. $localRepo->write();
  519. }
  520. }
  521. return 0;
  522. }
  523. /**
  524. * Workaround: if your packages depend on plugins, we must be sure
  525. * that those are installed / updated first; else it would lead to packages
  526. * being installed multiple times in different folders, when running Composer
  527. * twice.
  528. *
  529. * While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
  530. * it at least fixes the symptoms and makes usage of composer possible (again)
  531. * in such scenarios.
  532. *
  533. * @param OperationInterface[] $operations
  534. * @return OperationInterface[] reordered operation list
  535. */
  536. private function movePluginsToFront(array $operations)
  537. {
  538. $installerOps = array();
  539. foreach ($operations as $idx => $op) {
  540. if ($op instanceof InstallOperation) {
  541. $package = $op->getPackage();
  542. } elseif ($op instanceof UpdateOperation) {
  543. $package = $op->getTargetPackage();
  544. } else {
  545. continue;
  546. }
  547. if ($package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer') {
  548. // ignore requirements to platform or composer-plugin-api
  549. $requires = array_keys($package->getRequires());
  550. foreach ($requires as $index => $req) {
  551. if ($req === 'composer-plugin-api' || preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  552. unset($requires[$index]);
  553. }
  554. }
  555. // if there are no other requirements, move the plugin to the top of the op list
  556. if (!count($requires)) {
  557. $installerOps[] = $op;
  558. unset($operations[$idx]);
  559. }
  560. }
  561. }
  562. return array_merge($installerOps, $operations);
  563. }
  564. /**
  565. * Removals of packages should be executed before installations in
  566. * case two packages resolve to the same path (due to custom installers)
  567. *
  568. * @param OperationInterface[] $operations
  569. * @return OperationInterface[] reordered operation list
  570. */
  571. private function moveUninstallsToFront(array $operations)
  572. {
  573. $uninstOps = array();
  574. foreach ($operations as $idx => $op) {
  575. if ($op instanceof UninstallOperation) {
  576. $uninstOps[] = $op;
  577. unset($operations[$idx]);
  578. }
  579. }
  580. return array_merge($uninstOps, $operations);
  581. }
  582. private function createPool($withDevReqs)
  583. {
  584. $minimumStability = $this->package->getMinimumStability();
  585. $stabilityFlags = $this->package->getStabilityFlags();
  586. if (!$this->update && $this->locker->isLocked()) {
  587. $minimumStability = $this->locker->getMinimumStability();
  588. $stabilityFlags = $this->locker->getStabilityFlags();
  589. }
  590. $requires = $this->package->getRequires();
  591. if ($withDevReqs) {
  592. $requires = array_merge($requires, $this->package->getDevRequires());
  593. }
  594. $rootConstraints = array();
  595. foreach ($requires as $req => $constraint) {
  596. // skip platform requirements from the root package to avoid filtering out existing platform packages
  597. if ($this->ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  598. continue;
  599. }
  600. $rootConstraints[$req] = $constraint->getConstraint();
  601. }
  602. return new Pool($minimumStability, $stabilityFlags, $rootConstraints);
  603. }
  604. private function createPolicy()
  605. {
  606. $preferStable = null;
  607. if (!$this->update && $this->locker->isLocked()) {
  608. $preferStable = $this->locker->getPreferStable();
  609. }
  610. // old lock file without prefer stable will return null
  611. // so in this case we use the composer.json info
  612. if (null === $preferStable) {
  613. $preferStable = $this->package->getPreferStable();
  614. }
  615. return new DefaultPolicy($preferStable);
  616. }
  617. private function createRequest(Pool $pool, RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
  618. {
  619. $request = new Request($pool);
  620. $constraint = new VersionConstraint('=', $rootPackage->getVersion());
  621. $constraint->setPrettyString($rootPackage->getPrettyVersion());
  622. $request->install($rootPackage->getName(), $constraint);
  623. $fixedPackages = $platformRepo->getPackages();
  624. if ($this->additionalInstalledRepository) {
  625. $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
  626. $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
  627. }
  628. // fix the version of all platform packages + additionally installed packages
  629. // to prevent the solver trying to remove or update those
  630. $provided = $rootPackage->getProvides();
  631. foreach ($fixedPackages as $package) {
  632. $constraint = new VersionConstraint('=', $package->getVersion());
  633. $constraint->setPrettyString($package->getPrettyVersion());
  634. // skip platform packages that are provided by the root package
  635. if ($package->getRepository() !== $platformRepo
  636. || !isset($provided[$package->getName()])
  637. || !$provided[$package->getName()]->getConstraint()->matches($constraint)
  638. ) {
  639. $request->fix($package->getName(), $constraint);
  640. }
  641. }
  642. return $request;
  643. }
  644. private function processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, $task, array $operations = null)
  645. {
  646. if ($task === 'force-updates' && null === $operations) {
  647. throw new \InvalidArgumentException('Missing operations argument');
  648. }
  649. if ($task === 'force-links') {
  650. $operations = array();
  651. }
  652. foreach ($localRepo->getCanonicalPackages() as $package) {
  653. // skip non-dev packages
  654. if (!$package->isDev()) {
  655. continue;
  656. }
  657. // skip packages that will be updated/uninstalled
  658. foreach ($operations as $operation) {
  659. if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
  660. || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package))
  661. ) {
  662. continue 2;
  663. }
  664. }
  665. // force update to locked version if it does not match the installed version
  666. if ($installFromLock) {
  667. foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) {
  668. if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) {
  669. if ($task === 'force-links') {
  670. $package->setRequires($lockedPackage->getRequires());
  671. $package->setConflicts($lockedPackage->getConflicts());
  672. $package->setProvides($lockedPackage->getProvides());
  673. $package->setReplaces($lockedPackage->getReplaces());
  674. } elseif ($task === 'force-updates') {
  675. if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference())
  676. || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference())
  677. ) {
  678. $operations[] = new UpdateOperation($package, $lockedPackage);
  679. }
  680. }
  681. break;
  682. }
  683. }
  684. } else {
  685. // force update to latest on update
  686. if ($this->update) {
  687. // skip package if the whitelist is enabled and it is not in it
  688. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  689. continue;
  690. }
  691. // find similar packages (name/version) in all repositories
  692. $matches = $pool->whatProvides($package->getName(), new VersionConstraint('=', $package->getVersion()));
  693. foreach ($matches as $index => $match) {
  694. // skip local packages
  695. if (!in_array($match->getRepository(), $repositories, true)) {
  696. unset($matches[$index]);
  697. continue;
  698. }
  699. // skip providers/replacers
  700. if ($match->getName() !== $package->getName()) {
  701. unset($matches[$index]);
  702. continue;
  703. }
  704. $matches[$index] = $match->getId();
  705. }
  706. // select prefered package according to policy rules
  707. if ($matches && $matches = $policy->selectPreferedPackages($pool, array(), $matches)) {
  708. $newPackage = $pool->literalToPackage($matches[0]);
  709. if ($task === 'force-links' && $newPackage) {
  710. $package->setRequires($newPackage->getRequires());
  711. $package->setConflicts($newPackage->getConflicts());
  712. $package->setProvides($newPackage->getProvides());
  713. $package->setReplaces($newPackage->getReplaces());
  714. }
  715. if ($task === 'force-updates' && $newPackage && (
  716. (($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference())
  717. || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference())
  718. )
  719. )) {
  720. $operations[] = new UpdateOperation($package, $newPackage);
  721. }
  722. }
  723. }
  724. if ($task === 'force-updates') {
  725. // force installed package to update to referenced version if it does not match the installed version
  726. $references = $this->package->getReferences();
  727. if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) {
  728. // changing the source ref to update to will be handled in the operations loop below
  729. $operations[] = new UpdateOperation($package, clone $package);
  730. }
  731. }
  732. }
  733. }
  734. return $operations;
  735. }
  736. private function getRootAliases()
  737. {
  738. if (!$this->update && $this->locker->isLocked()) {
  739. $aliases = $this->locker->getAliases();
  740. } else {
  741. $aliases = $this->package->getAliases();
  742. }
  743. $normalizedAliases = array();
  744. foreach ($aliases as $alias) {
  745. $normalizedAliases[$alias['package']][$alias['version']] = array(
  746. 'alias' => $alias['alias'],
  747. 'alias_normalized' => $alias['alias_normalized']
  748. );
  749. }
  750. return $normalizedAliases;
  751. }
  752. private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases)
  753. {
  754. foreach ($aliases as $package => $versions) {
  755. foreach ($versions as $version => $alias) {
  756. $packages = $platformRepo->findPackages($package, $version);
  757. foreach ($packages as $package) {
  758. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  759. $aliasPackage->setRootPackageAlias(true);
  760. $platformRepo->addPackage($aliasPackage);
  761. }
  762. }
  763. }
  764. }
  765. private function isUpdateable(PackageInterface $package)
  766. {
  767. if (!$this->updateWhitelist) {
  768. throw new \LogicException('isUpdateable should only be called when a whitelist is present');
  769. }
  770. foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
  771. $patternRegexp = $this->packageNameToRegexp($whiteListedPattern);
  772. if (preg_match($patternRegexp, $package->getName())) {
  773. return true;
  774. }
  775. }
  776. return false;
  777. }
  778. /**
  779. * Build a regexp from a package name, expanding * globs as required
  780. *
  781. * @param string $whiteListedPattern
  782. * @return string
  783. */
  784. private function packageNameToRegexp($whiteListedPattern)
  785. {
  786. $cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern));
  787. return "{^" . $cleanedWhiteListedPattern . "$}i";
  788. }
  789. private function extractPlatformRequirements($links)
  790. {
  791. $platformReqs = array();
  792. foreach ($links as $link) {
  793. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  794. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  795. }
  796. }
  797. return $platformReqs;
  798. }
  799. /**
  800. * Adds all dependencies of the update whitelist to the whitelist, too.
  801. *
  802. * Packages which are listed as requirements in the root package will be
  803. * skipped including their dependencies, unless they are listed in the
  804. * update whitelist themselves.
  805. *
  806. * @param RepositoryInterface $localRepo
  807. * @param boolean $devMode
  808. * @param array $rootRequires An array of links to packages in require of the root package
  809. * @param array $rootDevRequires An array of links to packages in require-dev of the root package
  810. */
  811. private function whitelistUpdateDependencies($localRepo, $devMode, array $rootRequires, array $rootDevRequires)
  812. {
  813. if (!$this->updateWhitelist) {
  814. return;
  815. }
  816. $requiredPackageNames = array();
  817. foreach (array_merge($rootRequires, $rootDevRequires) as $require) {
  818. $requiredPackageNames[] = $require->getTarget();
  819. }
  820. if ($devMode) {
  821. $rootRequires = array_merge($rootRequires, $rootDevRequires);
  822. }
  823. $skipPackages = array();
  824. foreach ($rootRequires as $require) {
  825. $skipPackages[$require->getTarget()] = true;
  826. }
  827. $pool = new Pool;
  828. $pool->addRepository($localRepo);
  829. $seen = array();
  830. $rootRequiredPackageNames = array_keys($rootRequires);
  831. foreach ($this->updateWhitelist as $packageName => $void) {
  832. $packageQueue = new \SplQueue;
  833. $depPackages = $pool->whatProvides($packageName);
  834. $nameMatchesRequiredPackage = in_array($packageName, $requiredPackageNames, true);
  835. // check if the name is a glob pattern that did not match directly
  836. if (!$nameMatchesRequiredPackage) {
  837. $whitelistPatternRegexp = $this->packageNameToRegexp($packageName);
  838. foreach ($rootRequiredPackageNames as $rootRequiredPackageName) {
  839. if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) {
  840. $nameMatchesRequiredPackage = true;
  841. break;
  842. }
  843. }
  844. }
  845. if (count($depPackages) == 0 && !$nameMatchesRequiredPackage && !in_array($packageName, array('nothing', 'lock'))) {
  846. $this->io->write('<warning>Package "' . $packageName . '" listed for update is not installed. Ignoring.</warning>');
  847. }
  848. foreach ($depPackages as $depPackage) {
  849. $packageQueue->enqueue($depPackage);
  850. }
  851. while (!$packageQueue->isEmpty()) {
  852. $package = $packageQueue->dequeue();
  853. if (isset($seen[$package->getId()])) {
  854. continue;
  855. }
  856. $seen[$package->getId()] = true;
  857. $this->updateWhitelist[$package->getName()] = true;
  858. if (!$this->whitelistDependencies) {
  859. continue;
  860. }
  861. $requires = $package->getRequires();
  862. foreach ($requires as $require) {
  863. $requirePackages = $pool->whatProvides($require->getTarget());
  864. foreach ($requirePackages as $requirePackage) {
  865. if (isset($skipPackages[$requirePackage->getName()])) {
  866. continue;
  867. }
  868. $packageQueue->enqueue($requirePackage);
  869. }
  870. }
  871. }
  872. }
  873. }
  874. /**
  875. * Replace local repositories with InstalledArrayRepository instances
  876. *
  877. * This is to prevent any accidental modification of the existing repos on disk
  878. *
  879. * @param RepositoryManager $rm
  880. */
  881. private function mockLocalRepositories(RepositoryManager $rm)
  882. {
  883. $packages = array();
  884. foreach ($rm->getLocalRepository()->getPackages() as $package) {
  885. $packages[(string) $package] = clone $package;
  886. }
  887. foreach ($packages as $key => $package) {
  888. if ($package instanceof AliasPackage) {
  889. $alias = (string) $package->getAliasOf();
  890. $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion());
  891. }
  892. }
  893. $rm->setLocalRepository(
  894. new InstalledArrayRepository($packages)
  895. );
  896. }
  897. /**
  898. * Create Installer
  899. *
  900. * @param IOInterface $io
  901. * @param Composer $composer
  902. * @return Installer
  903. */
  904. public static function create(IOInterface $io, Composer $composer)
  905. {
  906. return new static(
  907. $io,
  908. $composer->getConfig(),
  909. $composer->getPackage(),
  910. $composer->getDownloadManager(),
  911. $composer->getRepositoryManager(),
  912. $composer->getLocker(),
  913. $composer->getInstallationManager(),
  914. $composer->getEventDispatcher(),
  915. $composer->getAutoloadGenerator()
  916. );
  917. }
  918. public function setAdditionalInstalledRepository(RepositoryInterface $additionalInstalledRepository)
  919. {
  920. $this->additionalInstalledRepository = $additionalInstalledRepository;
  921. return $this;
  922. }
  923. /**
  924. * Whether to run in drymode or not
  925. *
  926. * @param boolean $dryRun
  927. * @return Installer
  928. */
  929. public function setDryRun($dryRun = true)
  930. {
  931. $this->dryRun = (boolean) $dryRun;
  932. return $this;
  933. }
  934. /**
  935. * Checks, if this is a dry run (simulation mode).
  936. *
  937. * @return bool
  938. */
  939. public function isDryRun()
  940. {
  941. return $this->dryRun;
  942. }
  943. /**
  944. * prefer source installation
  945. *
  946. * @param boolean $preferSource
  947. * @return Installer
  948. */
  949. public function setPreferSource($preferSource = true)
  950. {
  951. $this->preferSource = (boolean) $preferSource;
  952. return $this;
  953. }
  954. /**
  955. * prefer dist installation
  956. *
  957. * @param boolean $preferDist
  958. * @return Installer
  959. */
  960. public function setPreferDist($preferDist = true)
  961. {
  962. $this->preferDist = (boolean) $preferDist;
  963. return $this;
  964. }
  965. /**
  966. * Whether or not generated autoloader are optimized
  967. *
  968. * @param bool $optimizeAutoloader
  969. * @return Installer
  970. */
  971. public function setOptimizeAutoloader($optimizeAutoloader = false)
  972. {
  973. $this->optimizeAutoloader = (boolean) $optimizeAutoloader;
  974. return $this;
  975. }
  976. /**
  977. * update packages
  978. *
  979. * @param boolean $update
  980. * @return Installer
  981. */
  982. public function setUpdate($update = true)
  983. {
  984. $this->update = (boolean) $update;
  985. return $this;
  986. }
  987. /**
  988. * enables dev packages
  989. *
  990. * @param boolean $devMode
  991. * @return Installer
  992. */
  993. public function setDevMode($devMode = true)
  994. {
  995. $this->devMode = (boolean) $devMode;
  996. return $this;
  997. }
  998. /**
  999. * set whether to run scripts or not
  1000. *
  1001. * @param boolean $runScripts
  1002. * @return Installer
  1003. */
  1004. public function setRunScripts($runScripts = true)
  1005. {
  1006. $this->runScripts = (boolean) $runScripts;
  1007. return $this;
  1008. }
  1009. /**
  1010. * set the config instance
  1011. *
  1012. * @param Config $config
  1013. * @return Installer
  1014. */
  1015. public function setConfig(Config $config)
  1016. {
  1017. $this->config = $config;
  1018. return $this;
  1019. }
  1020. /**
  1021. * run in verbose mode
  1022. *
  1023. * @param boolean $verbose
  1024. * @return Installer
  1025. */
  1026. public function setVerbose($verbose = true)
  1027. {
  1028. $this->verbose = (boolean) $verbose;
  1029. return $this;
  1030. }
  1031. /**
  1032. * Checks, if running in verbose mode.
  1033. *
  1034. * @return bool
  1035. */
  1036. public function isVerbose()
  1037. {
  1038. return $this->verbose;
  1039. }
  1040. /**
  1041. * set ignore Platform Package requirements
  1042. *
  1043. * @param boolean $ignorePlatformReqs
  1044. * @return Installer
  1045. */
  1046. public function setIgnorePlatformRequirements($ignorePlatformReqs = false)
  1047. {
  1048. $this->ignorePlatformReqs = (boolean) $ignorePlatformReqs;
  1049. return $this;
  1050. }
  1051. /**
  1052. * restrict the update operation to a few packages, all other packages
  1053. * that are already installed will be kept at their current version
  1054. *
  1055. * @param array $packages
  1056. * @return Installer
  1057. */
  1058. public function setUpdateWhitelist(array $packages)
  1059. {
  1060. $this->updateWhitelist = array_flip(array_map('strtolower', $packages));
  1061. return $this;
  1062. }
  1063. /**
  1064. * Should dependencies of whitelisted packages be updated recursively?
  1065. *
  1066. * @param boolean $updateDependencies
  1067. * @return Installer
  1068. */
  1069. public function setWhitelistDependencies($updateDependencies = true)
  1070. {
  1071. $this->whitelistDependencies = (boolean) $updateDependencies;
  1072. return $this;
  1073. }
  1074. /**
  1075. * Disables plugins.
  1076. *
  1077. * Call this if you want to ensure that third-party code never gets
  1078. * executed. The default is to automatically install, and execute
  1079. * custom third-party installers.
  1080. *
  1081. * @return Installer
  1082. */
  1083. public function disablePlugins()
  1084. {
  1085. $this->installationManager->disablePlugins();
  1086. return $this;
  1087. }
  1088. }