RequireCommand.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. // check for readability by reading the file as is_readable can not be trusted on network-mounts
  90. // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
  91. if (!is_readable($this->file) && false === Silencer::call('file_get_contents', $this->file)) {
  92. $io->writeError('<error>'.$this->file.' is not readable.</error>');
  93. return 1;
  94. }
  95. if (filesize($this->file) === 0) {
  96. file_put_contents($this->file, "{\n}\n");
  97. }
  98. $this->json = new JsonFile($this->file);
  99. $this->composerBackup = file_get_contents($this->json->getPath());
  100. // check for writability by writing to the file as is_writable can not be trusted on network-mounts
  101. // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
  102. if (!is_writable($this->file) && !Silencer::call('file_put_contents', $this->file, $this->composerBackup)) {
  103. $io->writeError('<error>'.$this->file.' is not writable.</error>');
  104. return 1;
  105. }
  106. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  107. $repos = $composer->getRepositoryManager()->getRepositories();
  108. $platformOverrides = $composer->getConfig()->get('platform') ?: array();
  109. // initialize $this->repos as it is used by the parent InitCommand
  110. $this->repos = new CompositeRepository(array_merge(
  111. array(new PlatformRepository(array(), $platformOverrides)),
  112. $repos
  113. ));
  114. if ($composer->getPackage()->getPreferStable()) {
  115. $preferredStability = 'stable';
  116. } else {
  117. $preferredStability = $composer->getPackage()->getMinimumStability();
  118. }
  119. $phpVersion = $this->repos->findPackage('php', '*')->getPrettyVersion();
  120. try {
  121. $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion, $preferredStability, !$input->getOption('no-update'));
  122. } catch (\Exception $e) {
  123. if ($this->newlyCreated) {
  124. throw new \RuntimeException('No composer.json present in the current directory, this may be the cause of the following exception.', 0, $e);
  125. }
  126. throw $e;
  127. }
  128. $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
  129. $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
  130. $requirements = $this->formatRequirements($requirements);
  131. // validate requirements format
  132. $versionParser = new VersionParser();
  133. foreach ($requirements as $package => $constraint) {
  134. if (strtolower($package) === $composer->getPackage()->getName()) {
  135. $io->writeError(sprintf('<error>Root package \'%s\' cannot require itself in its composer.json</error>', $package));
  136. return 1;
  137. }
  138. $versionParser->parseConstraints($constraint);
  139. }
  140. $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages');
  141. if (!$this->updateFileCleanly($this->json, $requirements, $requireKey, $removeKey, $sortPackages)) {
  142. $composerDefinition = $this->json->read();
  143. foreach ($requirements as $package => $version) {
  144. $composerDefinition[$requireKey][$package] = $version;
  145. unset($composerDefinition[$removeKey][$package]);
  146. }
  147. $this->json->write($composerDefinition);
  148. }
  149. $io->writeError('<info>'.$this->file.' has been '.($this->newlyCreated ? 'created' : 'updated').'</info>');
  150. if ($input->getOption('no-update')) {
  151. return 0;
  152. }
  153. try {
  154. return $this->doUpdate($input, $output, $io, $requirements);
  155. } catch (\Exception $e) {
  156. $this->revertComposerFile(false);
  157. throw $e;
  158. }
  159. }
  160. private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements)
  161. {
  162. // Update packages
  163. $this->resetComposer();
  164. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  165. $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
  166. $updateDevMode = !$input->getOption('update-no-dev');
  167. $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
  168. $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
  169. $apcu = $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader');
  170. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
  171. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  172. $install = Installer::create($io, $composer);
  173. $install
  174. ->setVerbose($input->getOption('verbose'))
  175. ->setPreferSource($input->getOption('prefer-source'))
  176. ->setPreferDist($input->getOption('prefer-dist'))
  177. ->setDevMode($updateDevMode)
  178. ->setRunScripts(!$input->getOption('no-scripts'))
  179. ->setSkipSuggest($input->getOption('no-suggest'))
  180. ->setOptimizeAutoloader($optimize)
  181. ->setClassMapAuthoritative($authoritative)
  182. ->setApcuAutoloader($apcu)
  183. ->setUpdate(true)
  184. ->setUpdateWhitelist(array_keys($requirements))
  185. ->setWhitelistTransitiveDependencies($input->getOption('update-with-dependencies'))
  186. ->setWhitelistAllDependencies($input->getOption('update-with-all-dependencies'))
  187. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  188. ->setPreferStable($input->getOption('prefer-stable'))
  189. ->setPreferLowest($input->getOption('prefer-lowest'))
  190. ;
  191. $status = $install->run();
  192. if ($status !== 0) {
  193. $this->revertComposerFile(false);
  194. }
  195. return $status;
  196. }
  197. private function updateFileCleanly($json, array $new, $requireKey, $removeKey, $sortPackages)
  198. {
  199. $contents = file_get_contents($json->getPath());
  200. $manipulator = new JsonManipulator($contents);
  201. foreach ($new as $package => $constraint) {
  202. if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) {
  203. return false;
  204. }
  205. if (!$manipulator->removeSubNode($removeKey, $package)) {
  206. return false;
  207. }
  208. }
  209. file_put_contents($json->getPath(), $manipulator->getContents());
  210. return true;
  211. }
  212. protected function interact(InputInterface $input, OutputInterface $output)
  213. {
  214. return;
  215. }
  216. public function revertComposerFile($hardExit = true)
  217. {
  218. $io = $this->getIO();
  219. if ($this->newlyCreated) {
  220. $io->writeError("\n".'<error>Installation failed, deleting '.$this->file.'.</error>');
  221. unlink($this->json->getPath());
  222. } else {
  223. $io->writeError("\n".'<error>Installation failed, reverting '.$this->file.' to its original content.</error>');
  224. file_put_contents($this->json->getPath(), $this->composerBackup);
  225. }
  226. if ($hardExit) {
  227. exit(1);
  228. }
  229. }
  230. }