show.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. license_expression: str
  57. entry_points: List[str]
  58. files: Optional[List[str]]
  59. def search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]:
  60. """
  61. Gather details from installed distributions. Print distribution name,
  62. version, location, and installed files. Installed files requires a
  63. pip generated 'installed-files.txt' in the distributions '.egg-info'
  64. directory.
  65. """
  66. env = get_default_environment()
  67. installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()}
  68. query_names = [canonicalize_name(name) for name in query]
  69. missing = sorted(
  70. [name for name, pkg in zip(query, query_names) if pkg not in installed]
  71. )
  72. if missing:
  73. logger.warning("Package(s) not found: %s", ", ".join(missing))
  74. def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]:
  75. return (
  76. dist.metadata["Name"] or "UNKNOWN"
  77. for dist in installed.values()
  78. if current_dist.canonical_name
  79. in {canonicalize_name(d.name) for d in dist.iter_dependencies()}
  80. )
  81. for query_name in query_names:
  82. try:
  83. dist = installed[query_name]
  84. except KeyError:
  85. continue
  86. try:
  87. requires = sorted(
  88. # Avoid duplicates in requirements (e.g. due to environment markers).
  89. {req.name for req in dist.iter_dependencies()},
  90. key=str.lower,
  91. )
  92. except InvalidRequirement:
  93. requires = sorted(dist.iter_raw_dependencies(), key=str.lower)
  94. try:
  95. required_by = sorted(_get_requiring_packages(dist), key=str.lower)
  96. except InvalidRequirement:
  97. required_by = ["#N/A"]
  98. try:
  99. entry_points_text = dist.read_text("entry_points.txt")
  100. entry_points = entry_points_text.splitlines(keepends=False)
  101. except FileNotFoundError:
  102. entry_points = []
  103. files_iter = dist.iter_declared_entries()
  104. if files_iter is None:
  105. files: Optional[List[str]] = None
  106. else:
  107. files = sorted(files_iter)
  108. metadata = dist.metadata
  109. project_urls = metadata.get_all("Project-URL", [])
  110. homepage = metadata.get("Home-page", "")
  111. if not homepage:
  112. # It's common that there is a "homepage" Project-URL, but Home-page
  113. # remains unset (especially as PEP 621 doesn't surface the field).
  114. #
  115. # This logic was taken from PyPI's codebase.
  116. for url in project_urls:
  117. url_label, url = url.split(",", maxsplit=1)
  118. normalized_label = (
  119. url_label.casefold().replace("-", "").replace("_", "").strip()
  120. )
  121. if normalized_label == "homepage":
  122. homepage = url.strip()
  123. break
  124. yield _PackageInfo(
  125. name=dist.raw_name,
  126. version=dist.raw_version,
  127. location=dist.location or "",
  128. editable_project_location=dist.editable_project_location,
  129. requires=requires,
  130. required_by=required_by,
  131. installer=dist.installer,
  132. metadata_version=dist.metadata_version or "",
  133. classifiers=metadata.get_all("Classifier", []),
  134. summary=metadata.get("Summary", ""),
  135. homepage=homepage,
  136. project_urls=project_urls,
  137. author=metadata.get("Author", ""),
  138. author_email=metadata.get("Author-email", ""),
  139. license=metadata.get("License", ""),
  140. license_expression=metadata.get("License-Expression", ""),
  141. entry_points=entry_points,
  142. files=files,
  143. )
  144. def print_results(
  145. distributions: Iterable[_PackageInfo],
  146. list_files: bool,
  147. verbose: bool,
  148. ) -> bool:
  149. """
  150. Print the information from installed distributions found.
  151. """
  152. results_printed = False
  153. for i, dist in enumerate(distributions):
  154. results_printed = True
  155. if i > 0:
  156. write_output("---")
  157. metadata_version_tuple = tuple(map(int, dist.metadata_version.split(".")))
  158. write_output("Name: %s", dist.name)
  159. write_output("Version: %s", dist.version)
  160. write_output("Summary: %s", dist.summary)
  161. write_output("Home-page: %s", dist.homepage)
  162. write_output("Author: %s", dist.author)
  163. write_output("Author-email: %s", dist.author_email)
  164. if metadata_version_tuple >= (2, 4) and dist.license_expression:
  165. write_output("License-Expression: %s", dist.license_expression)
  166. else:
  167. write_output("License: %s", dist.license)
  168. write_output("Location: %s", dist.location)
  169. if dist.editable_project_location is not None:
  170. write_output(
  171. "Editable project location: %s", dist.editable_project_location
  172. )
  173. write_output("Requires: %s", ", ".join(dist.requires))
  174. write_output("Required-by: %s", ", ".join(dist.required_by))
  175. if verbose:
  176. write_output("Metadata-Version: %s", dist.metadata_version)
  177. write_output("Installer: %s", dist.installer)
  178. write_output("Classifiers:")
  179. for classifier in dist.classifiers:
  180. write_output(" %s", classifier)
  181. write_output("Entry-points:")
  182. for entry in dist.entry_points:
  183. write_output(" %s", entry.strip())
  184. write_output("Project-URLs:")
  185. for project_url in dist.project_urls:
  186. write_output(" %s", project_url)
  187. if list_files:
  188. write_output("Files:")
  189. if dist.files is None:
  190. write_output("Cannot locate RECORD or installed-files.txt")
  191. else:
  192. for line in dist.files:
  193. write_output(" %s", line.strip())
  194. return results_printed