BaseDependencyCommand.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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\Package\Link;
  14. use Composer\Package\PackageInterface;
  15. use Composer\Repository\ArrayRepository;
  16. use Composer\Repository\CompositeRepository;
  17. use Composer\Repository\PlatformRepository;
  18. use Composer\Plugin\CommandEvent;
  19. use Composer\Plugin\PluginEvents;
  20. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  21. use Composer\Package\Version\VersionParser;
  22. use Symfony\Component\Console\Helper\Table;
  23. use Symfony\Component\Console\Input\InputArgument;
  24. use Symfony\Component\Console\Input\InputInterface;
  25. use Symfony\Component\Console\Input\InputOption;
  26. use Symfony\Component\Console\Output\OutputInterface;
  27. /**
  28. * Base implementation for commands mapping dependency relationships.
  29. *
  30. * @author Niels Keurentjes <niels.keurentjes@omines.com>
  31. */
  32. class BaseDependencyCommand extends BaseCommand
  33. {
  34. const ARGUMENT_PACKAGE = 'package';
  35. const ARGUMENT_CONSTRAINT = 'constraint';
  36. const OPTION_RECURSIVE = 'recursive';
  37. const OPTION_TREE = 'tree';
  38. protected $colors;
  39. /**
  40. * Set common options and arguments.
  41. */
  42. protected function configure()
  43. {
  44. $this->setDefinition(array(
  45. new InputArgument(self::ARGUMENT_PACKAGE, InputArgument::REQUIRED, 'Package to inspect'),
  46. new InputArgument(self::ARGUMENT_CONSTRAINT, InputArgument::OPTIONAL, 'Optional version constraint', '*'),
  47. new InputOption(self::OPTION_RECURSIVE, 'r', InputOption::VALUE_NONE, 'Recursively resolves up to the root package'),
  48. new InputOption(self::OPTION_TREE, 't', InputOption::VALUE_NONE, 'Prints the results as a nested tree'),
  49. ));
  50. }
  51. /**
  52. * Execute the command.
  53. *
  54. * @param InputInterface $input
  55. * @param OutputInterface $output
  56. * @param bool $inverted Whether to invert matching process (why-not vs why behaviour)
  57. * @return int|null Exit code of the operation.
  58. */
  59. protected function doExecute(InputInterface $input, OutputInterface $output, $inverted = false)
  60. {
  61. // Emit command event on startup
  62. $composer = $this->getComposer();
  63. $commandEvent = new CommandEvent(PluginEvents::COMMAND, $this->getName(), $input, $output);
  64. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  65. // Prepare repositories and set up a pool
  66. $platformOverrides = $composer->getConfig()->get('platform') ?: array();
  67. $repository = new CompositeRepository(array(
  68. new ArrayRepository(array($composer->getPackage())),
  69. $composer->getRepositoryManager()->getLocalRepository(),
  70. new PlatformRepository(array(), $platformOverrides),
  71. ));
  72. $pool = new Pool();
  73. $pool->addRepository($repository);
  74. // Parse package name and constraint
  75. list($needle, $textConstraint) = array_pad(
  76. explode(':', $input->getArgument(self::ARGUMENT_PACKAGE)),
  77. 2,
  78. $input->getArgument(self::ARGUMENT_CONSTRAINT)
  79. );
  80. // Find packages that are or provide the requested package first
  81. $packages = $pool->whatProvides($needle);
  82. if (empty($packages)) {
  83. throw new \InvalidArgumentException(sprintf('Could not find package "%s" in your project', $needle));
  84. }
  85. // Include replaced packages for inverted lookups as they are then the actual starting point to consider
  86. $needles = array($needle);
  87. if ($inverted) {
  88. foreach ($packages as $package) {
  89. $needles = array_merge($needles, array_map(function (Link $link) {
  90. return $link->getTarget();
  91. }, $package->getReplaces()));
  92. }
  93. }
  94. // Parse constraint if one was supplied
  95. if ('*' !== $textConstraint) {
  96. $versionParser = new VersionParser();
  97. $constraint = $versionParser->parseConstraints($textConstraint);
  98. } else {
  99. $constraint = null;
  100. }
  101. // Parse rendering options
  102. $renderTree = $input->getOption(self::OPTION_TREE);
  103. $recursive = $renderTree || $input->getOption(self::OPTION_RECURSIVE);
  104. // Resolve dependencies
  105. $results = $repository->getDependents($needles, $constraint, $inverted, $recursive);
  106. if (empty($results)) {
  107. $extra = (null !== $constraint) ? sprintf(' in versions %smatching %s', $inverted ? 'not ' : '', $textConstraint) : '';
  108. $this->getIO()->writeError(sprintf('<info>There is no installed package depending on "%s"%s</info>',
  109. $needle, $extra));
  110. } elseif ($renderTree) {
  111. $this->initStyles($output);
  112. $root = $packages[0];
  113. $this->getIO()->write(sprintf('<info>%s</info> %s %s', $root->getPrettyName(), $root->getPrettyVersion(), $root->getDescription()));
  114. $this->printTree($results);
  115. } else {
  116. $this->printTable($output, $results);
  117. }
  118. return 0;
  119. }
  120. /**
  121. * Assembles and prints a bottom-up table of the dependencies.
  122. *
  123. * @param OutputInterface $output
  124. * @param array $results
  125. */
  126. protected function printTable(OutputInterface $output, $results)
  127. {
  128. $table = array();
  129. $doubles = array();
  130. do {
  131. $queue = array();
  132. $rows = array();
  133. foreach ($results as $result) {
  134. /**
  135. * @var PackageInterface $package
  136. * @var Link $link
  137. */
  138. list($package, $link, $children) = $result;
  139. $unique = (string) $link;
  140. if (isset($doubles[$unique])) {
  141. continue;
  142. }
  143. $doubles[$unique] = true;
  144. $version = (strpos($package->getPrettyVersion(), 'No version set') === 0) ? '-' : $package->getPrettyVersion();
  145. $rows[] = array($package->getPrettyName(), $version, $link->getDescription(), sprintf('%s (%s)', $link->getTarget(), $link->getPrettyConstraint()));
  146. $queue = array_merge($queue, $children);
  147. }
  148. $results = $queue;
  149. $table = array_merge($rows, $table);
  150. } while (!empty($results));
  151. // Render table
  152. $renderer = new Table($output);
  153. $renderer->setStyle('compact');
  154. $renderer->getStyle()->setVerticalBorderChar('');
  155. $renderer->getStyle()->setCellRowContentFormat('%s ');
  156. $renderer->setRows($table)->render();
  157. }
  158. /**
  159. * Init styles for tree
  160. *
  161. * @param OutputInterface $output
  162. */
  163. protected function initStyles(OutputInterface $output)
  164. {
  165. $this->colors = array(
  166. 'green',
  167. 'yellow',
  168. 'cyan',
  169. 'magenta',
  170. 'blue',
  171. );
  172. foreach ($this->colors as $color) {
  173. $style = new OutputFormatterStyle($color);
  174. $output->getFormatter()->setStyle($color, $style);
  175. }
  176. }
  177. /**
  178. * Recursively prints a tree of the selected results.
  179. *
  180. * @param array $results
  181. * @param string $prefix
  182. */
  183. protected function printTree($results, $prefix = '', $level = 1)
  184. {
  185. $count = count($results);
  186. $idx = 0;
  187. foreach ($results as $key => $result) {
  188. /**
  189. * @var PackageInterface $package
  190. * @var Link $link
  191. */
  192. list($package, $link, $children) = $result;
  193. $color = $this->colors[$level % count($this->colors)];
  194. $prevColor = $this->colors[($level - 1) % count($this->colors)];
  195. $isLast = (++$idx == $count);
  196. $versionText = (strpos($package->getPrettyVersion(), 'No version set') === 0) ? '' : $package->getPrettyVersion();
  197. $packageText = rtrim(sprintf('<%s>%s</%1$s> %s', $color, $package->getPrettyName(), $versionText));
  198. $linkText = sprintf('%s <%s>%s</%2$s> %s', $link->getDescription(), $prevColor, $link->getTarget(), $link->getPrettyConstraint());
  199. $circularWarn = $children === false ? '(circular dependency aborted here)' : '';
  200. $this->writeTreeLine(rtrim(sprintf("%s%s%s (%s) %s", $prefix, $isLast ? '└──' : '├──', $packageText, $linkText, $circularWarn)));
  201. if ($children) {
  202. $this->printTree($children, $prefix . ($isLast ? ' ' : '│ '), $level + 1);
  203. }
  204. }
  205. }
  206. private function writeTreeLine($line)
  207. {
  208. $io = $this->getIO();
  209. if (!$io->isDecorated()) {
  210. $line = str_replace(array('└', '├', '──', '│'), array('`-', '|-', '-', '|'), $line);
  211. }
  212. $io->write($line);
  213. }
  214. }