RequireCommand.php 16 KB

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