RequireCommand.php 10 KB

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