show.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # The following comment should be removed at some point in the future.
  2. # mypy: disallow-untyped-defs=False
  3. from __future__ import absolute_import
  4. import logging
  5. import os
  6. from email.parser import FeedParser
  7. from pip._vendor import pkg_resources
  8. from pip._vendor.packaging.utils import canonicalize_name
  9. from pip._internal.cli.base_command import Command
  10. from pip._internal.cli.status_codes import ERROR, SUCCESS
  11. from pip._internal.utils.misc import write_output
  12. logger = logging.getLogger(__name__)
  13. class ShowCommand(Command):
  14. """
  15. Show information about one or more installed packages.
  16. The output is in RFC-compliant mail header format.
  17. """
  18. usage = """
  19. %prog [options] <package> ..."""
  20. ignore_require_venv = True
  21. def __init__(self, *args, **kw):
  22. super(ShowCommand, self).__init__(*args, **kw)
  23. self.cmd_opts.add_option(
  24. '-f', '--files',
  25. dest='files',
  26. action='store_true',
  27. default=False,
  28. help='Show the full list of installed files for each package.')
  29. self.parser.insert_option_group(0, self.cmd_opts)
  30. def run(self, options, args):
  31. if not args:
  32. logger.warning('ERROR: Please provide a package name or names.')
  33. return ERROR
  34. query = args
  35. results = search_packages_info(query)
  36. if not print_results(
  37. results, list_files=options.files, verbose=options.verbose):
  38. return ERROR
  39. return SUCCESS
  40. def search_packages_info(query):
  41. """
  42. Gather details from installed distributions. Print distribution name,
  43. version, location, and installed files. Installed files requires a
  44. pip generated 'installed-files.txt' in the distributions '.egg-info'
  45. directory.
  46. """
  47. installed = {}
  48. for p in pkg_resources.working_set:
  49. installed[canonicalize_name(p.project_name)] = p
  50. query_names = [canonicalize_name(name) for name in query]
  51. missing = sorted(
  52. [name for name, pkg in zip(query, query_names) if pkg not in installed]
  53. )
  54. if missing:
  55. logger.warning('Package(s) not found: %s', ', '.join(missing))
  56. def get_requiring_packages(package_name):
  57. canonical_name = canonicalize_name(package_name)
  58. return [
  59. pkg.project_name for pkg in pkg_resources.working_set
  60. if canonical_name in
  61. [canonicalize_name(required.name) for required in
  62. pkg.requires()]
  63. ]
  64. for dist in [installed[pkg] for pkg in query_names if pkg in installed]:
  65. package = {
  66. 'name': dist.project_name,
  67. 'version': dist.version,
  68. 'location': dist.location,
  69. 'requires': [dep.project_name for dep in dist.requires()],
  70. 'required_by': get_requiring_packages(dist.project_name)
  71. }
  72. file_list = None
  73. metadata = None
  74. if isinstance(dist, pkg_resources.DistInfoDistribution):
  75. # RECORDs should be part of .dist-info metadatas
  76. if dist.has_metadata('RECORD'):
  77. lines = dist.get_metadata_lines('RECORD')
  78. paths = [l.split(',')[0] for l in lines]
  79. paths = [os.path.join(dist.location, p) for p in paths]
  80. file_list = [os.path.relpath(p, dist.location) for p in paths]
  81. if dist.has_metadata('METADATA'):
  82. metadata = dist.get_metadata('METADATA')
  83. else:
  84. # Otherwise use pip's log for .egg-info's
  85. if dist.has_metadata('installed-files.txt'):
  86. paths = dist.get_metadata_lines('installed-files.txt')
  87. paths = [os.path.join(dist.egg_info, p) for p in paths]
  88. file_list = [os.path.relpath(p, dist.location) for p in paths]
  89. if dist.has_metadata('PKG-INFO'):
  90. metadata = dist.get_metadata('PKG-INFO')
  91. if dist.has_metadata('entry_points.txt'):
  92. entry_points = dist.get_metadata_lines('entry_points.txt')
  93. package['entry_points'] = entry_points
  94. if dist.has_metadata('INSTALLER'):
  95. for line in dist.get_metadata_lines('INSTALLER'):
  96. if line.strip():
  97. package['installer'] = line.strip()
  98. break
  99. # @todo: Should pkg_resources.Distribution have a
  100. # `get_pkg_info` method?
  101. feed_parser = FeedParser()
  102. feed_parser.feed(metadata)
  103. pkg_info_dict = feed_parser.close()
  104. for key in ('metadata-version', 'summary',
  105. 'home-page', 'author', 'author-email', 'license'):
  106. package[key] = pkg_info_dict.get(key)
  107. # It looks like FeedParser cannot deal with repeated headers
  108. classifiers = []
  109. for line in metadata.splitlines():
  110. if line.startswith('Classifier: '):
  111. classifiers.append(line[len('Classifier: '):])
  112. package['classifiers'] = classifiers
  113. if file_list:
  114. package['files'] = sorted(file_list)
  115. yield package
  116. def print_results(distributions, list_files=False, verbose=False):
  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.get('name', ''))
  126. write_output("Version: %s", dist.get('version', ''))
  127. write_output("Summary: %s", dist.get('summary', ''))
  128. write_output("Home-page: %s", dist.get('home-page', ''))
  129. write_output("Author: %s", dist.get('author', ''))
  130. write_output("Author-email: %s", dist.get('author-email', ''))
  131. write_output("License: %s", dist.get('license', ''))
  132. write_output("Location: %s", dist.get('location', ''))
  133. write_output("Requires: %s", ', '.join(dist.get('requires', [])))
  134. write_output("Required-by: %s", ', '.join(dist.get('required_by', [])))
  135. if verbose:
  136. write_output("Metadata-Version: %s",
  137. dist.get('metadata-version', ''))
  138. write_output("Installer: %s", dist.get('installer', ''))
  139. write_output("Classifiers:")
  140. for classifier in dist.get('classifiers', []):
  141. write_output(" %s", classifier)
  142. write_output("Entry-points:")
  143. for entry in dist.get('entry_points', []):
  144. write_output(" %s", entry.strip())
  145. if list_files:
  146. write_output("Files:")
  147. for line in dist.get('files', []):
  148. write_output(" %s", line.strip())
  149. if "files" not in dist:
  150. write_output("Cannot locate installed-files.txt")
  151. return results_printed