ShowCommand.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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\Composer;
  13. use Composer\DependencyResolver\DefaultPolicy;
  14. use Composer\DependencyResolver\Pool;
  15. use Composer\Json\JsonFile;
  16. use Composer\Package\BasePackage;
  17. use Composer\Package\CompletePackageInterface;
  18. use Composer\Package\PackageInterface;
  19. use Composer\Package\Version\VersionParser;
  20. use Composer\Package\Version\VersionSelector;
  21. use Composer\Plugin\CommandEvent;
  22. use Composer\Plugin\PluginEvents;
  23. use Composer\Repository\ArrayRepository;
  24. use Composer\Repository\ComposerRepository;
  25. use Composer\Repository\CompositeRepository;
  26. use Composer\Repository\PlatformRepository;
  27. use Composer\Repository\RepositoryFactory;
  28. use Composer\Repository\RepositoryInterface;
  29. use Composer\Semver\Constraint\ConstraintInterface;
  30. use Composer\Semver\Semver;
  31. use Composer\Spdx\SpdxLicenses;
  32. use Composer\Util\Platform;
  33. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  34. use Symfony\Component\Console\Input\InputArgument;
  35. use Symfony\Component\Console\Input\InputInterface;
  36. use Symfony\Component\Console\Input\InputOption;
  37. use Symfony\Component\Console\Output\OutputInterface;
  38. use Symfony\Component\Console\Terminal;
  39. /**
  40. * @author Robert Schönthal <seroscho@googlemail.com>
  41. * @author Jordi Boggiano <j.boggiano@seld.be>
  42. * @author Jérémy Romey <jeremyFreeAgent>
  43. * @author Mihai Plasoianu <mihai@plasoianu.de>
  44. */
  45. class ShowCommand extends BaseCommand
  46. {
  47. /** @var VersionParser */
  48. protected $versionParser;
  49. protected $colors;
  50. /** @var Pool */
  51. private $pool;
  52. protected function configure()
  53. {
  54. $this
  55. ->setName('show')
  56. ->setAliases(array('info'))
  57. ->setDescription('Shows information about packages.')
  58. ->setDefinition(array(
  59. new InputArgument('package', InputArgument::OPTIONAL, 'Package to inspect. Or a name including a wildcard (*) to filter lists of packages instead.'),
  60. new InputArgument('version', InputArgument::OPTIONAL, 'Version or version constraint to inspect'),
  61. new InputOption('all', null, InputOption::VALUE_NONE, 'List all packages'),
  62. new InputOption('installed', 'i', InputOption::VALUE_NONE, 'List installed packages only (enabled by default, only present for BC).'),
  63. new InputOption('platform', 'p', InputOption::VALUE_NONE, 'List platform packages only'),
  64. new InputOption('available', 'a', InputOption::VALUE_NONE, 'List available packages only'),
  65. new InputOption('self', 's', InputOption::VALUE_NONE, 'Show the root package information'),
  66. new InputOption('name-only', 'N', InputOption::VALUE_NONE, 'List package names only'),
  67. new InputOption('path', 'P', InputOption::VALUE_NONE, 'Show package paths'),
  68. new InputOption('tree', 't', InputOption::VALUE_NONE, 'List the dependencies as a tree'),
  69. new InputOption('latest', 'l', InputOption::VALUE_NONE, 'Show the latest version'),
  70. new InputOption('outdated', 'o', InputOption::VALUE_NONE, 'Show the latest version but only for packages that are outdated'),
  71. new InputOption('minor-only', 'm', InputOption::VALUE_NONE, 'Show only packages that have minor SemVer-compatible updates. Use with the --outdated option.'),
  72. new InputOption('direct', 'D', InputOption::VALUE_NONE, 'Shows only packages that are directly required by the root package'),
  73. new InputOption('strict', null, InputOption::VALUE_NONE, 'Return a non-zero exit code when there are outdated packages'),
  74. new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text'),
  75. ))
  76. ->setHelp(<<<EOT
  77. The show command displays detailed information about a package, or
  78. lists all packages available.
  79. EOT
  80. )
  81. ;
  82. }
  83. protected function execute(InputInterface $input, OutputInterface $output)
  84. {
  85. $this->versionParser = new VersionParser;
  86. if ($input->getOption('tree')) {
  87. $this->initStyles($output);
  88. }
  89. $composer = $this->getComposer(false);
  90. $io = $this->getIO();
  91. if ($input->getOption('installed')) {
  92. $io->writeError('<warning>You are using the deprecated option "installed". Only installed packages are shown by default now. The --all option can be used to show all packages.</warning>');
  93. }
  94. if ($input->getOption('outdated')) {
  95. $input->setOption('latest', true);
  96. }
  97. if ($input->getOption('direct') && ($input->getOption('all') || $input->getOption('available') || $input->getOption('platform'))) {
  98. $io->writeError('The --direct (-D) option is not usable in combination with --all, --platform (-p) or --available (-a)');
  99. return 1;
  100. }
  101. if ($input->getOption('tree') && ($input->getOption('all') || $input->getOption('available'))) {
  102. $io->writeError('The --tree (-t) option is not usable in combination with --all or --available (-a)');
  103. return 1;
  104. }
  105. $format = $input->getOption('format');
  106. if (!in_array($format, array('text', 'json'))) {
  107. $io->writeError(sprintf('Unsupported format "%s". See help for supported formats.', $format));
  108. return 1;
  109. }
  110. // init repos
  111. $platformOverrides = array();
  112. if ($composer) {
  113. $platformOverrides = $composer->getConfig()->get('platform') ?: array();
  114. }
  115. $platformRepo = new PlatformRepository(array(), $platformOverrides);
  116. $phpVersion = $platformRepo->findPackage('php', '*')->getVersion();
  117. if ($input->getOption('self')) {
  118. $package = $this->getComposer()->getPackage();
  119. $repos = $installedRepo = new ArrayRepository(array($package));
  120. } elseif ($input->getOption('platform')) {
  121. $repos = $installedRepo = $platformRepo;
  122. } elseif ($input->getOption('available')) {
  123. $installedRepo = $platformRepo;
  124. if ($composer) {
  125. $repos = new CompositeRepository($composer->getRepositoryManager()->getRepositories());
  126. } else {
  127. $defaultRepos = RepositoryFactory::defaultRepos($io);
  128. $repos = new CompositeRepository($defaultRepos);
  129. $io->writeError('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos)));
  130. }
  131. } elseif ($input->getOption('all') && $composer) {
  132. $localRepo = $composer->getRepositoryManager()->getLocalRepository();
  133. $installedRepo = new CompositeRepository(array($localRepo, $platformRepo));
  134. $repos = new CompositeRepository(array_merge(array($installedRepo), $composer->getRepositoryManager()->getRepositories()));
  135. } elseif ($input->getOption('all')) {
  136. $defaultRepos = RepositoryFactory::defaultRepos($io);
  137. $io->writeError('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos)));
  138. $installedRepo = $platformRepo;
  139. $repos = new CompositeRepository(array_merge(array($installedRepo), $defaultRepos));
  140. } else {
  141. $repos = $installedRepo = $this->getComposer()->getRepositoryManager()->getLocalRepository();
  142. $rootPkg = $this->getComposer()->getPackage();
  143. if (!$installedRepo->getPackages() && ($rootPkg->getRequires() || $rootPkg->getDevRequires())) {
  144. $io->writeError('<warning>No dependencies installed. Try running composer install or update.</warning>');
  145. }
  146. }
  147. if ($composer) {
  148. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'show', $input, $output);
  149. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  150. }
  151. if ($input->getOption('latest') && null === $composer) {
  152. $io->writeError('No composer.json found in the current directory, disabling "latest" option');
  153. $input->setOption('latest', false);
  154. }
  155. $packageFilter = $input->getArgument('package');
  156. // show single package or single version
  157. if (($packageFilter && false === strpos($packageFilter, '*')) || !empty($package)) {
  158. if ('json' === $format) {
  159. $io->writeError('Format "json" is only supported for package listings, falling back to format "text"');
  160. }
  161. if (empty($package)) {
  162. list($package, $versions) = $this->getPackage($installedRepo, $repos, $input->getArgument('package'), $input->getArgument('version'));
  163. if (empty($package)) {
  164. $options = $input->getOptions();
  165. if (!isset($options['working-dir']) || !file_exists('composer.json')) {
  166. throw new \InvalidArgumentException('Package ' . $packageFilter . ' not found');
  167. }
  168. $io->writeError('Package ' . $packageFilter . ' not found in ' . $options['working-dir'] . '/composer.json');
  169. return 1;
  170. }
  171. } else {
  172. $versions = array($package->getPrettyVersion() => $package->getVersion());
  173. }
  174. $exitCode = 0;
  175. if ($input->getOption('tree')) {
  176. $this->displayPackageTree($package, $installedRepo, $repos);
  177. } else {
  178. $latestPackage = null;
  179. if ($input->getOption('latest')) {
  180. $latestPackage = $this->findLatestPackage($package, $composer, $phpVersion);
  181. }
  182. if ($input->getOption('outdated') && $input->getOption('strict') && $latestPackage && $latestPackage->getFullPrettyVersion() !== $package->getFullPrettyVersion() && !$latestPackage->isAbandoned()) {
  183. $exitCode = 1;
  184. }
  185. $this->printMeta($package, $versions, $installedRepo, $latestPackage ?: null);
  186. $this->printLinks($package, 'requires');
  187. $this->printLinks($package, 'devRequires', 'requires (dev)');
  188. if ($package->getSuggests()) {
  189. $io->write("\n<info>suggests</info>");
  190. foreach ($package->getSuggests() as $suggested => $reason) {
  191. $io->write($suggested . ' <comment>' . $reason . '</comment>');
  192. }
  193. }
  194. $this->printLinks($package, 'provides');
  195. $this->printLinks($package, 'conflicts');
  196. $this->printLinks($package, 'replaces');
  197. }
  198. return $exitCode;
  199. }
  200. // show tree view if requested
  201. if ($input->getOption('tree')) {
  202. if ('json' === $format) {
  203. $io->writeError('Format "json" is only supported for package listings, falling back to format "text"');
  204. }
  205. $rootRequires = $this->getRootRequires();
  206. $packages = $installedRepo->getPackages();
  207. usort($packages, 'strcmp');
  208. foreach ($packages as $package) {
  209. if (in_array($package->getName(), $rootRequires, true)) {
  210. $this->displayPackageTree($package, $installedRepo, $repos);
  211. }
  212. }
  213. return 0;
  214. }
  215. if ($repos instanceof CompositeRepository) {
  216. $repos = $repos->getRepositories();
  217. } elseif (!is_array($repos)) {
  218. $repos = array($repos);
  219. }
  220. // list packages
  221. $packages = array();
  222. if (null !== $packageFilter) {
  223. $packageFilter = '{^'.str_replace('\\*', '.*?', preg_quote($packageFilter)).'$}i';
  224. }
  225. $packageListFilter = array();
  226. if ($input->getOption('direct')) {
  227. $packageListFilter = $this->getRootRequires();
  228. }
  229. if (class_exists('Symfony\Component\Console\Terminal')) {
  230. $terminal = new Terminal();
  231. $width = $terminal->getWidth();
  232. } else {
  233. // For versions of Symfony console before 3.2
  234. list($width) = $this->getApplication()->getTerminalDimensions();
  235. }
  236. if (null === $width) {
  237. // In case the width is not detected, we're probably running the command
  238. // outside of a real terminal, use space without a limit
  239. $width = PHP_INT_MAX;
  240. }
  241. if (Platform::isWindows()) {
  242. $width--;
  243. } else {
  244. $width = max(80, $width);
  245. }
  246. if ($input->getOption('path') && null === $composer) {
  247. $io->writeError('No composer.json found in the current directory, disabling "path" option');
  248. $input->setOption('path', false);
  249. }
  250. foreach ($repos as $repo) {
  251. if ($repo === $platformRepo) {
  252. $type = 'platform';
  253. } elseif (
  254. $repo === $installedRepo
  255. || ($installedRepo instanceof CompositeRepository && in_array($repo, $installedRepo->getRepositories(), true))
  256. ) {
  257. $type = 'installed';
  258. } else {
  259. $type = 'available';
  260. }
  261. if ($repo instanceof ComposerRepository && $repo->hasProviders()) {
  262. foreach ($repo->getProviderNames() as $name) {
  263. if (!$packageFilter || preg_match($packageFilter, $name)) {
  264. $packages[$type][$name] = $name;
  265. }
  266. }
  267. } else {
  268. foreach ($repo->getPackages() as $package) {
  269. if (!isset($packages[$type][$package->getName()])
  270. || !is_object($packages[$type][$package->getName()])
  271. || version_compare($packages[$type][$package->getName()]->getVersion(), $package->getVersion(), '<')
  272. ) {
  273. if (!$packageFilter || preg_match($packageFilter, $package->getName())) {
  274. if (!$packageListFilter || in_array($package->getName(), $packageListFilter, true)) {
  275. $packages[$type][$package->getName()] = $package;
  276. }
  277. }
  278. }
  279. }
  280. }
  281. }
  282. $showAllTypes = $input->getOption('all');
  283. $showLatest = $input->getOption('latest');
  284. $showMinorOnly = $input->getOption('minor-only');
  285. $indent = $showAllTypes ? ' ' : '';
  286. $latestPackages = array();
  287. $exitCode = 0;
  288. $viewData = array();
  289. $viewMetaData = array();
  290. foreach (array('platform' => true, 'available' => false, 'installed' => true) as $type => $showVersion) {
  291. if (isset($packages[$type])) {
  292. ksort($packages[$type]);
  293. $nameLength = $versionLength = $latestLength = 0;
  294. foreach ($packages[$type] as $package) {
  295. if (is_object($package)) {
  296. $nameLength = max($nameLength, strlen($package->getPrettyName()));
  297. if ($showVersion) {
  298. $versionLength = max($versionLength, strlen($package->getFullPrettyVersion()));
  299. if ($showLatest) {
  300. $latestPackage = $this->findLatestPackage($package, $composer, $phpVersion, $showMinorOnly);
  301. if ($latestPackage === false) {
  302. continue;
  303. }
  304. $latestPackages[$package->getPrettyName()] = $latestPackage;
  305. $latestLength = max($latestLength, strlen($latestPackage->getFullPrettyVersion()));
  306. }
  307. }
  308. } else {
  309. $nameLength = max($nameLength, strlen($package));
  310. }
  311. }
  312. $writePath = !$input->getOption('name-only') && $input->getOption('path');
  313. $writeVersion = !$input->getOption('name-only') && !$input->getOption('path') && $showVersion;
  314. $writeLatest = $writeVersion && $showLatest;
  315. $writeDescription = !$input->getOption('name-only') && !$input->getOption('path');
  316. $hasOutdatedPackages = false;
  317. $viewData[$type] = array();
  318. $viewMetaData[$type] = array(
  319. 'nameLength' => $nameLength,
  320. 'versionLength' => $versionLength,
  321. 'latestLength' => $latestLength,
  322. );
  323. foreach ($packages[$type] as $package) {
  324. $packageViewData = array();
  325. if (is_object($package)) {
  326. $latestPackage = null;
  327. if ($showLatest && isset($latestPackages[$package->getPrettyName()])) {
  328. $latestPackage = $latestPackages[$package->getPrettyName()];
  329. }
  330. if ($input->getOption('outdated') && $latestPackage && $latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion() && !$latestPackage->isAbandoned()) {
  331. continue;
  332. } elseif ($input->getOption('outdated') || $input->getOption('strict')) {
  333. $hasOutdatedPackages = true;
  334. }
  335. $packageViewData['name'] = $package->getPrettyName();
  336. if ($writeVersion) {
  337. $packageViewData['version'] = $package->getFullPrettyVersion();
  338. }
  339. if ($writeLatest && $latestPackage) {
  340. $packageViewData['latest'] = $latestPackage->getFullPrettyVersion();
  341. $packageViewData['latest-status'] = $this->getUpdateStatus($latestPackage, $package);
  342. }
  343. if ($writeDescription) {
  344. $packageViewData['description'] = $package->getDescription();
  345. }
  346. if ($writePath) {
  347. $packageViewData['path'] = strtok(realpath($composer->getInstallationManager()->getInstallPath($package)), "\r\n");
  348. }
  349. if ($latestPackage && $latestPackage->isAbandoned()) {
  350. $replacement = (is_string($latestPackage->getReplacementPackage()))
  351. ? 'Use ' . $latestPackage->getReplacementPackage() . ' instead'
  352. : 'No replacement was suggested';
  353. $packageWarning = sprintf(
  354. 'Package %s is abandoned, you should avoid using it. %s.',
  355. $package->getPrettyName(),
  356. $replacement
  357. );
  358. $packageViewData['warning'] = $packageWarning;
  359. }
  360. } else {
  361. $packageViewData['name'] = $package;
  362. }
  363. $viewData[$type][] = $packageViewData;
  364. }
  365. if ($input->getOption('strict') && $hasOutdatedPackages) {
  366. $exitCode = 1;
  367. break;
  368. }
  369. }
  370. }
  371. if ('json' === $format) {
  372. $io->write(JsonFile::encode($viewData));
  373. } else {
  374. foreach ($viewData as $type => $packages) {
  375. $nameLength = $viewMetaData[$type]['nameLength'];
  376. $versionLength = $viewMetaData[$type]['versionLength'];
  377. $latestLength = $viewMetaData[$type]['latestLength'];
  378. $writeVersion = $nameLength + $versionLength + 3 <= $width;
  379. $writeLatest = $nameLength + $versionLength + $latestLength + 3 <= $width;
  380. $writeDescription = $nameLength + $versionLength + $latestLength + 24 <= $width;
  381. if ($writeLatest && !$io->isDecorated()) {
  382. $latestLength += 2;
  383. }
  384. if ($showAllTypes) {
  385. if ('available' === $type) {
  386. $io->write('<comment>' . $type . '</comment>:');
  387. } else {
  388. $io->write('<info>' . $type . '</info>:');
  389. }
  390. }
  391. foreach ($packages as $package) {
  392. $io->write($indent . str_pad($package['name'], $nameLength, ' '), false);
  393. if (isset($package['version']) && $writeVersion) {
  394. $io->write(' ' . str_pad($package['version'], $versionLength, ' '), false);
  395. }
  396. if (isset($package['latest']) && $writeLatest) {
  397. $latestVersion = $package['latest'];
  398. $updateStatus = $package['latest-status'];
  399. $style = $this->updateStatusToVersionStyle($updateStatus);
  400. if (!$io->isDecorated()) {
  401. $latestVersion = str_replace(array('up-to-date', 'semver-safe-update', 'update-possible'), array('=', '!', '~'), $updateStatus) . ' ' . $latestVersion;
  402. }
  403. $io->write(' <' . $style . '>' . str_pad($latestVersion, $latestLength, ' ') . '</' . $style . '>', false);
  404. }
  405. if (isset($package['description']) && $writeDescription) {
  406. $description = strtok($package['description'], "\r\n");
  407. $remaining = $width - $nameLength - $versionLength - 4;
  408. if ($writeLatest) {
  409. $remaining -= $latestLength;
  410. }
  411. if (strlen($description) > $remaining) {
  412. $description = substr($description, 0, $remaining - 3) . '...';
  413. }
  414. $io->write(' ' . $description, false);
  415. }
  416. if (isset($package['path'])) {
  417. $io->write(' ' . $package['path'], false);
  418. }
  419. $io->write('');
  420. if (isset($package['warning'])) {
  421. $io->write('<warning>' . $package['warning'] . '</warning>');
  422. }
  423. }
  424. if ($showAllTypes) {
  425. $io->write('');
  426. }
  427. }
  428. }
  429. return $exitCode;
  430. }
  431. protected function getRootRequires()
  432. {
  433. $rootPackage = $this->getComposer()->getPackage();
  434. return array_map(
  435. 'strtolower',
  436. array_keys(array_merge($rootPackage->getRequires(), $rootPackage->getDevRequires()))
  437. );
  438. }
  439. protected function getVersionStyle(PackageInterface $latestPackage, PackageInterface $package)
  440. {
  441. return $this->updateStatusToVersionStyle($this->getUpdateStatus($latestPackage, $package));
  442. }
  443. /**
  444. * finds a package by name and version if provided
  445. *
  446. * @param RepositoryInterface $installedRepo
  447. * @param RepositoryInterface $repos
  448. * @param string $name
  449. * @param ConstraintInterface|string $version
  450. * @throws \InvalidArgumentException
  451. * @return array array(CompletePackageInterface, array of versions)
  452. */
  453. protected function getPackage(RepositoryInterface $installedRepo, RepositoryInterface $repos, $name, $version = null)
  454. {
  455. $name = strtolower($name);
  456. $constraint = is_string($version) ? $this->versionParser->parseConstraints($version) : $version;
  457. $policy = new DefaultPolicy();
  458. $pool = new Pool('dev');
  459. $pool->addRepository($repos);
  460. $matchedPackage = null;
  461. $versions = array();
  462. $matches = $pool->whatProvides($name, $constraint);
  463. foreach ($matches as $index => $package) {
  464. // skip providers/replacers
  465. if ($package->getName() !== $name) {
  466. unset($matches[$index]);
  467. continue;
  468. }
  469. // select an exact match if it is in the installed repo and no specific version was required
  470. if (null === $version && $installedRepo->hasPackage($package)) {
  471. $matchedPackage = $package;
  472. }
  473. $versions[$package->getPrettyVersion()] = $package->getVersion();
  474. $matches[$index] = $package->getId();
  475. }
  476. // select preferred package according to policy rules
  477. if (!$matchedPackage && $matches && $preferred = $policy->selectPreferredPackages($pool, array(), $matches)) {
  478. $matchedPackage = $pool->literalToPackage($preferred[0]);
  479. }
  480. return array($matchedPackage, $versions);
  481. }
  482. /**
  483. * Prints package metadata.
  484. *
  485. * @param CompletePackageInterface $package
  486. * @param array $versions
  487. * @param RepositoryInterface $installedRepo
  488. */
  489. protected function printMeta(CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo, PackageInterface $latestPackage = null)
  490. {
  491. $io = $this->getIO();
  492. $io->write('<info>name</info> : ' . $package->getPrettyName());
  493. $io->write('<info>descrip.</info> : ' . $package->getDescription());
  494. $io->write('<info>keywords</info> : ' . implode(', ', $package->getKeywords() ?: array()));
  495. $this->printVersions($package, $versions, $installedRepo);
  496. if ($latestPackage) {
  497. $style = $this->getVersionStyle($latestPackage, $package);
  498. $io->write('<info>latest</info> : <'.$style.'>' . $latestPackage->getPrettyVersion() . '</'.$style.'>');
  499. } else {
  500. $latestPackage = $package;
  501. }
  502. $io->write('<info>type</info> : ' . $package->getType());
  503. $this->printLicenses($package);
  504. $io->write('<info>source</info> : ' . sprintf('[%s] <comment>%s</comment> %s', $package->getSourceType(), $package->getSourceUrl(), $package->getSourceReference()));
  505. $io->write('<info>dist</info> : ' . sprintf('[%s] <comment>%s</comment> %s', $package->getDistType(), $package->getDistUrl(), $package->getDistReference()));
  506. $io->write('<info>names</info> : ' . implode(', ', $package->getNames()));
  507. if ($latestPackage->isAbandoned()) {
  508. $replacement = ($latestPackage->getReplacementPackage() !== null)
  509. ? ' The author suggests using the ' . $latestPackage->getReplacementPackage(). ' package instead.'
  510. : null;
  511. $io->writeError(
  512. sprintf('<warning>Attention: This package is abandoned and no longer maintained.%s</warning>', $replacement)
  513. );
  514. }
  515. if ($package->getSupport()) {
  516. $io->write("\n<info>support</info>");
  517. foreach ($package->getSupport() as $type => $value) {
  518. $io->write('<comment>' . $type . '</comment> : '.$value);
  519. }
  520. }
  521. if ($package->getAutoload()) {
  522. $io->write("\n<info>autoload</info>");
  523. foreach ($package->getAutoload() as $type => $autoloads) {
  524. $io->write('<comment>' . $type . '</comment>');
  525. if ($type === 'psr-0') {
  526. foreach ($autoloads as $name => $path) {
  527. $io->write(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.')));
  528. }
  529. } elseif ($type === 'psr-4') {
  530. foreach ($autoloads as $name => $path) {
  531. $io->write(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.')));
  532. }
  533. } elseif ($type === 'classmap') {
  534. $io->write(implode(', ', $autoloads));
  535. }
  536. }
  537. if ($package->getIncludePaths()) {
  538. $io->write('<comment>include-path</comment>');
  539. $io->write(implode(', ', $package->getIncludePaths()));
  540. }
  541. }
  542. }
  543. /**
  544. * Prints all available versions of this package and highlights the installed one if any.
  545. *
  546. * @param CompletePackageInterface $package
  547. * @param array $versions
  548. * @param RepositoryInterface $installedRepo
  549. */
  550. protected function printVersions(CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo)
  551. {
  552. uasort($versions, 'version_compare');
  553. $versions = array_keys(array_reverse($versions));
  554. // highlight installed version
  555. if ($installedRepo->hasPackage($package)) {
  556. $installedVersion = $package->getPrettyVersion();
  557. $key = array_search($installedVersion, $versions);
  558. if (false !== $key) {
  559. $versions[$key] = '<info>* ' . $installedVersion . '</info>';
  560. }
  561. }
  562. $versions = implode(', ', $versions);
  563. $this->getIO()->write('<info>versions</info> : ' . $versions);
  564. }
  565. /**
  566. * print link objects
  567. *
  568. * @param CompletePackageInterface $package
  569. * @param string $linkType
  570. * @param string $title
  571. */
  572. protected function printLinks(CompletePackageInterface $package, $linkType, $title = null)
  573. {
  574. $title = $title ?: $linkType;
  575. $io = $this->getIO();
  576. if ($links = $package->{'get'.ucfirst($linkType)}()) {
  577. $io->write("\n<info>" . $title . "</info>");
  578. foreach ($links as $link) {
  579. $io->write($link->getTarget() . ' <comment>' . $link->getPrettyConstraint() . '</comment>');
  580. }
  581. }
  582. }
  583. /**
  584. * Prints the licenses of a package with metadata
  585. *
  586. * @param CompletePackageInterface $package
  587. */
  588. protected function printLicenses(CompletePackageInterface $package)
  589. {
  590. $spdxLicenses = new SpdxLicenses();
  591. $licenses = $package->getLicense();
  592. $io = $this->getIO();
  593. foreach ($licenses as $licenseId) {
  594. $license = $spdxLicenses->getLicenseByIdentifier($licenseId); // keys: 0 fullname, 1 osi, 2 url
  595. if (!$license) {
  596. $out = $licenseId;
  597. } else {
  598. // is license OSI approved?
  599. if ($license[1] === true) {
  600. $out = sprintf('%s (%s) (OSI approved) %s', $license[0], $licenseId, $license[2]);
  601. } else {
  602. $out = sprintf('%s (%s) %s', $license[0], $licenseId, $license[2]);
  603. }
  604. }
  605. $io->write('<info>license</info> : ' . $out);
  606. }
  607. }
  608. /**
  609. * Init styles for tree
  610. *
  611. * @param OutputInterface $output
  612. */
  613. protected function initStyles(OutputInterface $output)
  614. {
  615. $this->colors = array(
  616. 'green',
  617. 'yellow',
  618. 'cyan',
  619. 'magenta',
  620. 'blue',
  621. );
  622. foreach ($this->colors as $color) {
  623. $style = new OutputFormatterStyle($color);
  624. $output->getFormatter()->setStyle($color, $style);
  625. }
  626. }
  627. /**
  628. * Display the tree
  629. *
  630. * @param PackageInterface|string $package
  631. * @param RepositoryInterface $installedRepo
  632. * @param RepositoryInterface $distantRepos
  633. */
  634. protected function displayPackageTree(PackageInterface $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos)
  635. {
  636. $io = $this->getIO();
  637. $io->write(sprintf('<info>%s</info>', $package->getPrettyName()), false);
  638. $io->write(' ' . $package->getPrettyVersion(), false);
  639. $io->write(' ' . strtok($package->getDescription(), "\r\n"));
  640. if (is_object($package)) {
  641. $requires = $package->getRequires();
  642. ksort($requires);
  643. $treeBar = '├';
  644. $j = 0;
  645. $total = count($requires);
  646. foreach ($requires as $requireName => $require) {
  647. $j++;
  648. if ($j == 0) {
  649. $this->writeTreeLine($treeBar);
  650. }
  651. if ($j == $total) {
  652. $treeBar = '└';
  653. }
  654. $level = 1;
  655. $color = $this->colors[$level];
  656. $info = sprintf('%s──<%s>%s</%s> %s', $treeBar, $color, $requireName, $color, $require->getPrettyConstraint());
  657. $this->writeTreeLine($info);
  658. $treeBar = str_replace('└', ' ', $treeBar);
  659. $packagesInTree = array($package->getName(), $requireName);
  660. $this->displayTree($requireName, $require, $installedRepo, $distantRepos, $packagesInTree, $treeBar, $level + 1);
  661. }
  662. }
  663. }
  664. /**
  665. * Display a package tree
  666. *
  667. * @param string $name
  668. * @param PackageInterface|string $package
  669. * @param RepositoryInterface $installedRepo
  670. * @param RepositoryInterface $distantRepos
  671. * @param array $packagesInTree
  672. * @param string $previousTreeBar
  673. * @param int $level
  674. */
  675. protected function displayTree($name, $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos, array $packagesInTree, $previousTreeBar = '├', $level = 1)
  676. {
  677. $previousTreeBar = str_replace('├', '│', $previousTreeBar);
  678. list($package, $versions) = $this->getPackage($installedRepo, $distantRepos, $name, $package->getPrettyConstraint() === 'self.version' ? $package->getConstraint() : $package->getPrettyConstraint());
  679. if (is_object($package)) {
  680. $requires = $package->getRequires();
  681. ksort($requires);
  682. $treeBar = $previousTreeBar . ' ├';
  683. $i = 0;
  684. $total = count($requires);
  685. foreach ($requires as $requireName => $require) {
  686. $currentTree = $packagesInTree;
  687. $i++;
  688. if ($i == $total) {
  689. $treeBar = $previousTreeBar . ' └';
  690. }
  691. $colorIdent = $level % count($this->colors);
  692. $color = $this->colors[$colorIdent];
  693. $circularWarn = in_array($requireName, $currentTree) ? '(circular dependency aborted here)' : '';
  694. $info = rtrim(sprintf('%s──<%s>%s</%s> %s %s', $treeBar, $color, $requireName, $color, $require->getPrettyConstraint(), $circularWarn));
  695. $this->writeTreeLine($info);
  696. $treeBar = str_replace('└', ' ', $treeBar);
  697. if (!in_array($requireName, $currentTree)) {
  698. $currentTree[] = $requireName;
  699. $this->displayTree($requireName, $require, $installedRepo, $distantRepos, $currentTree, $treeBar, $level + 1);
  700. }
  701. }
  702. }
  703. }
  704. private function updateStatusToVersionStyle($updateStatus)
  705. {
  706. // 'up-to-date' is printed green
  707. // 'semver-safe-update' is printed red
  708. // 'update-possible' is printed yellow
  709. return str_replace(array('up-to-date', 'semver-safe-update', 'update-possible'), array('info', 'highlight', 'comment'), $updateStatus);
  710. }
  711. private function getUpdateStatus(PackageInterface $latestPackage, PackageInterface $package)
  712. {
  713. if ($latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion()) {
  714. return 'up-to-date';
  715. }
  716. $constraint = $package->getVersion();
  717. if (0 !== strpos($constraint, 'dev-')) {
  718. $constraint = '^'.$constraint;
  719. }
  720. if ($latestPackage->getVersion() && Semver::satisfies($latestPackage->getVersion(), $constraint)) {
  721. // it needs an immediate semver-compliant upgrade
  722. return 'semver-safe-update';
  723. }
  724. // it needs an upgrade but has potential BC breaks so is not urgent
  725. return 'update-possible';
  726. }
  727. private function writeTreeLine($line)
  728. {
  729. $io = $this->getIO();
  730. if (!$io->isDecorated()) {
  731. $line = str_replace(array('└', '├', '──', '│'), array('`-', '|-', '-', '|'), $line);
  732. }
  733. $io->write($line);
  734. }
  735. /**
  736. * Given a package, this finds the latest package matching it
  737. *
  738. * @param PackageInterface $package
  739. * @param Composer $composer
  740. * @param string $phpVersion
  741. * @param bool $minorOnly
  742. *
  743. * @return PackageInterface|null
  744. */
  745. private function findLatestPackage(PackageInterface $package, Composer $composer, $phpVersion, $minorOnly = false)
  746. {
  747. // find the latest version allowed in this pool
  748. $name = $package->getName();
  749. $versionSelector = new VersionSelector($this->getPool($composer));
  750. $stability = $composer->getPackage()->getMinimumStability();
  751. $flags = $composer->getPackage()->getStabilityFlags();
  752. if (isset($flags[$name])) {
  753. $stability = array_search($flags[$name], BasePackage::$stabilities, true);
  754. }
  755. $bestStability = $stability;
  756. if ($composer->getPackage()->getPreferStable()) {
  757. $bestStability = $package->getStability();
  758. }
  759. $targetVersion = null;
  760. if (0 === strpos($package->getVersion(), 'dev-')) {
  761. $targetVersion = $package->getVersion();
  762. }
  763. if ($targetVersion === null && $minorOnly) {
  764. $targetVersion = '^' . $package->getVersion();
  765. }
  766. return $versionSelector->findBestCandidate($name, $targetVersion, $phpVersion, $bestStability);
  767. }
  768. private function getPool(Composer $composer)
  769. {
  770. if (!$this->pool) {
  771. $this->pool = new Pool($composer->getPackage()->getMinimumStability(), $composer->getPackage()->getStabilityFlags());
  772. $this->pool->addRepository(new CompositeRepository($composer->getRepositoryManager()->getRepositories()));
  773. }
  774. return $this->pool;
  775. }
  776. }