Application.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. /**
  28. * The console application that handles the commands
  29. *
  30. * @author Ryan Weaver <ryan@knplabs.com>
  31. * @author Jordi Boggiano <j.boggiano@seld.be>
  32. * @author François Pluchino <francois.pluchino@opendisplay.com>
  33. */
  34. class Application extends BaseApplication
  35. {
  36. /**
  37. * @var Composer
  38. */
  39. protected $composer;
  40. /**
  41. * @var IOInterface
  42. */
  43. protected $io;
  44. private static $logo = ' ______
  45. / ____/___ ____ ___ ____ ____ ________ _____
  46. / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
  47. / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
  48. \____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
  49. /_/
  50. ';
  51. public function __construct()
  52. {
  53. static $shutdownRegistered = false;
  54. if (function_exists('ini_set') && extension_loaded('xdebug')) {
  55. ini_set('xdebug.show_exception_trace', false);
  56. ini_set('xdebug.scream', false);
  57. }
  58. if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
  59. date_default_timezone_set(Silencer::call('date_default_timezone_get'));
  60. }
  61. if (!$shutdownRegistered) {
  62. $shutdownRegistered = true;
  63. register_shutdown_function(function () {
  64. $lastError = error_get_last();
  65. if ($lastError && $lastError['message'] &&
  66. (strpos($lastError['message'], 'Allowed memory') !== false /*Zend PHP out of memory error*/ ||
  67. strpos($lastError['message'], 'exceeded memory') !== false /*HHVM out of memory errors*/)) {
  68. echo "\n". 'Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.';
  69. }
  70. });
  71. }
  72. parent::__construct('Composer', Composer::VERSION);
  73. }
  74. /**
  75. * {@inheritDoc}
  76. */
  77. public function run(InputInterface $input = null, OutputInterface $output = null)
  78. {
  79. if (null === $output) {
  80. $styles = Factory::createAdditionalStyles();
  81. $formatter = new OutputFormatter(null, $styles);
  82. $output = new ConsoleOutput(ConsoleOutput::VERBOSITY_NORMAL, null, $formatter);
  83. }
  84. return parent::run($input, $output);
  85. }
  86. /**
  87. * {@inheritDoc}
  88. */
  89. public function doRun(InputInterface $input, OutputInterface $output)
  90. {
  91. $io = $this->io = new ConsoleIO($input, $output, $this->getHelperSet());
  92. ErrorHandler::register($io);
  93. // determine command name to be executed
  94. $commandName = '';
  95. if ($name = $this->getCommandName($input)) {
  96. try {
  97. $commandName = $this->find($name)->getName();
  98. } catch (\InvalidArgumentException $e) {
  99. }
  100. }
  101. if ($commandName !== 'global') {
  102. if (PHP_VERSION_ID < 50302) {
  103. $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>');
  104. }
  105. if (extension_loaded('xdebug') && !getenv('COMPOSER_DISABLE_XDEBUG_WARN')) {
  106. $io->writeError('<warning>You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug</warning>');
  107. }
  108. if (defined('COMPOSER_DEV_WARNING_TIME') && $commandName !== 'self-update' && $commandName !== 'selfupdate' && time() > COMPOSER_DEV_WARNING_TIME) {
  109. $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']));
  110. }
  111. if (getenv('COMPOSER_NO_INTERACTION')) {
  112. $input->setInteractive(false);
  113. }
  114. // switch working dir
  115. if ($newWorkDir = $this->getNewWorkingDir($input)) {
  116. $oldWorkingDir = getcwd();
  117. chdir($newWorkDir);
  118. $io->writeError('Changed CWD to ' . getcwd(), true, IOInterface::DEBUG);
  119. }
  120. // add non-standard scripts as own commands
  121. $file = Factory::getComposerFile();
  122. if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
  123. if (isset($composer['scripts']) && is_array($composer['scripts'])) {
  124. foreach ($composer['scripts'] as $script => $dummy) {
  125. if (!defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) {
  126. if ($this->has($script)) {
  127. $io->writeError('<warning>A script named '.$script.' would override a native Composer function and has been skipped</warning>');
  128. } else {
  129. $this->add(new Command\ScriptAliasCommand($script));
  130. }
  131. }
  132. }
  133. }
  134. }
  135. }
  136. try {
  137. if ($input->hasParameterOption('--profile')) {
  138. $startTime = microtime(true);
  139. $this->io->enableDebugging($startTime);
  140. }
  141. $result = parent::doRun($input, $output);
  142. if (isset($oldWorkingDir)) {
  143. chdir($oldWorkingDir);
  144. }
  145. if (isset($startTime)) {
  146. $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');
  147. }
  148. return $result;
  149. } catch (\Exception $e) {
  150. $this->hintCommonErrors($e);
  151. throw $e;
  152. }
  153. }
  154. /**
  155. * @param InputInterface $input
  156. * @throws \RuntimeException
  157. * @return string
  158. */
  159. private function getNewWorkingDir(InputInterface $input)
  160. {
  161. $workingDir = $input->getParameterOption(array('--working-dir', '-d'));
  162. if (false !== $workingDir && !is_dir($workingDir)) {
  163. throw new \RuntimeException('Invalid working directory specified, '.$workingDir.' does not exist.');
  164. }
  165. return $workingDir;
  166. }
  167. /**
  168. * {@inheritDoc}
  169. */
  170. private function hintCommonErrors($exception)
  171. {
  172. $io = $this->getIO();
  173. Silencer::suppress();
  174. try {
  175. $composer = $this->getComposer(false, true);
  176. if ($composer) {
  177. $config = $composer->getConfig();
  178. $minSpaceFree = 1024 * 1024;
  179. if ((($df = disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
  180. || (($df = disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
  181. || (($df = disk_free_space($dir = sys_get_temp_dir())) !== false && $df < $minSpaceFree)
  182. ) {
  183. $io->writeError('<error>The disk hosting '.$dir.' is full, this may be the cause of the following exception</error>', true, IOInterface::QUIET);
  184. }
  185. }
  186. } catch (\Exception $e) {
  187. }
  188. Silencer::restore();
  189. if (Platform::isWindows() && false !== strpos($exception->getMessage(), 'The system cannot find the path specified')) {
  190. $io->writeError('<error>The following exception may be caused by a stale entry in your cmd.exe AutoRun</error>', true, IOInterface::QUIET);
  191. $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);
  192. }
  193. if (false !== strpos($exception->getMessage(), 'fork failed - Cannot allocate memory')) {
  194. $io->writeError('<error>The following exception is caused by a lack of memory and not having swap configured</error>', true, IOInterface::QUIET);
  195. $io->writeError('<error>Check https://getcomposer.org/doc/articles/troubleshooting.md#proc-open-fork-failed-errors for details</error>', true, IOInterface::QUIET);
  196. }
  197. }
  198. /**
  199. * @param bool $required
  200. * @param bool $disablePlugins
  201. * @throws JsonValidationException
  202. * @return \Composer\Composer
  203. */
  204. public function getComposer($required = true, $disablePlugins = false)
  205. {
  206. if (null === $this->composer) {
  207. try {
  208. $this->composer = Factory::create($this->io, null, $disablePlugins);
  209. } catch (\InvalidArgumentException $e) {
  210. if ($required) {
  211. $this->io->writeError($e->getMessage());
  212. exit(1);
  213. }
  214. } catch (JsonValidationException $e) {
  215. $errors = ' - ' . implode(PHP_EOL . ' - ', $e->getErrors());
  216. $message = $e->getMessage() . ':' . PHP_EOL . $errors;
  217. throw new JsonValidationException($message);
  218. }
  219. }
  220. return $this->composer;
  221. }
  222. /**
  223. * Removes the cached composer instance
  224. */
  225. public function resetComposer()
  226. {
  227. $this->composer = null;
  228. }
  229. /**
  230. * @return IOInterface
  231. */
  232. public function getIO()
  233. {
  234. return $this->io;
  235. }
  236. public function getHelp()
  237. {
  238. return self::$logo . parent::getHelp();
  239. }
  240. /**
  241. * Initializes all the composer commands
  242. */
  243. protected function getDefaultCommands()
  244. {
  245. $commands = parent::getDefaultCommands();
  246. $commands[] = new Command\AboutCommand();
  247. $commands[] = new Command\ConfigCommand();
  248. $commands[] = new Command\DependsCommand();
  249. $commands[] = new Command\InitCommand();
  250. $commands[] = new Command\InstallCommand();
  251. $commands[] = new Command\CreateProjectCommand();
  252. $commands[] = new Command\UpdateCommand();
  253. $commands[] = new Command\SearchCommand();
  254. $commands[] = new Command\ValidateCommand();
  255. $commands[] = new Command\ShowCommand();
  256. $commands[] = new Command\SuggestsCommand();
  257. $commands[] = new Command\RequireCommand();
  258. $commands[] = new Command\DumpAutoloadCommand();
  259. $commands[] = new Command\StatusCommand();
  260. $commands[] = new Command\ArchiveCommand();
  261. $commands[] = new Command\DiagnoseCommand();
  262. $commands[] = new Command\RunScriptCommand();
  263. $commands[] = new Command\LicensesCommand();
  264. $commands[] = new Command\GlobalCommand();
  265. $commands[] = new Command\ClearCacheCommand();
  266. $commands[] = new Command\RemoveCommand();
  267. $commands[] = new Command\HomeCommand();
  268. if ('phar:' === substr(__FILE__, 0, 5)) {
  269. $commands[] = new Command\SelfUpdateCommand();
  270. }
  271. return $commands;
  272. }
  273. /**
  274. * {@inheritDoc}
  275. */
  276. public function getLongVersion()
  277. {
  278. if (Composer::BRANCH_ALIAS_VERSION) {
  279. return sprintf(
  280. '<info>%s</info> version <comment>%s (%s)</comment> %s',
  281. $this->getName(),
  282. Composer::BRANCH_ALIAS_VERSION,
  283. $this->getVersion(),
  284. Composer::RELEASE_DATE
  285. );
  286. }
  287. return parent::getLongVersion() . ' ' . Composer::RELEASE_DATE;
  288. }
  289. /**
  290. * {@inheritDoc}
  291. */
  292. protected function getDefaultInputDefinition()
  293. {
  294. $definition = parent::getDefaultInputDefinition();
  295. $definition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Display timing and memory usage information'));
  296. $definition->addOption(new InputOption('--working-dir', '-d', InputOption::VALUE_REQUIRED, 'If specified, use the given directory as working directory.'));
  297. return $definition;
  298. }
  299. }