show.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import logging
  2. from optparse import Values
  3. from typing import Iterator, List, NamedTuple, Optional
  4. from pip._vendor.packaging.utils import canonicalize_name
  5. from pip._internal.cli.base_command import Command
  6. from pip._internal.cli.status_codes import ERROR, SUCCESS
  7. from pip._internal.metadata import BaseDistribution, get_default_environment
  8. from pip._internal.utils.misc import write_output
  9. logger = logging.getLogger(__name__)
  10. class ShowCommand(Command):
  11. """
  12. Show information about one or more installed packages.
  13. The output is in RFC-compliant mail header format.
  14. """
  15. usage = """
  16. %prog [options] <package> ..."""
  17. ignore_require_venv = True
  18. def add_options(self) -> None:
  19. self.cmd_opts.add_option(
  20. "-f",
  21. "--files",
  22. dest="files",
  23. action="store_true",
  24. default=False,
  25. help="Show the full list of installed files for each package.",
  26. )
  27. self.parser.insert_option_group(0, self.cmd_opts)
  28. def run(self, options: Values, args: List[str]) -> int:
  29. if not args:
  30. logger.warning("ERROR: Please provide a package name or names.")
  31. return ERROR
  32. query = args
  33. results = search_packages_info(query)
  34. if not print_results(
  35. results, list_files=options.files, verbose=options.verbose
  36. ):
  37. return ERROR
  38. return SUCCESS
  39. class _PackageInfo(NamedTuple):
  40. name: str
  41. version: str
  42. location: str
  43. requires: List[str]
  44. required_by: List[str]
  45. installer: str
  46. metadata_version: str
  47. classifiers: List[str]
  48. summary: str
  49. homepage: str
  50. author: str
  51. author_email: str
  52. license: str
  53. entry_points: List[str]
  54. files: Optional[List[str]]
  55. def search_packages_info(query: List[str]) -> Iterator[_PackageInfo]:
  56. """
  57. Gather details from installed distributions. Print distribution name,
  58. version, location, and installed files. Installed files requires a
  59. pip generated 'installed-files.txt' in the distributions '.egg-info'
  60. directory.
  61. """
  62. env = get_default_environment()
  63. installed = {dist.canonical_name: dist for dist in env.iter_distributions()}
  64. query_names = [canonicalize_name(name) for name in query]
  65. missing = sorted(
  66. [name for name, pkg in zip(query, query_names) if pkg not in installed]
  67. )
  68. if missing:
  69. logger.warning("Package(s) not found: %s", ", ".join(missing))
  70. def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]:
  71. return (
  72. dist.metadata["Name"] or "UNKNOWN"
  73. for dist in installed.values()
  74. if current_dist.canonical_name
  75. in {canonicalize_name(d.name) for d in dist.iter_dependencies()}
  76. )
  77. for query_name in query_names:
  78. try:
  79. dist = installed[query_name]
  80. except KeyError:
  81. continue
  82. requires = sorted((req.name for req in dist.iter_dependencies()), key=str.lower)
  83. required_by = sorted(_get_requiring_packages(dist), key=str.lower)
  84. try:
  85. entry_points_text = dist.read_text("entry_points.txt")
  86. entry_points = entry_points_text.splitlines(keepends=False)
  87. except FileNotFoundError:
  88. entry_points = []
  89. files_iter = dist.iter_declared_entries()
  90. if files_iter is None:
  91. files: Optional[List[str]] = None
  92. else:
  93. files = sorted(files_iter)
  94. metadata = dist.metadata
  95. yield _PackageInfo(
  96. name=dist.raw_name,
  97. version=str(dist.version),
  98. location=dist.location or "",
  99. requires=requires,
  100. required_by=required_by,
  101. installer=dist.installer,
  102. metadata_version=dist.metadata_version or "",
  103. classifiers=metadata.get_all("Classifier", []),
  104. summary=metadata.get("Summary", ""),
  105. homepage=metadata.get("Home-page", ""),
  106. author=metadata.get("Author", ""),
  107. author_email=metadata.get("Author-email", ""),
  108. license=metadata.get("License", ""),
  109. entry_points=entry_points,
  110. files=files,
  111. )
  112. def print_results(
  113. distributions: Iterator[_PackageInfo],
  114. list_files: bool,
  115. verbose: bool,
  116. ) -> bool:
  117. """
  118. Print the information from installed distributions found.
  119. """
  120. results_printed = False
  121. for i, dist in enumerate(distributions):
  122. results_printed = True
  123. if i > 0:
  124. write_output("---")
  125. write_output("Name: %s", dist.name)
  126. write_output("Version: %s", dist.version)
  127. write_output("Summary: %s", dist.summary)
  128. write_output("Home-page: %s", dist.homepage)
  129. write_output("Author: %s", dist.author)
  130. write_output("Author-email: %s", dist.author_email)
  131. write_output("License: %s", dist.license)
  132. write_output("Location: %s", dist.location)
  133. write_output("Requires: %s", ", ".join(dist.requires))
  134. write_output("Required-by: %s", ", ".join(dist.required_by))
  135. if verbose:
  136. write_output("Metadata-Version: %s", dist.metadata_version)
  137. write_output("Installer: %s", dist.installer)
  138. write_output("Classifiers:")
  139. for classifier in dist.classifiers:
  140. write_output(" %s", classifier)
  141. write_output("Entry-points:")
  142. for entry in dist.entry_points:
  143. write_output(" %s", entry.strip())
  144. if list_files:
  145. write_output("Files:")
  146. if dist.files is None:
  147. write_output("Cannot locate RECORD or installed-files.txt")
  148. else:
  149. for line in dist.files:
  150. write_output(" %s", line.strip())
  151. return results_printed