Installer.php 48 KB

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