RequireCommand.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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-plugins', null, InputOption::VALUE_NONE, 'Disables all plugins.'),
  42. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  43. new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
  44. new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
  45. new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated with explicit dependencies.'),
  46. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  47. new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'),
  48. new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
  49. new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'),
  50. ))
  51. ->setHelp(<<<EOT
  52. The require command adds required packages to your composer.json and installs them.
  53. If you do not specify a version constraint, composer will choose a suitable one based on the available package versions.
  54. If you do not want to install the new dependencies immediately you can call it with --no-update
  55. EOT
  56. )
  57. ;
  58. }
  59. protected function execute(InputInterface $input, OutputInterface $output)
  60. {
  61. $file = Factory::getComposerFile();
  62. $io = $this->getIO();
  63. $newlyCreated = !file_exists($file);
  64. if (!file_exists($file) && !file_put_contents($file, "{\n}\n")) {
  65. $io->writeError('<error>'.$file.' could not be created.</error>');
  66. return 1;
  67. }
  68. if (!is_readable($file)) {
  69. $io->writeError('<error>'.$file.' is not readable.</error>');
  70. return 1;
  71. }
  72. if (!is_writable($file)) {
  73. $io->writeError('<error>'.$file.' is not writable.</error>');
  74. return 1;
  75. }
  76. if (filesize($file) === 0) {
  77. file_put_contents($file, "{\n}\n");
  78. }
  79. $json = new JsonFile($file);
  80. $composerDefinition = $json->read();
  81. $composerBackup = file_get_contents($json->getPath());
  82. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  83. $repos = $composer->getRepositoryManager()->getRepositories();
  84. $platformOverrides = $composer->getConfig()->get('platform') ?: array();
  85. // initialize $this->repos as it is used by the parent InitCommand
  86. $this->repos = new CompositeRepository(array_merge(
  87. array(new PlatformRepository(array(), $platformOverrides)),
  88. $repos
  89. ));
  90. $phpVersion = $this->repos->findPackage('php', '*')->getVersion();
  91. $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion);
  92. $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
  93. $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
  94. $baseRequirements = array_key_exists($requireKey, $composerDefinition) ? $composerDefinition[$requireKey] : array();
  95. $requirements = $this->formatRequirements($requirements);
  96. // validate requirements format
  97. $versionParser = new VersionParser();
  98. foreach ($requirements as $constraint) {
  99. $versionParser->parseConstraints($constraint);
  100. }
  101. $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages');
  102. if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey, $removeKey, $sortPackages)) {
  103. foreach ($requirements as $package => $version) {
  104. $baseRequirements[$package] = $version;
  105. if (isset($composerDefinition[$removeKey][$package])) {
  106. unset($composerDefinition[$removeKey][$package]);
  107. }
  108. }
  109. $composerDefinition[$requireKey] = $baseRequirements;
  110. $json->write($composerDefinition);
  111. }
  112. $io->writeError('<info>'.$file.' has been '.($newlyCreated ? 'created' : 'updated').'</info>');
  113. if ($input->getOption('no-update')) {
  114. return 0;
  115. }
  116. $updateDevMode = !$input->getOption('update-no-dev');
  117. $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
  118. $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
  119. // Update packages
  120. $this->resetComposer();
  121. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  122. $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
  123. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
  124. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  125. $install = Installer::create($io, $composer);
  126. $install
  127. ->setVerbose($input->getOption('verbose'))
  128. ->setPreferSource($input->getOption('prefer-source'))
  129. ->setPreferDist($input->getOption('prefer-dist'))
  130. ->setDevMode($updateDevMode)
  131. ->setOptimizeAutoloader($optimize)
  132. ->setClassMapAuthoritative($authoritative)
  133. ->setUpdate(true)
  134. ->setUpdateWhitelist(array_keys($requirements))
  135. ->setWhitelistDependencies($input->getOption('update-with-dependencies'))
  136. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  137. ;
  138. $exception = null;
  139. try {
  140. $status = $install->run();
  141. } catch (\Exception $exception) {
  142. $status = 1;
  143. }
  144. if ($status !== 0) {
  145. if ($newlyCreated) {
  146. $io->writeError("\n".'<error>Installation failed, deleting '.$file.'.</error>');
  147. unlink($json->getPath());
  148. } else {
  149. $io->writeError("\n".'<error>Installation failed, reverting '.$file.' to its original content.</error>');
  150. file_put_contents($json->getPath(), $composerBackup);
  151. }
  152. }
  153. if ($exception) {
  154. throw $exception;
  155. }
  156. return $status;
  157. }
  158. private function updateFileCleanly($json, array $base, array $new, $requireKey, $removeKey, $sortPackages)
  159. {
  160. $contents = file_get_contents($json->getPath());
  161. $manipulator = new JsonManipulator($contents);
  162. foreach ($new as $package => $constraint) {
  163. if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) {
  164. return false;
  165. }
  166. if (!$manipulator->removeSubNode($removeKey, $package)) {
  167. return false;
  168. }
  169. }
  170. file_put_contents($json->getPath(), $manipulator->getContents());
  171. return true;
  172. }
  173. protected function interact(InputInterface $input, OutputInterface $output)
  174. {
  175. return;
  176. }
  177. }