RequireCommand.php 11 KB

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