Application.php 20 KB

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