ShowCommand.php 34 KB

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