RequireCommand.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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\Package\Loader\ArrayLoader;
  22. use Composer\Package\BasePackage;
  23. use Composer\Plugin\CommandEvent;
  24. use Composer\Plugin\PluginEvents;
  25. use Composer\Repository\CompositeRepository;
  26. use Composer\Repository\PlatformRepository;
  27. use Composer\IO\IOInterface;
  28. use Composer\Util\Silencer;
  29. /**
  30. * @author Jérémy Romey <jeremy@free-agent.fr>
  31. * @author Jordi Boggiano <j.boggiano@seld.be>
  32. */
  33. class RequireCommand extends InitCommand
  34. {
  35. private $newlyCreated;
  36. private $firstRequire;
  37. private $json;
  38. private $file;
  39. private $composerBackup;
  40. protected function configure()
  41. {
  42. $this
  43. ->setName('require')
  44. ->setDescription('Adds required packages to your composer.json and installs them.')
  45. ->setDefinition(array(
  46. 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"'),
  47. new InputOption('dev', null, InputOption::VALUE_NONE, 'Add requirement to require-dev.'),
  48. new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'),
  49. new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
  50. new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
  51. new InputOption('fixed', null, InputOption::VALUE_NONE, 'Write fixed version to the composer.json.'),
  52. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  53. new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
  54. new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'),
  55. new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
  56. new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated, except those that are root requirements.'),
  57. new InputOption('update-with-all-dependencies', null, InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements.'),
  58. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  59. new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies.'),
  60. new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies.'),
  61. new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'),
  62. new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
  63. new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'),
  64. new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'),
  65. ))
  66. ->setHelp(
  67. <<<EOT
  68. The require command adds required packages to your composer.json and installs them.
  69. If you do not specify a package, composer will prompt you to search for a package, and given results, provide a list of
  70. matches to require.
  71. If you do not specify a version constraint, composer will choose a suitable one based on the available package versions.
  72. If you do not want to install the new dependencies immediately you can call it with --no-update
  73. Read more at https://getcomposer.org/doc/03-cli.md#require
  74. EOT
  75. )
  76. ;
  77. }
  78. protected function execute(InputInterface $input, OutputInterface $output)
  79. {
  80. if (function_exists('pcntl_async_signals')) {
  81. pcntl_async_signals(true);
  82. pcntl_signal(SIGINT, array($this, 'revertComposerFile'));
  83. pcntl_signal(SIGTERM, array($this, 'revertComposerFile'));
  84. pcntl_signal(SIGHUP, array($this, 'revertComposerFile'));
  85. }
  86. $this->file = Factory::getComposerFile();
  87. $io = $this->getIO();
  88. $this->newlyCreated = !file_exists($this->file);
  89. if ($this->newlyCreated && !file_put_contents($this->file, "{\n}\n")) {
  90. $io->writeError('<error>'.$this->file.' could not be created.</error>');
  91. return 1;
  92. }
  93. // check for readability by reading the file as is_readable can not be trusted on network-mounts
  94. // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
  95. if (!is_readable($this->file) && false === Silencer::call('file_get_contents', $this->file)) {
  96. $io->writeError('<error>'.$this->file.' is not readable.</error>');
  97. return 1;
  98. }
  99. if (filesize($this->file) === 0) {
  100. file_put_contents($this->file, "{\n}\n");
  101. }
  102. $this->json = new JsonFile($this->file);
  103. $this->composerBackup = file_get_contents($this->json->getPath());
  104. // check for writability by writing to the file as is_writable can not be trusted on network-mounts
  105. // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
  106. if (!is_writable($this->file) && !Silencer::call('file_put_contents', $this->file, $this->composerBackup)) {
  107. $io->writeError('<error>'.$this->file.' is not writable.</error>');
  108. return 1;
  109. }
  110. if ($input->getOption('fixed') === true) {
  111. $config = $this->json->read();
  112. $packageType = empty($config['type']) ? 'library' : $config['type'];
  113. /**
  114. * @see https://github.com/composer/composer/pull/8313#issuecomment-532637955
  115. */
  116. if ($packageType !== 'project') {
  117. $io->writeError('<error>"--fixed" option is allowed for "project" package types only to prevent possible misuses.</error>');
  118. if (empty($config['type'])) {
  119. $io->writeError('<error>If your package is not library, you should explicitly specify "type" parameter in composer.json.</error>');
  120. }
  121. return 1;
  122. }
  123. }
  124. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  125. $repos = $composer->getRepositoryManager()->getRepositories();
  126. $platformOverrides = $composer->getConfig()->get('platform') ?: array();
  127. // initialize $this->repos as it is used by the parent InitCommand
  128. $this->repos = new CompositeRepository(array_merge(
  129. array(new PlatformRepository(array(), $platformOverrides)),
  130. $repos
  131. ));
  132. if ($composer->getPackage()->getPreferStable()) {
  133. $preferredStability = 'stable';
  134. } else {
  135. $preferredStability = $composer->getPackage()->getMinimumStability();
  136. }
  137. $phpVersion = $this->repos->findPackage('php', '*')->getPrettyVersion();
  138. try {
  139. $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'), $phpVersion, $preferredStability, !$input->getOption('no-update'), $input->getOption('fixed'));
  140. } catch (\Exception $e) {
  141. if ($this->newlyCreated) {
  142. throw new \RuntimeException('No composer.json present in the current directory, this may be the cause of the following exception.', 0, $e);
  143. }
  144. throw $e;
  145. }
  146. $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
  147. $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
  148. $requirements = $this->formatRequirements($requirements);
  149. // validate requirements format
  150. $versionParser = new VersionParser();
  151. foreach ($requirements as $package => $constraint) {
  152. if (strtolower($package) === $composer->getPackage()->getName()) {
  153. $io->writeError(sprintf('<error>Root package \'%s\' cannot require itself in its composer.json</error>', $package));
  154. return 1;
  155. }
  156. $versionParser->parseConstraints($constraint);
  157. }
  158. $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages');
  159. $this->firstRequire = $this->newlyCreated;
  160. if (!$this->firstRequire) {
  161. $composerDefinition = $this->json->read();
  162. if (empty($composerDefinition['require']) && empty($composerDefinition['require-dev'])) {
  163. $this->firstRequire = true;
  164. }
  165. }
  166. if (!$input->getOption('dry-run') && !$this->updateFileCleanly($this->json, $requirements, $requireKey, $removeKey, $sortPackages)) {
  167. $composerDefinition = $this->json->read();
  168. foreach ($requirements as $package => $version) {
  169. $composerDefinition[$requireKey][$package] = $version;
  170. unset($composerDefinition[$removeKey][$package]);
  171. }
  172. $this->json->write($composerDefinition);
  173. }
  174. $io->writeError('<info>'.$this->file.' has been '.($this->newlyCreated ? 'created' : 'updated').'</info>');
  175. if ($input->getOption('no-update')) {
  176. return 0;
  177. }
  178. try {
  179. return $this->doUpdate($input, $output, $io, $requirements, $requireKey, $removeKey);
  180. } catch (\Exception $e) {
  181. $this->revertComposerFile(false);
  182. throw $e;
  183. }
  184. }
  185. private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements, $requireKey, $removeKey)
  186. {
  187. // Update packages
  188. $this->resetComposer();
  189. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  190. if ($input->getOption('dry-run')) {
  191. $rootPackage = $composer->getPackage();
  192. $links = array(
  193. 'require' => $rootPackage->getRequires(),
  194. 'require-dev' => $rootPackage->getDevRequires(),
  195. );
  196. $loader = new ArrayLoader();
  197. $newLinks = $loader->parseLinks($rootPackage->getName(), $rootPackage->getPrettyVersion(), BasePackage::$supportedLinkTypes[$requireKey]['description'], $requirements);
  198. $links[$requireKey] = array_merge($links[$requireKey], $newLinks);
  199. foreach ($requirements as $package => $constraint) {
  200. unset($links[$removeKey][$package]);
  201. }
  202. $rootPackage->setRequires($links['require']);
  203. $rootPackage->setDevRequires($links['require-dev']);
  204. }
  205. $updateDevMode = !$input->getOption('update-no-dev');
  206. $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader');
  207. $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative');
  208. $apcu = $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader');
  209. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
  210. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  211. $install = Installer::create($io, $composer);
  212. $install
  213. ->setVerbose($input->getOption('verbose'))
  214. ->setPreferSource($input->getOption('prefer-source'))
  215. ->setPreferDist($input->getOption('prefer-dist'))
  216. ->setDevMode($updateDevMode)
  217. ->setRunScripts(!$input->getOption('no-scripts'))
  218. ->setOptimizeAutoloader($optimize)
  219. ->setClassMapAuthoritative($authoritative)
  220. ->setApcuAutoloader($apcu)
  221. ->setUpdate(true)
  222. ->setWhitelistTransitiveDependencies($input->getOption('update-with-dependencies'))
  223. ->setWhitelistAllDependencies($input->getOption('update-with-all-dependencies'))
  224. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  225. ->setPreferStable($input->getOption('prefer-stable'))
  226. ->setPreferLowest($input->getOption('prefer-lowest'))
  227. ->setDryRun($input->getOption('dry-run'))
  228. ;
  229. // if no lock is present, or the file is brand new, we do not do a
  230. // partial update as this is not supported by the Installer
  231. if (!$this->firstRequire && $composer->getConfig()->get('lock')) {
  232. $install->setUpdateWhitelist(array_keys($requirements));
  233. }
  234. $status = $install->run();
  235. if ($status !== 0) {
  236. $this->revertComposerFile(false);
  237. }
  238. return $status;
  239. }
  240. private function updateFileCleanly($json, array $new, $requireKey, $removeKey, $sortPackages)
  241. {
  242. $contents = file_get_contents($json->getPath());
  243. $manipulator = new JsonManipulator($contents);
  244. foreach ($new as $package => $constraint) {
  245. if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) {
  246. return false;
  247. }
  248. if (!$manipulator->removeSubNode($removeKey, $package)) {
  249. return false;
  250. }
  251. }
  252. file_put_contents($json->getPath(), $manipulator->getContents());
  253. return true;
  254. }
  255. protected function interact(InputInterface $input, OutputInterface $output)
  256. {
  257. return;
  258. }
  259. public function revertComposerFile($hardExit = true)
  260. {
  261. $io = $this->getIO();
  262. if ($this->newlyCreated) {
  263. $io->writeError("\n".'<error>Installation failed, deleting '.$this->file.'.</error>');
  264. unlink($this->json->getPath());
  265. } else {
  266. $io->writeError("\n".'<error>Installation failed, reverting '.$this->file.' to its original content.</error>');
  267. file_put_contents($this->json->getPath(), $this->composerBackup);
  268. }
  269. if ($hardExit) {
  270. exit(1);
  271. }
  272. }
  273. }