Installer.php 48 KB

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