Debian Codegraph @

third_party/python/setuptools/_distutils_hack/__init__.py

raw
1 # don't import any costly modules
2 import os
3 import sys
4
5 report_url = (
6 "https://github.com/pypa/setuptools/issues/new?"
7 "template=distutils-deprecation.yml"
8 )
9
10
11 def warn_distutils_present():
12 if 'distutils' not in sys.modules:
13 return
14 import warnings
15
16 warnings.warn(
17 "Distutils was imported before Setuptools, but importing Setuptools "
18 "also replaces the `distutils` module in `sys.modules`. This may lead "
19 "to undesirable behaviors or errors. To avoid these issues, avoid "
20 "using distutils directly, ensure that setuptools is installed in the "
21 "traditional way (e.g. not an editable install), and/or make sure "
22 "that setuptools is always imported before distutils."
23 )
24
25
26 def clear_distutils():
27 if 'distutils' not in sys.modules:
28 return
29 import warnings
30
31 warnings.warn(
32 "Setuptools is replacing distutils. Support for replacing "
33 "an already imported distutils is deprecated. In the future, "
34 "this condition will fail. "
35 f"Register concerns at {report_url}"
36 )
37 mods = [
38 name
39 for name in sys.modules
40 if name == "distutils" or name.startswith("distutils.")
41 ]
42 for name in mods:
43 del sys.modules[name]
44
45
46 def enabled():
47 """
48 Allow selection of distutils by environment variable.
49 """
50 which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
51 if which == 'stdlib':
52 import warnings
53
54 warnings.warn(
55 "Reliance on distutils from stdlib is deprecated. Users "
56 "must rely on setuptools to provide the distutils module. "
57 "Avoid importing distutils or import setuptools first, "
58 "and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. "
59 f"Register concerns at {report_url}"
60 )
61 return which == 'local'
62
63
64 def ensure_local_distutils():
65 import importlib
66
67 clear_distutils()
68
69 # With the DistutilsMetaFinder in place,
70 # perform an import to cause distutils to be
71 # loaded from setuptools._distutils. Ref #2906.
72 with shim():
73 importlib.import_module('distutils')
74
75 # check that submodules load as expected
76 core = importlib.import_module('distutils.core')
77 assert '_distutils' in core.__file__, core.__file__
78 assert 'setuptools._distutils.log' not in sys.modules
79
80
81 def do_override():
82 """
83 Ensure that the local copy of distutils is preferred over stdlib.
84
85 See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
86 for more motivation.
87 """
88 if enabled():
89 warn_distutils_present()
90 ensure_local_distutils()
91
92
93 class _TrivialRe:
94 def __init__(self, *patterns):
95 self._patterns = patterns
96
97 def match(self, string):
98 return all(pat in string for pat in self._patterns)
99
100
101 class DistutilsMetaFinder:
102 def find_spec(self, fullname, path, target=None):
103 # optimization: only consider top level modules and those
104 # found in the CPython test suite.
105 if path is not None and not fullname.startswith('test.'):
106 return None
107
108 method_name = 'spec_for_{fullname}'.format(**locals())
109 method = getattr(self, method_name, lambda: None)
110 return method()
111
112 def spec_for_distutils(self):
113 if self.is_cpython():
114 return None
115
116 import importlib
117 import importlib.abc
118 import importlib.util
119
120 try:
121 mod = importlib.import_module('setuptools._distutils')
122 except Exception:
123 # There are a couple of cases where setuptools._distutils
124 # may not be present:
125 # - An older Setuptools without a local distutils is
126 # taking precedence. Ref #2957.
127 # - Path manipulation during sitecustomize removes
128 # setuptools from the path but only after the hook
129 # has been loaded. Ref #2980.
130 # In either case, fall back to stdlib behavior.
131 return None
132
133 class DistutilsLoader(importlib.abc.Loader):
134 def create_module(self, spec):
135 mod.__name__ = 'distutils'
136 return mod
137
138 def exec_module(self, module):
139 pass
140
141 return importlib.util.spec_from_loader(
142 'distutils', DistutilsLoader(), origin=mod.__file__
143 )
144
145 @staticmethod
146 def is_cpython():
147 """
148 Suppress supplying distutils for CPython (build and tests).
149 Ref #2965 and #3007.
150 """
151 return os.path.isfile('pybuilddir.txt')
152
153 def spec_for_pip(self):
154 """
155 Ensure stdlib distutils when running under pip.
156 See pypa/pip#8761 for rationale.
157 """
158 if sys.version_info >= (3, 12) or self.pip_imported_during_build():
159 return
160 clear_distutils()
161 self.spec_for_distutils = lambda: None
162
163 @classmethod
164 def pip_imported_during_build(cls):
165 """
166 Detect if pip is being imported in a build script. Ref #2355.
167 """
168 import traceback
169
170 return any(
171 cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None)
172 )
173
174 @staticmethod
175 def frame_file_is_setup(frame):
176 """
177 Return True if the indicated frame suggests a setup.py file.
178 """
179 # some frames may not have __file__ (#2940)
180 return frame.f_globals.get('__file__', '').endswith('setup.py')
181
182 def spec_for_sensitive_tests(self):
183 """
184 Ensure stdlib distutils when running select tests under CPython.
185
186 python/cpython#91169
187 """
188 clear_distutils()
189 self.spec_for_distutils = lambda: None
190
191 sensitive_tests = (
192 [
193 'test.test_distutils',
194 'test.test_peg_generator',
195 'test.test_importlib',
196 ]
197 if sys.version_info < (3, 10)
198 else [
199 'test.test_distutils',
200 ]
201 )
202
203
204 for name in DistutilsMetaFinder.sensitive_tests:
205 setattr(
206 DistutilsMetaFinder,
207 f'spec_for_{name}',
208 DistutilsMetaFinder.spec_for_sensitive_tests,
209 )
210
211
212 DISTUTILS_FINDER = DistutilsMetaFinder()
213
214
215 def add_shim():
216 DISTUTILS_FINDER in sys.meta_path or insert_shim()
217
218
219 class shim:
220 def __enter__(self) -> None:
221 insert_shim()
222
223 def __exit__(self, exc: object, value: object, tb: object) -> None:
224 _remove_shim()
225
226
227 def insert_shim():
228 sys.meta_path.insert(0, DISTUTILS_FINDER)
229
230
231 def _remove_shim():
232 try:
233 sys.meta_path.remove(DISTUTILS_FINDER)
234 except ValueError:
235 pass
236
237
238 if sys.version_info < (3, 12):
239 # DistutilsMetaFinder can only be disabled in Python < 3.12 (PEP 632)
240 remove_shim = _remove_shim