show.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import logging
  2. from optparse import Values
  3. from typing import Generator, Iterable, Iterator, List, NamedTuple, Optional
  4. from pip._vendor.packaging.requirements import InvalidRequirement
  5. from pip._vendor.packaging.utils import canonicalize_name
  6. from pip._internal.cli.base_command import Command
  7. from pip._internal.cli.status_codes import ERROR, SUCCESS
  8. from pip._internal.metadata import BaseDistribution, get_default_environment
  9. from pip._internal.utils.misc import write_output
  10. logger = logging.getLogger(__name__)
  11. class ShowCommand(Command):
  12. """
  13. Show information about one or more installed packages.
  14. The output is in RFC-compliant mail header format.
  15. """
  16. usage = """
  17. %prog [options] <package> ..."""
  18. ignore_require_venv = True
  19. def add_options(self) -> None:
  20. self.cmd_opts.add_option(
  21. "-f",
  22. "--files",
  23. dest="files",
  24. action="store_true",
  25. default=False,
  26. help="Show the full list of installed files for each package.",
  27. )
  28. self.parser.insert_option_group(0, self.cmd_opts)
  29. def run(self, options: Values, args: List[str]) -> int:
  30. if not args:
  31. logger.warning("ERROR: Please provide a package name or names.")
  32. return ERROR
  33. query = args
  34. results = search_packages_info(query)
  35. if not print_results(
  36. results, list_files=options.files, verbose=options.verbose
  37. ):
  38. return ERROR
  39. return SUCCESS
  40. class _PackageInfo(NamedTuple):
  41. name: str
  42. version: str
  43. location: str
  44. editable_project_location: Optional[str]
  45. requires: List[str]
  46. required_by: List[str]
  47. installer: str
  48. metadata_version: str
  49. classifiers: List[str]
  50. summary: str
  51. homepage: str
  52. project_urls: List[str]
  53. author: str
  54. author_email: str
  55. license: str
  56. entry_points: List[str]
  57. files: Optional[List[str]]
  58. def search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]:
  59. """
  60. Gather details from installed distributions. Print distribution name,
  61. version, location, and installed files. Installed files requires a
  62. pip generated 'installed-files.txt' in the distributions '.egg-info'
  63. directory.
  64. """
  65. env = get_default_environment()
  66. installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()}
  67. query_names = [canonicalize_name(name) for name in query]
  68. missing = sorted(
  69. [name for name, pkg in zip(query, query_names) if pkg not in installed]
  70. )
  71. if missing:
  72. logger.warning("Package(s) not found: %s", ", ".join(missing))
  73. def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]:
  74. return (
  75. dist.metadata["Name"] or "UNKNOWN"
  76. for dist in installed.values()
  77. if current_dist.canonical_name
  78. in {canonicalize_name(d.name) for d in dist.iter_dependencies()}
  79. )
  80. for query_name in query_names:
  81. try:
  82. dist = installed[query_name]
  83. except KeyError:
  84. continue
  85. try:
  86. requires = sorted(
  87. # Avoid duplicates in requirements (e.g. due to environment markers).
  88. {req.name for req in dist.iter_dependencies()},
  89. key=str.lower,
  90. )
  91. except InvalidRequirement:
  92. requires = sorted(dist.iter_raw_dependencies(), key=str.lower)
  93. try:
  94. required_by = sorted(_get_requiring_packages(dist), key=str.lower)
  95. except InvalidRequirement:
  96. required_by = ["#N/A"]
  97. try:
  98. entry_points_text = dist.read_text("entry_points.txt")
  99. entry_points = entry_points_text.splitlines(keepends=False)
  100. except FileNotFoundError:
  101. entry_points = []
  102. files_iter = dist.iter_declared_entries()
  103. if files_iter is None:
  104. files: Optional[List[str]] = None
  105. else:
  106. files = sorted(files_iter)
  107. metadata = dist.metadata
  108. project_urls = metadata.get_all("Project-URL", [])
  109. homepage = metadata.get("Home-page", "")
  110. if not homepage:
  111. # It's common that there is a "homepage" Project-URL, but Home-page
  112. # remains unset (especially as PEP 621 doesn't surface the field).
  113. #
  114. # This logic was taken from PyPI's codebase.
  115. for url in project_urls:
  116. url_label, url = url.split(",", maxsplit=1)
  117. normalized_label = (
  118. url_label.casefold().replace("-", "").replace("_", "").strip()
  119. )
  120. if normalized_label == "homepage":
  121. homepage = url.strip()
  122. break
  123. yield _PackageInfo(
  124. name=dist.raw_name,
  125. version=dist.raw_version,
  126. location=dist.location or "",
  127. editable_project_location=dist.editable_project_location,
  128. requires=requires,
  129. required_by=required_by,
  130. installer=dist.installer,
  131. metadata_version=dist.metadata_version or "",
  132. classifiers=metadata.get_all("Classifier", []),
  133. summary=metadata.get("Summary", ""),
  134. homepage=homepage,
  135. project_urls=project_urls,
  136. author=metadata.get("Author", ""),
  137. author_email=metadata.get("Author-email", ""),
  138. license=metadata.get("License", ""),
  139. entry_points=entry_points,
  140. files=files,
  141. )
  142. def print_results(
  143. distributions: Iterable[_PackageInfo],
  144. list_files: bool,
  145. verbose: bool,
  146. ) -> bool:
  147. """
  148. Print the information from installed distributions found.
  149. """
  150. results_printed = False
  151. for i, dist in enumerate(distributions):
  152. results_printed = True
  153. if i > 0:
  154. write_output("---")
  155. write_output("Name: %s", dist.name)
  156. write_output("Version: %s", dist.version)
  157. write_output("Summary: %s", dist.summary)
  158. write_output("Home-page: %s", dist.homepage)
  159. write_output("Author: %s", dist.author)
  160. write_output("Author-email: %s", dist.author_email)
  161. write_output("License: %s", dist.license)
  162. write_output("Location: %s", dist.location)
  163. if dist.editable_project_location is not None:
  164. write_output(
  165. "Editable project location: %s", dist.editable_project_location
  166. )
  167. write_output("Requires: %s", ", ".join(dist.requires))
  168. write_output("Required-by: %s", ", ".join(dist.required_by))
  169. if verbose:
  170. write_output("Metadata-Version: %s", dist.metadata_version)
  171. write_output("Installer: %s", dist.installer)
  172. write_output("Classifiers:")
  173. for classifier in dist.classifiers:
  174. write_output(" %s", classifier)
  175. write_output("Entry-points:")
  176. for entry in dist.entry_points:
  177. write_output(" %s", entry.strip())
  178. write_output("Project-URLs:")
  179. for project_url in dist.project_urls:
  180. write_output(" %s", project_url)
  181. if list_files:
  182. write_output("Files:")
  183. if dist.files is None:
  184. write_output("Cannot locate RECORD or installed-files.txt")
  185. else:
  186. for line in dist.files:
  187. write_output(" %s", line.strip())
  188. return results_printed