Application.php 17 KB

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