You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

show.py 6.1KB

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