RequireCommand.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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\Command;
  12. use Composer\DependencyResolver\Request;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Input\InputArgument;
  15. use Symfony\Component\Console\Input\InputOption;
  16. use Symfony\Component\Console\Output\OutputInterface;
  17. use Composer\Factory;
  18. use Composer\Installer;
  19. use Composer\Json\JsonFile;
  20. use Composer\Json\JsonManipulator;
  21. use Composer\Package\Version\VersionParser;
  22. use Composer\Package\Loader\ArrayLoader;
  23. use Composer\Package\BasePackage;
  24. use Composer\Plugin\CommandEvent;
  25. use Composer\Plugin\PluginEvents;
  26. use Composer\Repository\CompositeRepository;
  27. use Composer\Repository\PlatformRepository;
  28. use Composer\IO\IOInterface;
  29. use Composer\Util\Silencer;
  30. /**
  31. * @author Jérémy Romey <jeremy@free-agent.fr>
  32. * @author Jordi Boggiano <j.boggiano@seld.be>
  33. */
  34. class RequireCommand extends InitCommand
  35. {
  36. private $newlyCreated;
  37. private $firstRequire;
  38. private $json;
  39. private $file;
  40. private $composerBackup;
  41. /** @var string file name */
  42. private $lock;
  43. /** @var ?string contents before modification if the lock file exists */
  44. private $lockBackup;
  45. protected function configure()
  46. {
  47. $this
  48. ->setName('require')
  49. ->setDescription('Adds required packages to your composer.json and installs them.')
  50. ->setDefinition(array(
  51. new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Optional package name can also include a version constraint, e.g. foo/bar or foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  52. new InputOption('dev', null, InputOption::VALUE_NONE, 'Add requirement to require-dev.'),
  53. new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'),
  54. new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
  55. new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
  56. new InputOption('fixed', null, InputOption::VALUE_NONE, 'Write fixed version to the composer.json.'),
  57. new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'DEPRECATED: This flag does not exist anymore.'),
  58. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  59. new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
  60. new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'),
  61. new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
  62. new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated, except those that are root requirements.'),
  63. new InputOption('update-with-all-dependencies', null, InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements.'),
  64. new InputOption('with-dependencies', null, InputOption::VALUE_NONE, 'Alias for --update-with-dependencies'),
  65. new InputOption('with-all-dependencies', null, InputOption::VALUE_NONE, 'Alias for --update-with-all-dependencies'),
  66. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  67. new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies.'),
  68. new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies.'),
  69. new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'),
  70. new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
  71. new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'),
  72. new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'),
  73. ))
  74. ->setHelp(
  75. <<<EOT
  76. The require command adds required packages to your composer.json and installs them.
  77. If you do not specify a package, composer will prompt you to search for a package, and given results, provide a list of
  78. matches to require.
  79. If you do not specify a version constraint, composer will choose a suitable one based on the available package versions.
  80. If you do not want to install the new dependencies immediately you can call it with --no-update
  81. Read more at https://getcomposer.org/doc/03-cli.md#require
  82. EOT
  83. )
  84. ;
  85. }
  86. protected function execute(InputInterface $input, OutputInterface $output)
  87. {
  88. if (function_exists('pcntl_async_signals')) {
  89. pcntl_async_signals(true);
  90. pcntl_signal(SIGINT, array($this, 'revertComposerFile'));
  91. pcntl_signal(SIGTERM, array($this, 'revertComposerFile'));
  92. pcntl_signal(SIGHUP, array($this, 'revertComposerFile'));
  93. }
  94. $this->file = Factory::getComposerFile();
  95. $io = $this->getIO();
  96. if ($input->getOption('no-suggest')) {
  97. $io->writeError('<warning>You are using the deprecated option "--no-suggest". It has no effect and will break in Composer 3.</warning>');
  98. }
  99. $this->newlyCreated = !file_exists($this->file);
  100. if ($this->newlyCreated && !file_put_contents($this->file, "{\n}\n")) {
  101. $io->writeError('<error>'.$this->file.' could not be created.</error>');
  102. return 1;
  103. }
  104. // check for readability by reading the file as is_readable can not be trusted on network-mounts
  105. // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
  106. if (!is_readable($this->file) && false === Silencer::call('file_get_contents', $this->file)) {
  107. $io->writeError('<error>'.$this->file.' is not readable.</error>');
  108. return 1;
  109. }
  110. if (filesize($this->file) === 0) {
  111. file_put_contents($this->file, "{\n}\n");
  112. }
  113. $this->json = new JsonFile($this->file);
  114. $this->lock = Factory::getLockFile($this->file);
  115. $this->composerBackup = file_get_contents($this->json->getPath());
  116. $this->lockBackup = file_exists($this->lock) ? file_get_contents($this->lock) : null;
  117. // check for writability by writing to the file as is_writable can not be trusted on network-mounts
  118. // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
  119. if (!is_writable($this->file) && !Silencer::call('file_put_contents', $this->file, $this->composerBackup)) {
  120. $io->writeError('<error>'.$this->file.' is not writable.</error>');
  121. return 1;
  122. }
  123. if ($input->getOption('fixed') === true) {
  124. $config = $this->json->read();
  125. $packageType = empty($config['type']) ? 'library' : $config['type'];
  126. /**
  127. * @see https://github.com/composer/composer/pull/8313#issuecomment-532637955
  128. */
  129. if ($packageType !== 'project') {
  130. $io->writeError('<error>"--fixed" option is allowed for "project" package types only to prevent possible misuses.</error>');
  131. if (empty($config['type'])) {
  132. $io->writeError('<error>If your package is not library, you should explicitly specify "type" parameter in composer.json.</error>');
  133. }
  134. return 1;
  135. }
  136. }
  137. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  138. $repos = $composer->getRepositoryManager()->getRepositories();
  139. $platformOverrides = $composer->getConfig()->get('platform') ?: array();
  140. // initialize $this->repos as it is used by the parent InitCommand
  141. $this->repos = new CompositeRepository(array_merge(
  142. array(new PlatformRepository(array(), $platformOverrides)),
  143. $repos
  144. ));
  145. if ($composer->getPackage()->getPreferStable()) {
  146. $preferredStability = 'stable';
  147. } else {
  148. $preferredStability = $composer->getPackage()->getMinimumStability();
  149. }
  150. $phpVersion = $this->repos->findPackage('php', '*')->getPrettyVersion();
  151. try {
  152. $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion, $preferredStability, !$input->getOption('no-update'), $input->getOption('fixed'));
  153. } catch (\Exception $e) {
  154. if ($this->newlyCreated) {
  155. throw new \RuntimeException('No composer.json present in the current directory, this may be the cause of the following exception.', 0, $e);
  156. }
  157. throw $e;
  158. }
  159. $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
  160. $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
  161. $requirements = $this->formatRequirements($requirements);
  162. // validate requirements format
  163. $versionParser = new VersionParser();
  164. foreach ($requirements as $package => $constraint) {
  165. if (strtolower($package) === $composer->getPackage()->getName()) {
  166. $io->writeError(sprintf('<error>Root package \'%s\' cannot require itself in its composer.json</error>', $package));
  167. return 1;
  168. }
  169. $versionParser->parseConstraints($constraint);
  170. }
  171. $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages');
  172. $this->firstRequire = $this->newlyCreated;
  173. if (!$this->firstRequire) {
  174. $composerDefinition = $this->json->read();
  175. if (empty($composerDefinition['require']) && empty($composerDefinition['require-dev'])) {
  176. $this->firstRequire = true;
  177. }
  178. }
  179. if (!$input->getOption('dry-run') && !$this->updateFileCleanly($this->json, $requirements, $requireKey, $removeKey, $sortPackages)) {
  180. $composerDefinition = $this->json->read();
  181. foreach ($requirements as $package => $version) {
  182. $composerDefinition[$requireKey][$package] = $version;
  183. unset($composerDefinition[$removeKey][$package]);
  184. }
  185. $this->json->write($composerDefinition);
  186. }
  187. $io->writeError('<info>'.$this->file.' has been '.($this->newlyCreated ? 'created' : 'updated').'</info>');
  188. if ($input->getOption('no-update')) {
  189. return 0;
  190. }
  191. try {
  192. return $this->doUpdate($input, $output, $io, $requirements, $requireKey, $removeKey);
  193. } catch (\Exception $e) {
  194. $this->revertComposerFile(false);
  195. throw $e;
  196. }
  197. }
  198. private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements, $requireKey, $removeKey)
  199. {
  200. // Update packages
  201. $this->resetComposer();
  202. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  203. if ($input->getOption('dry-run')) {
  204. $rootPackage = $composer->getPackage();
  205. $links = array(
  206. 'require' => $rootPackage->getRequires(),
  207. 'require-dev' => $rootPackage->getDevRequires(),
  208. );
  209. $loader = new ArrayLoader();
  210. $newLinks = $loader->parseLinks($rootPackage->getName(), $rootPackage->getPrettyVersion(), BasePackage::$supportedLinkTypes[$requireKey]['description'], $requirements);
  211. $links[$requireKey] = array_merge($links[$requireKey], $newLinks);
  212. foreach ($requirements as $package => $constraint) {
  213. unset($links[$removeKey][$package]);
  214. }
  215. $rootPackage->setRequires($links['require']);
  216. $rootPackage->setDevRequires($links['require-dev']);
  217. }
  218. $updateDevMode = !$input->getOption('update-no-dev');
  219. $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
  220. $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
  221. $apcu = $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader');
  222. $updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED;
  223. if ($input->getOption('update-with-all-dependencies') || $input->getOption('with-all-dependencies')) {
  224. $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS;
  225. } elseif ($input->getOption('update-with-dependencies') || $input->getOption('with-dependencies')) {
  226. $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE;
  227. }
  228. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
  229. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  230. $install = Installer::create($io, $composer);
  231. $install
  232. ->setDryRun($input->getOption('dry-run'))
  233. ->setVerbose($input->getOption('verbose'))
  234. ->setPreferSource($input->getOption('prefer-source'))
  235. ->setPreferDist($input->getOption('prefer-dist'))
  236. ->setDevMode($updateDevMode)
  237. ->setRunScripts(!$input->getOption('no-scripts'))
  238. ->setOptimizeAutoloader($optimize)
  239. ->setClassMapAuthoritative($authoritative)
  240. ->setApcuAutoloader($apcu)
  241. ->setUpdate(true)
  242. ->setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies)
  243. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  244. ->setPreferStable($input->getOption('prefer-stable'))
  245. ->setPreferLowest($input->getOption('prefer-lowest'))
  246. ;
  247. // if no lock is present, or the file is brand new, we do not do a
  248. // partial update as this is not supported by the Installer
  249. if (!$this->firstRequire && $composer->getConfig()->get('lock')) {
  250. $install->setUpdateAllowList(array_keys($requirements));
  251. }
  252. $status = $install->run();
  253. if ($status !== 0) {
  254. $this->revertComposerFile(false);
  255. }
  256. return $status;
  257. }
  258. private function updateFileCleanly($json, array $new, $requireKey, $removeKey, $sortPackages)
  259. {
  260. $contents = file_get_contents($json->getPath());
  261. $manipulator = new JsonManipulator($contents);
  262. foreach ($new as $package => $constraint) {
  263. if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) {
  264. return false;
  265. }
  266. if (!$manipulator->removeSubNode($removeKey, $package)) {
  267. return false;
  268. }
  269. }
  270. file_put_contents($json->getPath(), $manipulator->getContents());
  271. return true;
  272. }
  273. protected function interact(InputInterface $input, OutputInterface $output)
  274. {
  275. return;
  276. }
  277. public function revertComposerFile($hardExit = true)
  278. {
  279. $io = $this->getIO();
  280. if ($this->newlyCreated) {
  281. $io->writeError("\n".'<error>Installation failed, deleting '.$this->file.'.</error>');
  282. unlink($this->json->getPath());
  283. if (file_exists($this->lock)) {
  284. unlink($this->lock);
  285. }
  286. } else {
  287. $msg = ' to its ';
  288. if ($this->lockBackup) {
  289. $msg = ' and '.$this->lock.' to their ';
  290. }
  291. $io->writeError("\n".'<error>Installation failed, reverting '.$this->file.$msg.'original content.</error>');
  292. file_put_contents($this->json->getPath(), $this->composerBackup);
  293. if ($this->lockBackup) {
  294. file_put_contents($this->lock, $this->lockBackup);
  295. }
  296. }
  297. if ($hardExit) {
  298. exit(1);
  299. }
  300. }
  301. }