monkey.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """
  2. Monkey patching of distutils.
  3. """
  4. import functools
  5. import inspect
  6. import platform
  7. import sys
  8. import types
  9. from importlib import import_module
  10. import distutils.filelist
  11. __all__ = []
  12. """
  13. Everything is private. Contact the project team
  14. if you think you need this functionality.
  15. """
  16. def _get_mro(cls):
  17. """
  18. Returns the bases classes for cls sorted by the MRO.
  19. Works around an issue on Jython where inspect.getmro will not return all
  20. base classes if multiple classes share the same name. Instead, this
  21. function will return a tuple containing the class itself, and the contents
  22. of cls.__bases__. See https://github.com/pypa/setuptools/issues/1024.
  23. """
  24. if platform.python_implementation() == "Jython":
  25. return (cls,) + cls.__bases__
  26. return inspect.getmro(cls)
  27. def get_unpatched(item):
  28. lookup = (
  29. get_unpatched_class
  30. if isinstance(item, type)
  31. else get_unpatched_function
  32. if isinstance(item, types.FunctionType)
  33. else lambda item: None
  34. )
  35. return lookup(item)
  36. def get_unpatched_class(cls):
  37. """Protect against re-patching the distutils if reloaded
  38. Also ensures that no other distutils extension monkeypatched the distutils
  39. first.
  40. """
  41. external_bases = (
  42. cls for cls in _get_mro(cls) if not cls.__module__.startswith('setuptools')
  43. )
  44. base = next(external_bases)
  45. if not base.__module__.startswith('distutils'):
  46. msg = "distutils has already been patched by %r" % cls
  47. raise AssertionError(msg)
  48. return base
  49. def patch_all():
  50. import setuptools
  51. # we can't patch distutils.cmd, alas
  52. distutils.core.Command = setuptools.Command
  53. has_issue_12885 = sys.version_info <= (3, 5, 3)
  54. if has_issue_12885:
  55. # fix findall bug in distutils (https://bugs.python.org/issue12885)
  56. distutils.filelist.findall = setuptools.findall
  57. needs_warehouse = (3, 4) < sys.version_info < (3, 4, 6) or (
  58. 3,
  59. 5,
  60. ) < sys.version_info <= (3, 5, 3)
  61. if needs_warehouse:
  62. warehouse = 'https://upload.pypi.org/legacy/'
  63. distutils.config.PyPIRCCommand.DEFAULT_REPOSITORY = warehouse
  64. _patch_distribution_metadata()
  65. # Install Distribution throughout the distutils
  66. for module in distutils.dist, distutils.core, distutils.cmd:
  67. module.Distribution = setuptools.dist.Distribution
  68. # Install the patched Extension
  69. distutils.core.Extension = setuptools.extension.Extension
  70. distutils.extension.Extension = setuptools.extension.Extension
  71. if 'distutils.command.build_ext' in sys.modules:
  72. sys.modules[
  73. 'distutils.command.build_ext'
  74. ].Extension = setuptools.extension.Extension
  75. patch_for_msvc_specialized_compiler()
  76. def _patch_distribution_metadata():
  77. from . import _core_metadata
  78. """Patch write_pkg_file and read_pkg_file for higher metadata standards"""
  79. for attr in (
  80. 'write_pkg_info',
  81. 'write_pkg_file',
  82. 'read_pkg_file',
  83. 'get_metadata_version',
  84. ):
  85. new_val = getattr(_core_metadata, attr)
  86. setattr(distutils.dist.DistributionMetadata, attr, new_val)
  87. def patch_func(replacement, target_mod, func_name):
  88. """
  89. Patch func_name in target_mod with replacement
  90. Important - original must be resolved by name to avoid
  91. patching an already patched function.
  92. """
  93. original = getattr(target_mod, func_name)
  94. # set the 'unpatched' attribute on the replacement to
  95. # point to the original.
  96. vars(replacement).setdefault('unpatched', original)
  97. # replace the function in the original module
  98. setattr(target_mod, func_name, replacement)
  99. def get_unpatched_function(candidate):
  100. return getattr(candidate, 'unpatched')
  101. def patch_for_msvc_specialized_compiler():
  102. """
  103. Patch functions in distutils to use standalone Microsoft Visual C++
  104. compilers.
  105. """
  106. # import late to avoid circular imports on Python < 3.5
  107. msvc = import_module('setuptools.msvc')
  108. if platform.system() != 'Windows':
  109. # Compilers only available on Microsoft Windows
  110. return
  111. def patch_params(mod_name, func_name):
  112. """
  113. Prepare the parameters for patch_func to patch indicated function.
  114. """
  115. repl_prefix = 'msvc14_'
  116. repl_name = repl_prefix + func_name.lstrip('_')
  117. repl = getattr(msvc, repl_name)
  118. mod = import_module(mod_name)
  119. if not hasattr(mod, func_name):
  120. raise ImportError(func_name)
  121. return repl, mod, func_name
  122. # Python 3.5+
  123. msvc14 = functools.partial(patch_params, 'distutils._msvccompiler')
  124. try:
  125. # Patch distutils._msvccompiler._get_vc_env
  126. patch_func(*msvc14('_get_vc_env'))
  127. except ImportError:
  128. pass