debug.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import locale
  2. import logging
  3. import os
  4. import sys
  5. from optparse import Values
  6. from types import ModuleType
  7. from typing import Any, Dict, List, Optional
  8. import pip._vendor
  9. from pip._vendor.certifi import where
  10. from pip._vendor.packaging.version import parse as parse_version
  11. from pip import __file__ as pip_location
  12. from pip._internal.cli import cmdoptions
  13. from pip._internal.cli.base_command import Command
  14. from pip._internal.cli.cmdoptions import make_target_python
  15. from pip._internal.cli.status_codes import SUCCESS
  16. from pip._internal.configuration import Configuration
  17. from pip._internal.metadata import get_environment
  18. from pip._internal.utils.logging import indent_log
  19. from pip._internal.utils.misc import get_pip_version
  20. logger = logging.getLogger(__name__)
  21. def show_value(name: str, value: Any) -> None:
  22. logger.info('%s: %s', name, value)
  23. def show_sys_implementation() -> None:
  24. logger.info('sys.implementation:')
  25. implementation_name = sys.implementation.name
  26. with indent_log():
  27. show_value('name', implementation_name)
  28. def create_vendor_txt_map() -> Dict[str, str]:
  29. vendor_txt_path = os.path.join(
  30. os.path.dirname(pip_location),
  31. '_vendor',
  32. 'vendor.txt'
  33. )
  34. with open(vendor_txt_path) as f:
  35. # Purge non version specifying lines.
  36. # Also, remove any space prefix or suffixes (including comments).
  37. lines = [line.strip().split(' ', 1)[0]
  38. for line in f.readlines() if '==' in line]
  39. # Transform into "module" -> version dict.
  40. return dict(line.split('==', 1) for line in lines) # type: ignore
  41. def get_module_from_module_name(module_name: str) -> ModuleType:
  42. # Module name can be uppercase in vendor.txt for some reason...
  43. module_name = module_name.lower()
  44. # PATCH: setuptools is actually only pkg_resources.
  45. if module_name == 'setuptools':
  46. module_name = 'pkg_resources'
  47. __import__(
  48. f'pip._vendor.{module_name}',
  49. globals(),
  50. locals(),
  51. level=0
  52. )
  53. return getattr(pip._vendor, module_name)
  54. def get_vendor_version_from_module(module_name: str) -> Optional[str]:
  55. module = get_module_from_module_name(module_name)
  56. version = getattr(module, '__version__', None)
  57. if not version:
  58. # Try to find version in debundled module info.
  59. env = get_environment([os.path.dirname(module.__file__)])
  60. dist = env.get_distribution(module_name)
  61. if dist:
  62. version = str(dist.version)
  63. return version
  64. def show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None:
  65. """Log the actual version and print extra info if there is
  66. a conflict or if the actual version could not be imported.
  67. """
  68. for module_name, expected_version in vendor_txt_versions.items():
  69. extra_message = ''
  70. actual_version = get_vendor_version_from_module(module_name)
  71. if not actual_version:
  72. extra_message = ' (Unable to locate actual module version, using'\
  73. ' vendor.txt specified version)'
  74. actual_version = expected_version
  75. elif parse_version(actual_version) != parse_version(expected_version):
  76. extra_message = ' (CONFLICT: vendor.txt suggests version should'\
  77. ' be {})'.format(expected_version)
  78. logger.info('%s==%s%s', module_name, actual_version, extra_message)
  79. def show_vendor_versions() -> None:
  80. logger.info('vendored library versions:')
  81. vendor_txt_versions = create_vendor_txt_map()
  82. with indent_log():
  83. show_actual_vendor_versions(vendor_txt_versions)
  84. def show_tags(options: Values) -> None:
  85. tag_limit = 10
  86. target_python = make_target_python(options)
  87. tags = target_python.get_tags()
  88. # Display the target options that were explicitly provided.
  89. formatted_target = target_python.format_given()
  90. suffix = ''
  91. if formatted_target:
  92. suffix = f' (target: {formatted_target})'
  93. msg = 'Compatible tags: {}{}'.format(len(tags), suffix)
  94. logger.info(msg)
  95. if options.verbose < 1 and len(tags) > tag_limit:
  96. tags_limited = True
  97. tags = tags[:tag_limit]
  98. else:
  99. tags_limited = False
  100. with indent_log():
  101. for tag in tags:
  102. logger.info(str(tag))
  103. if tags_limited:
  104. msg = (
  105. '...\n'
  106. '[First {tag_limit} tags shown. Pass --verbose to show all.]'
  107. ).format(tag_limit=tag_limit)
  108. logger.info(msg)
  109. def ca_bundle_info(config: Configuration) -> str:
  110. levels = set()
  111. for key, _ in config.items():
  112. levels.add(key.split('.')[0])
  113. if not levels:
  114. return "Not specified"
  115. levels_that_override_global = ['install', 'wheel', 'download']
  116. global_overriding_level = [
  117. level for level in levels if level in levels_that_override_global
  118. ]
  119. if not global_overriding_level:
  120. return 'global'
  121. if 'global' in levels:
  122. levels.remove('global')
  123. return ", ".join(levels)
  124. class DebugCommand(Command):
  125. """
  126. Display debug information.
  127. """
  128. usage = """
  129. %prog <options>"""
  130. ignore_require_venv = True
  131. def add_options(self) -> None:
  132. cmdoptions.add_target_python_options(self.cmd_opts)
  133. self.parser.insert_option_group(0, self.cmd_opts)
  134. self.parser.config.load()
  135. def run(self, options: Values, args: List[str]) -> int:
  136. logger.warning(
  137. "This command is only meant for debugging. "
  138. "Do not use this with automation for parsing and getting these "
  139. "details, since the output and options of this command may "
  140. "change without notice."
  141. )
  142. show_value('pip version', get_pip_version())
  143. show_value('sys.version', sys.version)
  144. show_value('sys.executable', sys.executable)
  145. show_value('sys.getdefaultencoding', sys.getdefaultencoding())
  146. show_value('sys.getfilesystemencoding', sys.getfilesystemencoding())
  147. show_value(
  148. 'locale.getpreferredencoding', locale.getpreferredencoding(),
  149. )
  150. show_value('sys.platform', sys.platform)
  151. show_sys_implementation()
  152. show_value("'cert' config value", ca_bundle_info(self.parser.config))
  153. show_value("REQUESTS_CA_BUNDLE", os.environ.get('REQUESTS_CA_BUNDLE'))
  154. show_value("CURL_CA_BUNDLE", os.environ.get('CURL_CA_BUNDLE'))
  155. show_value("pip._vendor.certifi.where()", where())
  156. show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED)
  157. show_vendor_versions()
  158. show_tags(options)
  159. return SUCCESS