RequireCommand.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  48. new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'Do not show package suggestions.'),
  49. new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
  50. new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'),
  51. new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
  52. new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated, except those that are root requirements.'),
  53. new InputOption('update-with-all-dependencies', null, InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements.'),
  54. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  55. new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies.'),
  56. new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies.'),
  57. new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'),
  58. new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
  59. new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'),
  60. new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'),
  61. ))
  62. ->setHelp(
  63. <<<EOT
  64. The require command adds required packages to your composer.json and installs them.
  65. If you do not specify a package, composer will prompt you to search for a package, and given results, provide a list of
  66. matches to require.
  67. If you do not specify a version constraint, composer will choose a suitable one based on the available package versions.
  68. If you do not want to install the new dependencies immediately you can call it with --no-update
  69. Read more at https://getcomposer.org/doc/03-cli.md#require
  70. EOT
  71. )
  72. ;
  73. }
  74. protected function execute(InputInterface $input, OutputInterface $output)
  75. {
  76. if (function_exists('pcntl_async_signals')) {
  77. pcntl_async_signals(true);
  78. pcntl_signal(SIGINT, array($this, 'revertComposerFile'));
  79. pcntl_signal(SIGTERM, array($this, 'revertComposerFile'));
  80. pcntl_signal(SIGHUP, array($this, 'revertComposerFile'));
  81. }
  82. $this->file = Factory::getComposerFile();
  83. $io = $this->getIO();
  84. $this->newlyCreated = !file_exists($this->file);
  85. if ($this->newlyCreated && !file_put_contents($this->file, "{\n}\n")) {
  86. $io->writeError('<error>'.$this->file.' could not be created.</error>');
  87. return 1;
  88. }
  89. if (!is_readable($this->file)) {
  90. $io->writeError('<error>'.$this->file.' is not readable.</error>');
  91. return 1;
  92. }
  93. if (filesize($this->file) === 0) {
  94. file_put_contents($this->file, "{\n}\n");
  95. }
  96. $this->json = new JsonFile($this->file);
  97. $this->composerBackup = file_get_contents($this->json->getPath());
  98. // check for writability by writing to the file as is_writable can not be trusted on network-mounts
  99. // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
  100. if (!is_writable($this->file) && !Silencer::call('file_put_contents', $this->file, $this->composerBackup)) {
  101. $io->writeError('<error>'.$this->file.' is not writable.</error>');
  102. return 1;
  103. }
  104. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  105. $repos = $composer->getRepositoryManager()->getRepositories();
  106. $platformOverrides = $composer->getConfig()->get('platform') ?: array();
  107. // initialize $this->repos as it is used by the parent InitCommand
  108. $this->repos = new CompositeRepository(array_merge(
  109. array(new PlatformRepository(array(), $platformOverrides)),
  110. $repos
  111. ));
  112. if ($composer->getPackage()->getPreferStable()) {
  113. $preferredStability = 'stable';
  114. } else {
  115. $preferredStability = $composer->getPackage()->getMinimumStability();
  116. }
  117. $phpVersion = $this->repos->findPackage('php', '*')->getPrettyVersion();
  118. $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion, $preferredStability, !$input->getOption('no-update'));
  119. $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
  120. $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
  121. $requirements = $this->formatRequirements($requirements);
  122. // validate requirements format
  123. $versionParser = new VersionParser();
  124. foreach ($requirements as $package => $constraint) {
  125. if (strtolower($package) === $composer->getPackage()->getName()) {
  126. $io->writeError(sprintf('<error>Root package \'%s\' cannot require itself in its composer.json</error>', $package));
  127. return 1;
  128. }
  129. $versionParser->parseConstraints($constraint);
  130. }
  131. $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages');
  132. if (!$this->updateFileCleanly($this->json, $requirements, $requireKey, $removeKey, $sortPackages)) {
  133. $composerDefinition = $this->json->read();
  134. foreach ($requirements as $package => $version) {
  135. $composerDefinition[$requireKey][$package] = $version;
  136. unset($composerDefinition[$removeKey][$package]);
  137. }
  138. $this->json->write($composerDefinition);
  139. }
  140. $io->writeError('<info>'.$this->file.' has been '.($this->newlyCreated ? 'created' : 'updated').'</info>');
  141. if ($input->getOption('no-update')) {
  142. return 0;
  143. }
  144. try {
  145. return $this->doUpdate($input, $output, $io, $requirements);
  146. } catch (\Exception $e) {
  147. $this->revertComposerFile(false);
  148. throw $e;
  149. }
  150. }
  151. private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements)
  152. {
  153. // Update packages
  154. $this->resetComposer();
  155. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  156. $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
  157. $updateDevMode = !$input->getOption('update-no-dev');
  158. $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
  159. $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
  160. $apcu = $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader');
  161. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
  162. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  163. $install = Installer::create($io, $composer);
  164. $install
  165. ->setVerbose($input->getOption('verbose'))
  166. ->setPreferSource($input->getOption('prefer-source'))
  167. ->setPreferDist($input->getOption('prefer-dist'))
  168. ->setDevMode($updateDevMode)
  169. ->setRunScripts(!$input->getOption('no-scripts'))
  170. ->setSkipSuggest($input->getOption('no-suggest'))
  171. ->setOptimizeAutoloader($optimize)
  172. ->setClassMapAuthoritative($authoritative)
  173. ->setApcuAutoloader($apcu)
  174. ->setUpdate(true)
  175. ->setUpdateWhitelist(array_keys($requirements))
  176. ->setWhitelistTransitiveDependencies($input->getOption('update-with-dependencies'))
  177. ->setWhitelistAllDependencies($input->getOption('update-with-all-dependencies'))
  178. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  179. ->setPreferStable($input->getOption('prefer-stable'))
  180. ->setPreferLowest($input->getOption('prefer-lowest'))
  181. ;
  182. $status = $install->run();
  183. if ($status !== 0) {
  184. $this->revertComposerFile(false);
  185. }
  186. return $status;
  187. }
  188. private function updateFileCleanly($json, array $new, $requireKey, $removeKey, $sortPackages)
  189. {
  190. $contents = file_get_contents($json->getPath());
  191. $manipulator = new JsonManipulator($contents);
  192. foreach ($new as $package => $constraint) {
  193. if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) {
  194. return false;
  195. }
  196. if (!$manipulator->removeSubNode($removeKey, $package)) {
  197. return false;
  198. }
  199. }
  200. file_put_contents($json->getPath(), $manipulator->getContents());
  201. return true;
  202. }
  203. protected function interact(InputInterface $input, OutputInterface $output)
  204. {
  205. return;
  206. }
  207. public function revertComposerFile($hardExit = true)
  208. {
  209. $io = $this->getIO();
  210. if ($this->newlyCreated) {
  211. $io->writeError("\n".'<error>Installation failed, deleting '.$this->file.'.</error>');
  212. unlink($this->json->getPath());
  213. } else {
  214. $io->writeError("\n".'<error>Installation failed, reverting '.$this->file.' to its original content.</error>');
  215. file_put_contents($this->json->getPath(), $this->composerBackup);
  216. }
  217. if ($hardExit) {
  218. exit(1);
  219. }
  220. }
  221. }