ShowCommand.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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 = '<info>platform</info>:';
  207. } elseif (
  208. $repo === $installedRepo
  209. || ($installedRepo instanceof CompositeRepository && in_array($repo, $installedRepo->getRepositories(), true))
  210. ) {
  211. $type = '<info>installed</info>:';
  212. } else {
  213. $type = '<comment>available</comment>:';
  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. foreach (array('<info>platform</info>:' => true, '<comment>available</comment>:' => false, '<info>installed</info>:' => true) as $type => $showVersion) {
  242. if (isset($packages[$type])) {
  243. ksort($packages[$type]);
  244. $nameLength = $versionLength = $latestLength = 0;
  245. foreach ($packages[$type] as $package) {
  246. if (is_object($package)) {
  247. $nameLength = max($nameLength, strlen($package->getPrettyName()));
  248. if ($showVersion) {
  249. $versionLength = max($versionLength, strlen($package->getFullPrettyVersion()));
  250. if ($showLatest) {
  251. $latestPackage = $this->findLatestPackage($package, $composer, $phpVersion, $showMinorOnly);
  252. if ($latestPackage === false) {
  253. continue;
  254. }
  255. $latestPackages[$package->getPrettyName()] = $latestPackage;
  256. $latestLength = max($latestLength, strlen($latestPackage->getFullPrettyVersion()));
  257. }
  258. }
  259. } else {
  260. $nameLength = max($nameLength, strlen($package));
  261. }
  262. }
  263. list($width) = $this->getApplication()->getTerminalDimensions();
  264. if (null === $width) {
  265. // In case the width is not detected, we're probably running the command
  266. // outside of a real terminal, use space without a limit
  267. $width = PHP_INT_MAX;
  268. }
  269. if (Platform::isWindows()) {
  270. $width--;
  271. }
  272. if ($input->getOption('path') && null === $composer) {
  273. $io->writeError('No composer.json found in the current directory, disabling "path" option');
  274. $input->setOption('path', false);
  275. }
  276. $writePath = !$input->getOption('name-only') && $input->getOption('path');
  277. $writeVersion = !$input->getOption('name-only') && !$input->getOption('path') && $showVersion && ($nameLength + $versionLength + 3 <= $width);
  278. $writeLatest = $writeVersion && $showLatest && ($nameLength + $versionLength + $latestLength + 3 <= $width);
  279. $writeDescription = !$input->getOption('name-only') && !$input->getOption('path') && ($nameLength + $versionLength + $latestLength + 24 <= $width);
  280. if ($writeLatest && !$io->isDecorated()) {
  281. $latestLength += 2;
  282. }
  283. $hasOutdatedPackages = false;
  284. if ($showAllTypes) {
  285. $io->write($type);
  286. }
  287. foreach ($packages[$type] as $package) {
  288. if (is_object($package)) {
  289. $latestPackage = null;
  290. if ($showLatest && isset($latestPackages[$package->getPrettyName()])) {
  291. $latestPackage = $latestPackages[$package->getPrettyName()];
  292. }
  293. if ($input->getOption('outdated') && $latestPackage && $latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion() && !$latestPackage->isAbandoned()) {
  294. continue;
  295. } elseif ($input->getOption('outdated')) {
  296. $hasOutdatedPackages = true;
  297. }
  298. $io->write($indent . str_pad($package->getPrettyName(), $nameLength, ' '), false);
  299. if ($writeVersion) {
  300. $io->write(' ' . str_pad($package->getFullPrettyVersion(), $versionLength, ' '), false);
  301. }
  302. if ($writeLatest && $latestPackage) {
  303. $latestVersion = $latestPackage->getFullPrettyVersion();
  304. $style = $this->getVersionStyle($latestPackage, $package);
  305. if (!$io->isDecorated()) {
  306. $latestVersion = str_replace(array('info', 'highlight', 'comment'), array('=', '!', '~'), $style) . ' ' . $latestVersion;
  307. }
  308. $io->write(' <'.$style.'>' . str_pad($latestVersion, $latestLength, ' ') . '</'.$style.'>', false);
  309. }
  310. if ($writeDescription) {
  311. $description = strtok($package->getDescription(), "\r\n");
  312. $remaining = $width - $nameLength - $versionLength - 4;
  313. if ($writeLatest) {
  314. $remaining -= $latestLength;
  315. }
  316. if (strlen($description) > $remaining) {
  317. $description = substr($description, 0, $remaining - 3) . '...';
  318. }
  319. $io->write(' ' . $description, false);
  320. }
  321. if ($writePath) {
  322. $path = strtok(realpath($composer->getInstallationManager()->getInstallPath($package)), "\r\n");
  323. $io->write(' ' . $path, false);
  324. }
  325. if ($latestPackage && $latestPackage->isAbandoned()) {
  326. $replacement = (is_string($latestPackage->getReplacementPackage()))
  327. ? 'Use ' . $latestPackage->getReplacementPackage() . ' instead'
  328. : 'No replacement was suggested';
  329. $io->writeError('');
  330. $io->writeError(
  331. sprintf(
  332. "<warning>Package %s is abandoned, you should avoid using it. %s.</warning>",
  333. $package->getPrettyName(),
  334. $replacement
  335. ),
  336. false
  337. );
  338. }
  339. } else {
  340. $io->write($indent . $package, false);
  341. }
  342. $io->write('');
  343. }
  344. if ($showAllTypes) {
  345. $io->write('');
  346. }
  347. if ($input->getOption('strict') && $hasOutdatedPackages) {
  348. return 1;
  349. }
  350. }
  351. }
  352. }
  353. protected function getRootRequires()
  354. {
  355. $rootPackage = $this->getComposer()->getPackage();
  356. return array_map(
  357. 'strtolower',
  358. array_keys(array_merge($rootPackage->getRequires(), $rootPackage->getDevRequires()))
  359. );
  360. }
  361. protected function getVersionStyle(PackageInterface $latestPackage, PackageInterface $package)
  362. {
  363. if ($latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion()) {
  364. // print green as it's up to date
  365. return 'info';
  366. }
  367. $constraint = $package->getVersion();
  368. if (0 !== strpos($constraint, 'dev-')) {
  369. $constraint = '^'.$constraint;
  370. }
  371. if ($latestPackage->getVersion() && Semver::satisfies($latestPackage->getVersion(), $constraint)) {
  372. // print red as it needs an immediate semver-compliant upgrade
  373. return 'highlight';
  374. }
  375. // print yellow as it needs an upgrade but has potential BC breaks so is not urgent
  376. return 'comment';
  377. }
  378. /**
  379. * finds a package by name and version if provided
  380. *
  381. * @param RepositoryInterface $installedRepo
  382. * @param RepositoryInterface $repos
  383. * @param string $name
  384. * @param ConstraintInterface|string $version
  385. * @throws \InvalidArgumentException
  386. * @return array array(CompletePackageInterface, array of versions)
  387. */
  388. protected function getPackage(RepositoryInterface $installedRepo, RepositoryInterface $repos, $name, $version = null)
  389. {
  390. $name = strtolower($name);
  391. $constraint = is_string($version) ? $this->versionParser->parseConstraints($version) : $version;
  392. $policy = new DefaultPolicy();
  393. $pool = new Pool('dev');
  394. $pool->addRepository($repos);
  395. $matchedPackage = null;
  396. $versions = array();
  397. $matches = $pool->whatProvides($name, $constraint);
  398. foreach ($matches as $index => $package) {
  399. // skip providers/replacers
  400. if ($package->getName() !== $name) {
  401. unset($matches[$index]);
  402. continue;
  403. }
  404. // select an exact match if it is in the installed repo and no specific version was required
  405. if (null === $version && $installedRepo->hasPackage($package)) {
  406. $matchedPackage = $package;
  407. }
  408. $versions[$package->getPrettyVersion()] = $package->getVersion();
  409. $matches[$index] = $package->getId();
  410. }
  411. // select preferred package according to policy rules
  412. if (!$matchedPackage && $matches && $preferred = $policy->selectPreferredPackages($pool, array(), $matches)) {
  413. $matchedPackage = $pool->literalToPackage($preferred[0]);
  414. }
  415. return array($matchedPackage, $versions);
  416. }
  417. /**
  418. * Prints package metadata.
  419. *
  420. * @param CompletePackageInterface $package
  421. * @param array $versions
  422. * @param RepositoryInterface $installedRepo
  423. */
  424. protected function printMeta(CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo, PackageInterface $latestPackage = null)
  425. {
  426. $io = $this->getIO();
  427. $io->write('<info>name</info> : ' . $package->getPrettyName());
  428. $io->write('<info>descrip.</info> : ' . $package->getDescription());
  429. $io->write('<info>keywords</info> : ' . implode(', ', $package->getKeywords() ?: array()));
  430. $this->printVersions($package, $versions, $installedRepo);
  431. if ($latestPackage) {
  432. $style = $this->getVersionStyle($latestPackage, $package);
  433. $io->write('<info>latest</info> : <'.$style.'>' . $latestPackage->getPrettyVersion() . '</'.$style.'>');
  434. } else {
  435. $latestPackage = $package;
  436. }
  437. $io->write('<info>type</info> : ' . $package->getType());
  438. $this->printLicenses($package);
  439. $io->write('<info>source</info> : ' . sprintf('[%s] <comment>%s</comment> %s', $package->getSourceType(), $package->getSourceUrl(), $package->getSourceReference()));
  440. $io->write('<info>dist</info> : ' . sprintf('[%s] <comment>%s</comment> %s', $package->getDistType(), $package->getDistUrl(), $package->getDistReference()));
  441. $io->write('<info>names</info> : ' . implode(', ', $package->getNames()));
  442. if ($latestPackage->isAbandoned()) {
  443. $replacement = ($latestPackage->getReplacementPackage() !== null)
  444. ? ' The author suggests using the ' . $latestPackage->getReplacementPackage(). ' package instead.'
  445. : null;
  446. $io->writeError(
  447. sprintf('<warning>Attention: This package is abandoned and no longer maintained.%s</warning>', $replacement)
  448. );
  449. }
  450. if ($package->getSupport()) {
  451. $io->write("\n<info>support</info>");
  452. foreach ($package->getSupport() as $type => $value) {
  453. $io->write('<comment>' . $type . '</comment> : '.$value);
  454. }
  455. }
  456. if ($package->getAutoload()) {
  457. $io->write("\n<info>autoload</info>");
  458. foreach ($package->getAutoload() as $type => $autoloads) {
  459. $io->write('<comment>' . $type . '</comment>');
  460. if ($type === 'psr-0') {
  461. foreach ($autoloads as $name => $path) {
  462. $io->write(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.')));
  463. }
  464. } elseif ($type === 'psr-4') {
  465. foreach ($autoloads as $name => $path) {
  466. $io->write(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.')));
  467. }
  468. } elseif ($type === 'classmap') {
  469. $io->write(implode(', ', $autoloads));
  470. }
  471. }
  472. if ($package->getIncludePaths()) {
  473. $io->write('<comment>include-path</comment>');
  474. $io->write(implode(', ', $package->getIncludePaths()));
  475. }
  476. }
  477. }
  478. /**
  479. * Prints all available versions of this package and highlights the installed one if any.
  480. *
  481. * @param CompletePackageInterface $package
  482. * @param array $versions
  483. * @param RepositoryInterface $installedRepo
  484. */
  485. protected function printVersions(CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo)
  486. {
  487. uasort($versions, 'version_compare');
  488. $versions = array_keys(array_reverse($versions));
  489. // highlight installed version
  490. if ($installedRepo->hasPackage($package)) {
  491. $installedVersion = $package->getPrettyVersion();
  492. $key = array_search($installedVersion, $versions);
  493. if (false !== $key) {
  494. $versions[$key] = '<info>* ' . $installedVersion . '</info>';
  495. }
  496. }
  497. $versions = implode(', ', $versions);
  498. $this->getIO()->write('<info>versions</info> : ' . $versions);
  499. }
  500. /**
  501. * print link objects
  502. *
  503. * @param CompletePackageInterface $package
  504. * @param string $linkType
  505. * @param string $title
  506. */
  507. protected function printLinks(CompletePackageInterface $package, $linkType, $title = null)
  508. {
  509. $title = $title ?: $linkType;
  510. $io = $this->getIO();
  511. if ($links = $package->{'get'.ucfirst($linkType)}()) {
  512. $io->write("\n<info>" . $title . "</info>");
  513. foreach ($links as $link) {
  514. $io->write($link->getTarget() . ' <comment>' . $link->getPrettyConstraint() . '</comment>');
  515. }
  516. }
  517. }
  518. /**
  519. * Prints the licenses of a package with metadata
  520. *
  521. * @param CompletePackageInterface $package
  522. */
  523. protected function printLicenses(CompletePackageInterface $package)
  524. {
  525. $spdxLicenses = new SpdxLicenses();
  526. $licenses = $package->getLicense();
  527. $io = $this->getIO();
  528. foreach ($licenses as $licenseId) {
  529. $license = $spdxLicenses->getLicenseByIdentifier($licenseId); // keys: 0 fullname, 1 osi, 2 url
  530. if (!$license) {
  531. $out = $licenseId;
  532. } else {
  533. // is license OSI approved?
  534. if ($license[1] === true) {
  535. $out = sprintf('%s (%s) (OSI approved) %s', $license[0], $licenseId, $license[2]);
  536. } else {
  537. $out = sprintf('%s (%s) %s', $license[0], $licenseId, $license[2]);
  538. }
  539. }
  540. $io->write('<info>license</info> : ' . $out);
  541. }
  542. }
  543. /**
  544. * Init styles for tree
  545. *
  546. * @param OutputInterface $output
  547. */
  548. protected function initStyles(OutputInterface $output)
  549. {
  550. $this->colors = array(
  551. 'green',
  552. 'yellow',
  553. 'cyan',
  554. 'magenta',
  555. 'blue',
  556. );
  557. foreach ($this->colors as $color) {
  558. $style = new OutputFormatterStyle($color);
  559. $output->getFormatter()->setStyle($color, $style);
  560. }
  561. }
  562. /**
  563. * Display the tree
  564. *
  565. * @param PackageInterface|string $package
  566. * @param RepositoryInterface $installedRepo
  567. * @param RepositoryInterface $distantRepos
  568. */
  569. protected function displayPackageTree(PackageInterface $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos)
  570. {
  571. $io = $this->getIO();
  572. $io->write(sprintf('<info>%s</info>', $package->getPrettyName()), false);
  573. $io->write(' ' . $package->getPrettyVersion(), false);
  574. $io->write(' ' . strtok($package->getDescription(), "\r\n"));
  575. if (is_object($package)) {
  576. $requires = $package->getRequires();
  577. $treeBar = '├';
  578. $j = 0;
  579. $total = count($requires);
  580. foreach ($requires as $requireName => $require) {
  581. $j++;
  582. if ($j == 0) {
  583. $this->writeTreeLine($treeBar);
  584. }
  585. if ($j == $total) {
  586. $treeBar = '└';
  587. }
  588. $level = 1;
  589. $color = $this->colors[$level];
  590. $info = sprintf('%s──<%s>%s</%s> %s', $treeBar, $color, $requireName, $color, $require->getPrettyConstraint());
  591. $this->writeTreeLine($info);
  592. $treeBar = str_replace('└', ' ', $treeBar);
  593. $packagesInTree = array($package->getName(), $requireName);
  594. $this->displayTree($requireName, $require, $installedRepo, $distantRepos, $packagesInTree, $treeBar, $level + 1);
  595. }
  596. }
  597. }
  598. /**
  599. * Display a package tree
  600. *
  601. * @param string $name
  602. * @param PackageInterface|string $package
  603. * @param RepositoryInterface $installedRepo
  604. * @param RepositoryInterface $distantRepos
  605. * @param array $packagesInTree
  606. * @param string $previousTreeBar
  607. * @param int $level
  608. */
  609. protected function displayTree($name, $package, RepositoryInterface $installedRepo, RepositoryInterface $distantRepos, array $packagesInTree, $previousTreeBar = '├', $level = 1)
  610. {
  611. $previousTreeBar = str_replace('├', '│', $previousTreeBar);
  612. list($package, $versions) = $this->getPackage($installedRepo, $distantRepos, $name, $package->getPrettyConstraint() === 'self.version' ? $package->getConstraint() : $package->getPrettyConstraint());
  613. if (is_object($package)) {
  614. $requires = $package->getRequires();
  615. $treeBar = $previousTreeBar . ' ├';
  616. $i = 0;
  617. $total = count($requires);
  618. foreach ($requires as $requireName => $require) {
  619. $currentTree = $packagesInTree;
  620. $i++;
  621. if ($i == $total) {
  622. $treeBar = $previousTreeBar . ' └';
  623. }
  624. $colorIdent = $level % count($this->colors);
  625. $color = $this->colors[$colorIdent];
  626. $circularWarn = in_array($requireName, $currentTree) ? '(circular dependency aborted here)' : '';
  627. $info = rtrim(sprintf('%s──<%s>%s</%s> %s %s', $treeBar, $color, $requireName, $color, $require->getPrettyConstraint(), $circularWarn));
  628. $this->writeTreeLine($info);
  629. $treeBar = str_replace('└', ' ', $treeBar);
  630. if (!in_array($requireName, $currentTree)) {
  631. $currentTree[] = $requireName;
  632. $this->displayTree($requireName, $require, $installedRepo, $distantRepos, $currentTree, $treeBar, $level + 1);
  633. }
  634. }
  635. }
  636. }
  637. private function writeTreeLine($line)
  638. {
  639. $io = $this->getIO();
  640. if (!$io->isDecorated()) {
  641. $line = str_replace(array('└', '├', '──', '│'), array('`-', '|-', '-', '|'), $line);
  642. }
  643. $io->write($line);
  644. }
  645. /**
  646. * Given a package, this finds the latest package matching it
  647. *
  648. * @param PackageInterface $package
  649. * @param Composer $composer
  650. * @param string $phpVersion
  651. * @param bool $minorOnly
  652. *
  653. * @return PackageInterface|null
  654. */
  655. private function findLatestPackage(PackageInterface $package, Composer $composer, $phpVersion, $minorOnly = false)
  656. {
  657. // find the latest version allowed in this pool
  658. $name = $package->getName();
  659. $versionSelector = new VersionSelector($this->getPool($composer));
  660. $stability = $composer->getPackage()->getMinimumStability();
  661. $flags = $composer->getPackage()->getStabilityFlags();
  662. if (isset($flags[$name])) {
  663. $stability = array_search($flags[$name], BasePackage::$stabilities, true);
  664. }
  665. $bestStability = $stability;
  666. if ($composer->getPackage()->getPreferStable()) {
  667. $bestStability = $package->getStability();
  668. }
  669. $targetVersion = null;
  670. if (0 === strpos($package->getVersion(), 'dev-')) {
  671. $targetVersion = $package->getVersion();
  672. }
  673. if ($targetVersion === null && $minorOnly) {
  674. $targetVersion = '^' . $package->getVersion();
  675. }
  676. return $versionSelector->findBestCandidate($name, $targetVersion, $phpVersion, $bestStability);
  677. }
  678. private function getPool(Composer $composer)
  679. {
  680. if (!$this->pool) {
  681. $this->pool = new Pool($composer->getPackage()->getMinimumStability(), $composer->getPackage()->getStabilityFlags());
  682. $this->pool->addRepository(new CompositeRepository($composer->getRepositoryManager()->getRepositories()));
  683. }
  684. return $this->pool;
  685. }
  686. }