Application.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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\Console;
  12. use Composer\IO\NullIO;
  13. use Composer\Util\Platform;
  14. use Composer\Util\Silencer;
  15. use Symfony\Component\Console\Application as BaseApplication;
  16. use Symfony\Component\Console\Exception\CommandNotFoundException;
  17. use Symfony\Component\Console\Input\InputInterface;
  18. use Symfony\Component\Console\Input\InputOption;
  19. use Symfony\Component\Console\Output\OutputInterface;
  20. use Composer\Command;
  21. use Composer\Composer;
  22. use Composer\Factory;
  23. use Composer\IO\IOInterface;
  24. use Composer\IO\ConsoleIO;
  25. use Composer\Json\JsonValidationException;
  26. use Composer\Util\ErrorHandler;
  27. use Composer\EventDispatcher\ScriptExecutionException;
  28. use Composer\Exception\NoSslException;
  29. /**
  30. * The console application that handles the commands
  31. *
  32. * @author Ryan Weaver <ryan@knplabs.com>
  33. * @author Jordi Boggiano <j.boggiano@seld.be>
  34. * @author François Pluchino <francois.pluchino@opendisplay.com>
  35. */
  36. class Application extends BaseApplication
  37. {
  38. /**
  39. * @var Composer
  40. */
  41. protected $composer;
  42. /**
  43. * @var IOInterface
  44. */
  45. protected $io;
  46. private static $logo = ' ______
  47. / ____/___ ____ ___ ____ ____ ________ _____
  48. / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
  49. / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
  50. \____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
  51. /_/
  52. ';
  53. private $hasPluginCommands = false;
  54. private $disablePluginsByDefault = false;
  55. public function __construct()
  56. {
  57. static $shutdownRegistered = false;
  58. if (function_exists('ini_set') && extension_loaded('xdebug')) {
  59. ini_set('xdebug.show_exception_trace', false);
  60. ini_set('xdebug.scream', false);
  61. }
  62. if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
  63. date_default_timezone_set(Silencer::call('date_default_timezone_get'));
  64. }
  65. if (!$shutdownRegistered) {
  66. $shutdownRegistered = true;
  67. register_shutdown_function(function () {
  68. $lastError = error_get_last();
  69. if ($lastError && $lastError['message'] &&
  70. (strpos($lastError['message'], 'Allowed memory') !== false /*Zend PHP out of memory error*/ ||
  71. strpos($lastError['message'], 'exceeded memory') !== false /*HHVM out of memory errors*/)) {
  72. echo "\n". 'Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.';
  73. }
  74. });
  75. }
  76. $this->io = new NullIO();
  77. parent::__construct('Composer', Composer::VERSION);
  78. }
  79. /**
  80. * {@inheritDoc}
  81. */
  82. public function run(InputInterface $input = null, OutputInterface $output = null)
  83. {
  84. if (null === $output) {
  85. $output = Factory::createOutput();
  86. }
  87. return parent::run($input, $output);
  88. }
  89. /**
  90. * {@inheritDoc}
  91. */
  92. public function doRun(InputInterface $input, OutputInterface $output)
  93. {
  94. $this->disablePluginsByDefault = $input->hasParameterOption('--no-plugins');
  95. $io = $this->io = new ConsoleIO($input, $output, $this->getHelperSet());
  96. ErrorHandler::register($io);
  97. // switch working dir
  98. if ($newWorkDir = $this->getNewWorkingDir($input)) {
  99. $oldWorkingDir = getcwd();
  100. chdir($newWorkDir);
  101. $io->writeError('Changed CWD to ' . getcwd(), true, IOInterface::DEBUG);
  102. }
  103. // determine command name to be executed without including plugin commands
  104. $commandName = '';
  105. if ($name = $this->getCommandName($input)) {
  106. try {
  107. $commandName = $this->find($name)->getName();
  108. } catch (CommandNotFoundException $e) {
  109. // we'll check command validity again later after plugins are loaded
  110. $commandName = false;
  111. } catch (\InvalidArgumentException $e) {
  112. }
  113. }
  114. // prompt user for dir change if no composer.json is present in current dir
  115. if ($io->isInteractive() && !$newWorkDir && !in_array($commandName, array('', 'list', 'init', 'about', 'help', 'diagnose', 'self-update', 'global', 'create-project'), true) && !file_exists(Factory::getComposerFile())) {
  116. $dir = dirname(getcwd());
  117. $home = realpath(getenv('HOME') ?: getenv('USERPROFILE') ?: '/');
  118. // abort when we reach the home dir or top of the filesystem
  119. while (dirname($dir) !== $dir && $dir !== $home) {
  120. if (file_exists($dir.'/'.Factory::getComposerFile())) {
  121. if ($io->askConfirmation('<info>No composer.json in current directory, do you want to use the one at '.$dir.'?</info> [<comment>Y,n</comment>]? ', true)) {
  122. $oldWorkingDir = getcwd();
  123. chdir($dir);
  124. }
  125. break;
  126. }
  127. $dir = dirname($dir);
  128. }
  129. }
  130. if (!$this->disablePluginsByDefault && !$this->hasPluginCommands && 'global' !== $commandName) {
  131. try {
  132. foreach ($this->getPluginCommands() as $command) {
  133. if ($this->has($command->getName())) {
  134. $io->writeError('<warning>Plugin command '.$command->getName().' ('.get_class($command).') would override a Composer command and has been skipped</warning>');
  135. } else {
  136. $this->add($command);
  137. }
  138. }
  139. } catch (NoSslException $e) {
  140. // suppress these as they are not relevant at this point
  141. }
  142. $this->hasPluginCommands = true;
  143. }
  144. // determine command name to be executed incl plugin commands, and check if it's a proxy command
  145. $isProxyCommand = false;
  146. if ($name = $this->getCommandName($input)) {
  147. try {
  148. $command = $this->find($name);
  149. $commandName = $command->getName();
  150. $isProxyCommand = ($command instanceof Command\BaseCommand && $command->isProxyCommand());
  151. } catch (\InvalidArgumentException $e) {
  152. }
  153. }
  154. if (!$isProxyCommand) {
  155. $io->writeError(sprintf(
  156. 'Running %s (%s) with %s on %s',
  157. Composer::VERSION,
  158. Composer::RELEASE_DATE,
  159. defined('HHVM_VERSION') ? 'HHVM '.HHVM_VERSION : 'PHP '.PHP_VERSION,
  160. function_exists('php_uname') ? php_uname('s') . ' / ' . php_uname('r') : 'Unknown OS'
  161. ), true, IOInterface::DEBUG);
  162. if (PHP_VERSION_ID < 50302) {
  163. $io->writeError('<warning>Composer only officially supports PHP 5.3.2 and above, you will most likely encounter problems with your PHP '.PHP_VERSION.', upgrading is strongly recommended.</warning>');
  164. }
  165. if (extension_loaded('xdebug') && !getenv('COMPOSER_DISABLE_XDEBUG_WARN')) {
  166. $io->writeError('<warning>You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug</warning>');
  167. }
  168. if (defined('COMPOSER_DEV_WARNING_TIME') && $commandName !== 'self-update' && $commandName !== 'selfupdate' && time() > COMPOSER_DEV_WARNING_TIME) {
  169. $io->writeError(sprintf('<warning>Warning: This development build of composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']));
  170. }
  171. if (getenv('COMPOSER_NO_INTERACTION')) {
  172. $input->setInteractive(false);
  173. }
  174. if (!Platform::isWindows() && function_exists('exec') && !getenv('COMPOSER_ALLOW_SUPERUSER')) {
  175. if (function_exists('posix_getuid') && posix_getuid() === 0) {
  176. if ($commandName !== 'self-update' && $commandName !== 'selfupdate') {
  177. $io->writeError('<warning>Do not run Composer as root/super user! See https://getcomposer.org/root for details</warning>');
  178. if ($io->isInteractive()) {
  179. if (!$io->askConfirmation('<info>Continue as root/super user</info> [<comment>yes</comment>]? ', true)) {
  180. exit(0);
  181. }
  182. }
  183. }
  184. if ($uid = (int) getenv('SUDO_UID')) {
  185. // Silently clobber any sudo credentials on the invoking user to avoid privilege escalations later on
  186. // ref. https://github.com/composer/composer/issues/5119
  187. Silencer::call('exec', "sudo -u \\#{$uid} sudo -K > /dev/null 2>&1");
  188. }
  189. }
  190. // Silently clobber any remaining sudo leases on the current user as well to avoid privilege escalations
  191. Silencer::call('exec', 'sudo -K > /dev/null 2>&1');
  192. }
  193. // Check system temp folder for usability as it can cause weird runtime issues otherwise
  194. Silencer::call(function () use ($io) {
  195. $tempfile = sys_get_temp_dir() . '/temp-' . md5(microtime());
  196. if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) == __FILE__) && unlink($tempfile) && !file_exists($tempfile))) {
  197. $io->writeError(sprintf('<error>PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini</error>', sys_get_temp_dir()));
  198. }
  199. });
  200. // add non-standard scripts as own commands
  201. $file = Factory::getComposerFile();
  202. if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
  203. if (isset($composer['scripts']) && is_array($composer['scripts'])) {
  204. foreach ($composer['scripts'] as $script => $dummy) {
  205. if (!defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) {
  206. if ($this->has($script)) {
  207. $io->writeError('<warning>A script named '.$script.' would override a Composer command and has been skipped</warning>');
  208. } else {
  209. $description = null;
  210. if (isset($composer['scripts-descriptions'][$script])) {
  211. $description = $composer['scripts-descriptions'][$script];
  212. }
  213. $this->add(new Command\ScriptAliasCommand($script, $description));
  214. }
  215. }
  216. }
  217. }
  218. }
  219. }
  220. try {
  221. if ($input->hasParameterOption('--profile')) {
  222. $startTime = microtime(true);
  223. $this->io->enableDebugging($startTime);
  224. }
  225. $result = parent::doRun($input, $output);
  226. if (isset($oldWorkingDir)) {
  227. chdir($oldWorkingDir);
  228. }
  229. if (isset($startTime)) {
  230. $io->writeError('<info>Memory usage: '.round(memory_get_usage() / 1024 / 1024, 2).'MB (peak: '.round(memory_get_peak_usage() / 1024 / 1024, 2).'MB), time: '.round(microtime(true) - $startTime, 2).'s');
  231. }
  232. restore_error_handler();
  233. return $result;
  234. } catch (ScriptExecutionException $e) {
  235. return $e->getCode();
  236. } catch (\Exception $e) {
  237. $this->hintCommonErrors($e);
  238. restore_error_handler();
  239. throw $e;
  240. }
  241. }
  242. /**
  243. * @param InputInterface $input
  244. * @throws \RuntimeException
  245. * @return string
  246. */
  247. private function getNewWorkingDir(InputInterface $input)
  248. {
  249. $workingDir = $input->getParameterOption(array('--working-dir', '-d'));
  250. if (false !== $workingDir && !is_dir($workingDir)) {
  251. throw new \RuntimeException('Invalid working directory specified, '.$workingDir.' does not exist.');
  252. }
  253. return $workingDir;
  254. }
  255. /**
  256. * {@inheritDoc}
  257. */
  258. private function hintCommonErrors($exception)
  259. {
  260. $io = $this->getIO();
  261. Silencer::suppress();
  262. try {
  263. $composer = $this->getComposer(false, true);
  264. if ($composer) {
  265. $config = $composer->getConfig();
  266. $minSpaceFree = 1024 * 1024;
  267. if ((($df = disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
  268. || (($df = disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
  269. || (($df = disk_free_space($dir = sys_get_temp_dir())) !== false && $df < $minSpaceFree)
  270. ) {
  271. $io->writeError('<error>The disk hosting '.$dir.' is full, this may be the cause of the following exception</error>', true, IOInterface::QUIET);
  272. }
  273. }
  274. } catch (\Exception $e) {
  275. }
  276. Silencer::restore();
  277. if (Platform::isWindows() && false !== strpos($exception->getMessage(), 'The system cannot find the path specified')) {
  278. $io->writeError('<error>The following exception may be caused by a stale entry in your cmd.exe AutoRun</error>', true, IOInterface::QUIET);
  279. $io->writeError('<error>Check https://getcomposer.org/doc/articles/troubleshooting.md#-the-system-cannot-find-the-path-specified-windows- for details</error>', true, IOInterface::QUIET);
  280. }
  281. if (false !== strpos($exception->getMessage(), 'fork failed - Cannot allocate memory')) {
  282. $io->writeError('<error>The following exception is caused by a lack of memory or swap, or not having swap configured</error>', true, IOInterface::QUIET);
  283. $io->writeError('<error>Check https://getcomposer.org/doc/articles/troubleshooting.md#proc-open-fork-failed-errors for details</error>', true, IOInterface::QUIET);
  284. }
  285. }
  286. /**
  287. * @param bool $required
  288. * @param bool|null $disablePlugins
  289. * @throws JsonValidationException
  290. * @return \Composer\Composer
  291. */
  292. public function getComposer($required = true, $disablePlugins = null)
  293. {
  294. if (null === $disablePlugins) {
  295. $disablePlugins = $this->disablePluginsByDefault;
  296. }
  297. if (null === $this->composer) {
  298. try {
  299. $this->composer = Factory::create($this->io, null, $disablePlugins);
  300. } catch (\InvalidArgumentException $e) {
  301. if ($required) {
  302. $this->io->writeError($e->getMessage());
  303. exit(1);
  304. }
  305. } catch (JsonValidationException $e) {
  306. $errors = ' - ' . implode(PHP_EOL . ' - ', $e->getErrors());
  307. $message = $e->getMessage() . ':' . PHP_EOL . $errors;
  308. throw new JsonValidationException($message);
  309. }
  310. }
  311. return $this->composer;
  312. }
  313. /**
  314. * Removes the cached composer instance
  315. */
  316. public function resetComposer()
  317. {
  318. $this->composer = null;
  319. }
  320. /**
  321. * @return IOInterface
  322. */
  323. public function getIO()
  324. {
  325. return $this->io;
  326. }
  327. public function getHelp()
  328. {
  329. return self::$logo . parent::getHelp();
  330. }
  331. /**
  332. * Initializes all the composer commands.
  333. */
  334. protected function getDefaultCommands()
  335. {
  336. $commands = array_merge(parent::getDefaultCommands(), array(
  337. new Command\AboutCommand(),
  338. new Command\ConfigCommand(),
  339. new Command\DependsCommand(),
  340. new Command\ProhibitsCommand(),
  341. new Command\InitCommand(),
  342. new Command\InstallCommand(),
  343. new Command\CreateProjectCommand(),
  344. new Command\UpdateCommand(),
  345. new Command\SearchCommand(),
  346. new Command\ValidateCommand(),
  347. new Command\ShowCommand(),
  348. new Command\SuggestsCommand(),
  349. new Command\RequireCommand(),
  350. new Command\DumpAutoloadCommand(),
  351. new Command\StatusCommand(),
  352. new Command\ArchiveCommand(),
  353. new Command\DiagnoseCommand(),
  354. new Command\RunScriptCommand(),
  355. new Command\LicensesCommand(),
  356. new Command\GlobalCommand(),
  357. new Command\ClearCacheCommand(),
  358. new Command\RemoveCommand(),
  359. new Command\HomeCommand(),
  360. new Command\ExecCommand(),
  361. new Command\OutdatedCommand(),
  362. new Command\CheckPlatformReqsCommand(),
  363. ));
  364. if ('phar:' === substr(__FILE__, 0, 5)) {
  365. $commands[] = new Command\SelfUpdateCommand();
  366. }
  367. return $commands;
  368. }
  369. /**
  370. * {@inheritDoc}
  371. */
  372. public function getLongVersion()
  373. {
  374. if (Composer::BRANCH_ALIAS_VERSION) {
  375. return sprintf(
  376. '<info>%s</info> version <comment>%s (%s)</comment> %s',
  377. $this->getName(),
  378. Composer::BRANCH_ALIAS_VERSION,
  379. $this->getVersion(),
  380. Composer::RELEASE_DATE
  381. );
  382. }
  383. return parent::getLongVersion() . ' ' . Composer::RELEASE_DATE;
  384. }
  385. /**
  386. * {@inheritDoc}
  387. */
  388. protected function getDefaultInputDefinition()
  389. {
  390. $definition = parent::getDefaultInputDefinition();
  391. $definition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Display timing and memory usage information'));
  392. $definition->addOption(new InputOption('--no-plugins', null, InputOption::VALUE_NONE, 'Whether to disable plugins.'));
  393. $definition->addOption(new InputOption('--working-dir', '-d', InputOption::VALUE_REQUIRED, 'If specified, use the given directory as working directory.'));
  394. return $definition;
  395. }
  396. private function getPluginCommands()
  397. {
  398. $commands = array();
  399. $composer = $this->getComposer(false, false);
  400. if (null === $composer) {
  401. $composer = Factory::createGlobal($this->io, false);
  402. }
  403. if (null !== $composer) {
  404. $pm = $composer->getPluginManager();
  405. foreach ($pm->getPluginCapabilities('Composer\Plugin\Capability\CommandProvider', array('composer' => $composer, 'io' => $this->io)) as $capability) {
  406. $newCommands = $capability->getCommands();
  407. if (!is_array($newCommands)) {
  408. throw new \UnexpectedValueException('Plugin capability '.get_class($capability).' failed to return an array from getCommands');
  409. }
  410. foreach ($newCommands as $command) {
  411. if (!$command instanceof Command\BaseCommand) {
  412. throw new \UnexpectedValueException('Plugin capability '.get_class($capability).' returned an invalid value, we expected an array of Composer\Command\BaseCommand objects');
  413. }
  414. }
  415. $commands = array_merge($commands, $newCommands);
  416. }
  417. }
  418. return $commands;
  419. }
  420. }