monkey.py 4.7 KB

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