RequireCommand.php 13 KB

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