We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[BUG] Having setuptools installed causes cpython stdlib build to fail
### setuptools version

setuptools>=60

### Python version

Python 3.9.9 (and probably others)

### OS

Probably affects all; reported on macOS

### Additional environment information

Originally reported in the context of MacPorts' python39 and py39-setuptools ports.

### Description

If you have setuptools installed and attempt to build cpython from source, setuptools' copy of distutils may be used when building the stdlib modules and cause the build to fail due to an incompatibility.

This is easily cured by setting `SETUPTOOLS_USE_DISTUTILS=stdlib` if you understand the problem, but if you don't, it's a pretty baffling failure mode.

Downstream report: https://trac.macports.org/ticket/64352

### Expected behavior

Cpython build uses its own distutils and succeeds.

### How to Reproduce

1. Install setuptools into a convenient site-packages directory.
2. Configure cpython to install in a prefix such that it will be using the site-packages directory from step 1.
3. Build cpython.

### Output

```console
Traceback (most recent call last):
  File "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/./setup.py", line 2598, in <module>
    main()
  File "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/./setup.py", line 2568, in main
    setup(# PyPI Metadata (PEP 301)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/core.py", line 148, in setup
    return run_commands(dist)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/core.py", line 163, in run_commands
    dist.run_commands()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/dist.py", line 967, in run_commands
    self.run_command(cmd)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/dist.py", line 986, in run_command
    cmd_obj.run()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build.py", line 135, in run
    self.run_command(cmd_name)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/dist.py", line 986, in run_command
    cmd_obj.run()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py", line 339, in run
    self.build_extensions()
  File "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/./setup.py", line 456, in build_extensions
    build_ext.build_extensions(self)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py", line 446, in build_extensions
    self._build_extensions_parallel()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py", line 468, in _build_extensions_parallel
    fut.result()
  File "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/Lib/concurrent/futures/_base.py", line 445, in result
    return self.__get_result()
  File "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/Lib/concurrent/futures/_base.py", line 390, in __get_result
    raise self._exception
  File "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/Lib/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/./setup.py", line 554, in build_extension
    build_ext.build_extension(self, ext)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py", line 528, in build_extension
    objects = self.compiler.compile(sources,
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py", line 574, in compile
    self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/unixccompiler.py", line 117, in _compile
    self.spawn(compiler_so + cc_args + [src, '-o', obj] +
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py", line 917, in spawn
    spawn(cmd, dry_run=self.dry_run, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/spawn.py", line 38, in spawn
    log.info(subprocess.list2cmdline(cmd))
AttributeError: module '_bootsubprocess' has no attribute 'list2cmdline'
make: *** [sharedmods] Error 1
make: Leaving directory `/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9'
Command failed:  cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9" && /usr/bin/make -j2 -w all
```


### Code of Conduct

- [ ] I agree to follow the PSF Code of Conduct

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `_distutils_hack/__init__.py`
Content:
```
1 # don't import any costly modules
2 import sys
3 import os
4 
5 
6 is_pypy = '__pypy__' in sys.builtin_module_names
7 
8 
9 def warn_distutils_present():
10     if 'distutils' not in sys.modules:
11         return
12     if is_pypy and sys.version_info < (3, 7):
13         # PyPy for 3.6 unconditionally imports distutils, so bypass the warning
14         # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
15         return
16     import warnings
17     warnings.warn(
18         "Distutils was imported before Setuptools, but importing Setuptools "
19         "also replaces the `distutils` module in `sys.modules`. This may lead "
20         "to undesirable behaviors or errors. To avoid these issues, avoid "
21         "using distutils directly, ensure that setuptools is installed in the "
22         "traditional way (e.g. not an editable install), and/or make sure "
23         "that setuptools is always imported before distutils.")
24 
25 
26 def clear_distutils():
27     if 'distutils' not in sys.modules:
28         return
29     import warnings
30     warnings.warn("Setuptools is replacing distutils.")
31     mods = [
32         name for name in sys.modules
33         if name == "distutils" or name.startswith("distutils.")
34     ]
35     for name in mods:
36         del sys.modules[name]
37 
38 
39 def enabled():
40     """
41     Allow selection of distutils by environment variable.
42     """
43     which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
44     return which == 'local'
45 
46 
47 def ensure_local_distutils():
48     import importlib
49     clear_distutils()
50 
51     # With the DistutilsMetaFinder in place,
52     # perform an import to cause distutils to be
53     # loaded from setuptools._distutils. Ref #2906.
54     with shim():
55         importlib.import_module('distutils')
56 
57     # check that submodules load as expected
58     core = importlib.import_module('distutils.core')
59     assert '_distutils' in core.__file__, core.__file__
60 
61 
62 def do_override():
63     """
64     Ensure that the local copy of distutils is preferred over stdlib.
65 
66     See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
67     for more motivation.
68     """
69     if enabled():
70         warn_distutils_present()
71         ensure_local_distutils()
72 
73 
74 class _TrivialRe:
75     def __init__(self, *patterns):
76         self._patterns = patterns
77 
78     def match(self, string):
79         return all(pat in string for pat in self._patterns)
80 
81 
82 class DistutilsMetaFinder:
83     def find_spec(self, fullname, path, target=None):
84         if path is not None:
85             return
86 
87         method_name = 'spec_for_{fullname}'.format(**locals())
88         method = getattr(self, method_name, lambda: None)
89         return method()
90 
91     def spec_for_distutils(self):
92         import importlib
93         import importlib.abc
94         import importlib.util
95 
96         try:
97             mod = importlib.import_module('setuptools._distutils')
98         except Exception:
99             # There are a couple of cases where setuptools._distutils
100             # may not be present:
101             # - An older Setuptools without a local distutils is
102             #   taking precedence. Ref #2957.
103             # - Path manipulation during sitecustomize removes
104             #   setuptools from the path but only after the hook
105             #   has been loaded. Ref #2980.
106             # In either case, fall back to stdlib behavior.
107             return
108 
109         class DistutilsLoader(importlib.abc.Loader):
110 
111             def create_module(self, spec):
112                 return mod
113 
114             def exec_module(self, module):
115                 pass
116 
117         return importlib.util.spec_from_loader(
118             'distutils', DistutilsLoader(), origin=mod.__file__
119         )
120 
121     def spec_for_pip(self):
122         """
123         Ensure stdlib distutils when running under pip.
124         See pypa/pip#8761 for rationale.
125         """
126         if self.pip_imported_during_build():
127             return
128         clear_distutils()
129         self.spec_for_distutils = lambda: None
130 
131     def spec_for_setuptools(self):
132         """
133         get-pip imports setuptools solely for the purpose of
134         determining if it's installed. In this case, provide
135         a stubbed spec to represent setuptools being present
136         without invoking any behavior.
137 
138         Workaround for pypa/get-pip#137. Ref #2993.
139         """
140         if not self.is_script('get-pip'):
141             return
142 
143         import importlib
144 
145         class StubbedLoader(importlib.abc.Loader):
146 
147             def create_module(self, spec):
148                 import types
149                 return types.ModuleType('setuptools')
150 
151             def exec_module(self, module):
152                 pass
153 
154         return importlib.util.spec_from_loader(
155             'setuptools', StubbedLoader(),
156         )
157 
158     @classmethod
159     def pip_imported_during_build(cls):
160         """
161         Detect if pip is being imported in a build script. Ref #2355.
162         """
163         import traceback
164         return any(
165             cls.frame_file_is_setup(frame)
166             for frame, line in traceback.walk_stack(None)
167         )
168 
169     @staticmethod
170     def is_script(name):
171         try:
172             import __main__
173             return os.path.basename(__main__.__file__) == f'{name}.py'
174         except AttributeError:
175             pass
176 
177     @staticmethod
178     def frame_file_is_setup(frame):
179         """
180         Return True if the indicated frame suggests a setup.py file.
181         """
182         # some frames may not have __file__ (#2940)
183         return frame.f_globals.get('__file__', '').endswith('setup.py')
184 
185 
186 DISTUTILS_FINDER = DistutilsMetaFinder()
187 
188 
189 def add_shim():
190     DISTUTILS_FINDER in sys.meta_path or insert_shim()
191 
192 
193 class shim:
194     def __enter__(self):
195         insert_shim()
196 
197     def __exit__(self, exc, value, tb):
198         remove_shim()
199 
200 
201 def insert_shim():
202     sys.meta_path.insert(0, DISTUTILS_FINDER)
203 
204 
205 def remove_shim():
206     try:
207         sys.meta_path.remove(DISTUTILS_FINDER)
208     except ValueError:
209         pass
210
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/_distutils_hack/__init__.py b/_distutils_hack/__init__.py
--- a/_distutils_hack/__init__.py
+++ b/_distutils_hack/__init__.py
@@ -89,6 +89,9 @@
         return method()
 
     def spec_for_distutils(self):
+        if self.is_cpython():
+            return
+
         import importlib
         import importlib.abc
         import importlib.util
@@ -118,6 +121,14 @@
             'distutils', DistutilsLoader(), origin=mod.__file__
         )
 
+    @staticmethod
+    def is_cpython():
+        """
+        Suppress supplying distutils for CPython (build and tests).
+        Ref #2965 and #3007.
+        """
+        return os.path.isfile('pybuilddir.txt')
+
     def spec_for_pip(self):
         """
         Ensure stdlib distutils when running under pip.

{"golden_diff": "diff --git a/_distutils_hack/__init__.py b/_distutils_hack/__init__.py\n--- a/_distutils_hack/__init__.py\n+++ b/_distutils_hack/__init__.py\n@@ -89,6 +89,9 @@\n         return method()\n \n     def spec_for_distutils(self):\n+        if self.is_cpython():\n+            return\n+\n         import importlib\n         import importlib.abc\n         import importlib.util\n@@ -118,6 +121,14 @@\n             'distutils', DistutilsLoader(), origin=mod.__file__\n         )\n \n+    @staticmethod\n+    def is_cpython():\n+        \"\"\"\n+        Suppress supplying distutils for CPython (build and tests).\n+        Ref #2965 and #3007.\n+        \"\"\"\n+        return os.path.isfile('pybuilddir.txt')\n+\n     def spec_for_pip(self):\n         \"\"\"\n         Ensure stdlib distutils when running under pip.\n", "issue": "[BUG] Having setuptools installed causes cpython stdlib build to fail\n### setuptools version\n\nsetuptools>=60\n\n### Python version\n\nPython 3.9.9 (and probably others)\n\n### OS\n\nProbably affects all; reported on macOS\n\n### Additional environment information\n\nOriginally reported in the context of MacPorts' python39 and py39-setuptools ports.\n\n### Description\n\nIf you have setuptools installed and attempt to build cpython from source, setuptools' copy of distutils may be used when building the stdlib modules and cause the build to fail due to an incompatibility.\r\n\r\nThis is easily cured by setting `SETUPTOOLS_USE_DISTUTILS=stdlib` if you understand the problem, but if you don't, it's a pretty baffling failure mode.\r\n\r\nDownstream report: https://trac.macports.org/ticket/64352\n\n### Expected behavior\n\nCpython build uses its own distutils and succeeds.\n\n### How to Reproduce\n\n1. Install setuptools into a convenient site-packages directory.\r\n2. Configure cpython to install in a prefix such that it will be using the site-packages directory from step 1.\r\n3. Build cpython.\n\n### Output\n\n```console\r\nTraceback (most recent call last):\r\n  File \"/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/./setup.py\", line 2598, in <module>\r\n    main()\r\n  File \"/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/./setup.py\", line 2568, in main\r\n    setup(# PyPI Metadata (PEP 301)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/core.py\", line 148, in setup\r\n    return run_commands(dist)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/core.py\", line 163, in run_commands\r\n    dist.run_commands()\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/dist.py\", line 967, in run_commands\r\n    self.run_command(cmd)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/dist.py\", line 986, in run_command\r\n    cmd_obj.run()\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build.py\", line 135, in run\r\n    self.run_command(cmd_name)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/cmd.py\", line 313, in run_command\r\n    self.distribution.run_command(command)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/dist.py\", line 986, in run_command\r\n    cmd_obj.run()\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py\", line 339, in run\r\n    self.build_extensions()\r\n  File \"/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/./setup.py\", line 456, in build_extensions\r\n    build_ext.build_extensions(self)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py\", line 446, in build_extensions\r\n    self._build_extensions_parallel()\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py\", line 468, in _build_extensions_parallel\r\n    fut.result()\r\n  File \"/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/Lib/concurrent/futures/_base.py\", line 445, in result\r\n    return self.__get_result()\r\n  File \"/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/Lib/concurrent/futures/_base.py\", line 390, in __get_result\r\n    raise self._exception\r\n  File \"/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/Lib/concurrent/futures/thread.py\", line 58, in run\r\n    result = self.fn(*self.args, **self.kwargs)\r\n  File \"/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9/./setup.py\", line 554, in build_extension\r\n    build_ext.build_extension(self, ext)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/command/build_ext.py\", line 528, in build_extension\r\n    objects = self.compiler.compile(sources,\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py\", line 574, in compile\r\n    self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/unixccompiler.py\", line 117, in _compile\r\n    self.spawn(compiler_so + cc_args + [src, '-o', obj] +\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py\", line 917, in spawn\r\n    spawn(cmd, dry_run=self.dry_run, **kwargs)\r\n  File \"/opt/local/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/setuptools/_distutils/spawn.py\", line 38, in spawn\r\n    log.info(subprocess.list2cmdline(cmd))\r\nAttributeError: module '_bootsubprocess' has no attribute 'list2cmdline'\r\nmake: *** [sharedmods] Error 1\r\nmake: Leaving directory `/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9'\r\nCommand failed:  cd \"/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_macports_release_tarballs_ports_lang_python39/python39/work/Python-3.9.9\" && /usr/bin/make -j2 -w all\r\n```\r\n\n\n### Code of Conduct\n\n- [ ] I agree to follow the PSF Code of Conduct\n", "before_files": [{"content": "# don't import any costly modules\nimport sys\nimport os\n\n\nis_pypy = '__pypy__' in sys.builtin_module_names\n\n\ndef warn_distutils_present():\n    if 'distutils' not in sys.modules:\n        return\n    if is_pypy and sys.version_info < (3, 7):\n        # PyPy for 3.6 unconditionally imports distutils, so bypass the warning\n        # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250\n        return\n    import warnings\n    warnings.warn(\n        \"Distutils was imported before Setuptools, but importing Setuptools \"\n        \"also replaces the `distutils` module in `sys.modules`. This may lead \"\n        \"to undesirable behaviors or errors. To avoid these issues, avoid \"\n        \"using distutils directly, ensure that setuptools is installed in the \"\n        \"traditional way (e.g. not an editable install), and/or make sure \"\n        \"that setuptools is always imported before distutils.\")\n\n\ndef clear_distutils():\n    if 'distutils' not in sys.modules:\n        return\n    import warnings\n    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [\n        name for name in sys.modules\n        if name == \"distutils\" or name.startswith(\"distutils.\")\n    ]\n    for name in mods:\n        del sys.modules[name]\n\n\ndef enabled():\n    \"\"\"\n    Allow selection of distutils by environment variable.\n    \"\"\"\n    which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')\n    return which == 'local'\n\n\ndef ensure_local_distutils():\n    import importlib\n    clear_distutils()\n\n    # With the DistutilsMetaFinder in place,\n    # perform an import to cause distutils to be\n    # loaded from setuptools._distutils. Ref #2906.\n    with shim():\n        importlib.import_module('distutils')\n\n    # check that submodules load as expected\n    core = importlib.import_module('distutils.core')\n    assert '_distutils' in core.__file__, core.__file__\n\n\ndef do_override():\n    \"\"\"\n    Ensure that the local copy of distutils is preferred over stdlib.\n\n    See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401\n    for more motivation.\n    \"\"\"\n    if enabled():\n        warn_distutils_present()\n        ensure_local_distutils()\n\n\nclass _TrivialRe:\n    def __init__(self, *patterns):\n        self._patterns = patterns\n\n    def match(self, string):\n        return all(pat in string for pat in self._patterns)\n\n\nclass DistutilsMetaFinder:\n    def find_spec(self, fullname, path, target=None):\n        if path is not None:\n            return\n\n        method_name = 'spec_for_{fullname}'.format(**locals())\n        method = getattr(self, method_name, lambda: None)\n        return method()\n\n    def spec_for_distutils(self):\n        import importlib\n        import importlib.abc\n        import importlib.util\n\n        try:\n            mod = importlib.import_module('setuptools._distutils')\n        except Exception:\n            # There are a couple of cases where setuptools._distutils\n            # may not be present:\n            # - An older Setuptools without a local distutils is\n            #   taking precedence. Ref #2957.\n            # - Path manipulation during sitecustomize removes\n            #   setuptools from the path but only after the hook\n            #   has been loaded. Ref #2980.\n            # In either case, fall back to stdlib behavior.\n            return\n\n        class DistutilsLoader(importlib.abc.Loader):\n\n            def create_module(self, spec):\n                return mod\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader(\n            'distutils', DistutilsLoader(), origin=mod.__file__\n        )\n\n    def spec_for_pip(self):\n        \"\"\"\n        Ensure stdlib distutils when running under pip.\n        See pypa/pip#8761 for rationale.\n        \"\"\"\n        if self.pip_imported_during_build():\n            return\n        clear_distutils()\n        self.spec_for_distutils = lambda: None\n\n    def spec_for_setuptools(self):\n        \"\"\"\n        get-pip imports setuptools solely for the purpose of\n        determining if it's installed. In this case, provide\n        a stubbed spec to represent setuptools being present\n        without invoking any behavior.\n\n        Workaround for pypa/get-pip#137. Ref #2993.\n        \"\"\"\n        if not self.is_script('get-pip'):\n            return\n\n        import importlib\n\n        class StubbedLoader(importlib.abc.Loader):\n\n            def create_module(self, spec):\n                import types\n                return types.ModuleType('setuptools')\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader(\n            'setuptools', StubbedLoader(),\n        )\n\n    @classmethod\n    def pip_imported_during_build(cls):\n        \"\"\"\n        Detect if pip is being imported in a build script. Ref #2355.\n        \"\"\"\n        import traceback\n        return any(\n            cls.frame_file_is_setup(frame)\n            for frame, line in traceback.walk_stack(None)\n        )\n\n    @staticmethod\n    def is_script(name):\n        try:\n            import __main__\n            return os.path.basename(__main__.__file__) == f'{name}.py'\n        except AttributeError:\n            pass\n\n    @staticmethod\n    def frame_file_is_setup(frame):\n        \"\"\"\n        Return True if the indicated frame suggests a setup.py file.\n        \"\"\"\n        # some frames may not have __file__ (#2940)\n        return frame.f_globals.get('__file__', '').endswith('setup.py')\n\n\nDISTUTILS_FINDER = DistutilsMetaFinder()\n\n\ndef add_shim():\n    DISTUTILS_FINDER in sys.meta_path or insert_shim()\n\n\nclass shim:\n    def __enter__(self):\n        insert_shim()\n\n    def __exit__(self, exc, value, tb):\n        remove_shim()\n\n\ndef insert_shim():\n    sys.meta_path.insert(0, DISTUTILS_FINDER)\n\n\ndef remove_shim():\n    try:\n        sys.meta_path.remove(DISTUTILS_FINDER)\n    except ValueError:\n        pass\n", "path": "_distutils_hack/__init__.py"}], "after_files": [{"content": "# don't import any costly modules\nimport sys\nimport os\n\n\nis_pypy = '__pypy__' in sys.builtin_module_names\n\n\ndef warn_distutils_present():\n    if 'distutils' not in sys.modules:\n        return\n    if is_pypy and sys.version_info < (3, 7):\n        # PyPy for 3.6 unconditionally imports distutils, so bypass the warning\n        # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250\n        return\n    import warnings\n    warnings.warn(\n        \"Distutils was imported before Setuptools, but importing Setuptools \"\n        \"also replaces the `distutils` module in `sys.modules`. This may lead \"\n        \"to undesirable behaviors or errors. To avoid these issues, avoid \"\n        \"using distutils directly, ensure that setuptools is installed in the \"\n        \"traditional way (e.g. not an editable install), and/or make sure \"\n        \"that setuptools is always imported before distutils.\")\n\n\ndef clear_distutils():\n    if 'distutils' not in sys.modules:\n        return\n    import warnings\n    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [\n        name for name in sys.modules\n        if name == \"distutils\" or name.startswith(\"distutils.\")\n    ]\n    for name in mods:\n        del sys.modules[name]\n\n\ndef enabled():\n    \"\"\"\n    Allow selection of distutils by environment variable.\n    \"\"\"\n    which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')\n    return which == 'local'\n\n\ndef ensure_local_distutils():\n    import importlib\n    clear_distutils()\n\n    # With the DistutilsMetaFinder in place,\n    # perform an import to cause distutils to be\n    # loaded from setuptools._distutils. Ref #2906.\n    with shim():\n        importlib.import_module('distutils')\n\n    # check that submodules load as expected\n    core = importlib.import_module('distutils.core')\n    assert '_distutils' in core.__file__, core.__file__\n\n\ndef do_override():\n    \"\"\"\n    Ensure that the local copy of distutils is preferred over stdlib.\n\n    See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401\n    for more motivation.\n    \"\"\"\n    if enabled():\n        warn_distutils_present()\n        ensure_local_distutils()\n\n\nclass _TrivialRe:\n    def __init__(self, *patterns):\n        self._patterns = patterns\n\n    def match(self, string):\n        return all(pat in string for pat in self._patterns)\n\n\nclass DistutilsMetaFinder:\n    def find_spec(self, fullname, path, target=None):\n        if path is not None:\n            return\n\n        method_name = 'spec_for_{fullname}'.format(**locals())\n        method = getattr(self, method_name, lambda: None)\n        return method()\n\n    def spec_for_distutils(self):\n        if self.is_cpython():\n            return\n\n        import importlib\n        import importlib.abc\n        import importlib.util\n\n        try:\n            mod = importlib.import_module('setuptools._distutils')\n        except Exception:\n            # There are a couple of cases where setuptools._distutils\n            # may not be present:\n            # - An older Setuptools without a local distutils is\n            #   taking precedence. Ref #2957.\n            # - Path manipulation during sitecustomize removes\n            #   setuptools from the path but only after the hook\n            #   has been loaded. Ref #2980.\n            # In either case, fall back to stdlib behavior.\n            return\n\n        class DistutilsLoader(importlib.abc.Loader):\n\n            def create_module(self, spec):\n                return mod\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader(\n            'distutils', DistutilsLoader(), origin=mod.__file__\n        )\n\n    @staticmethod\n    def is_cpython():\n        \"\"\"\n        Suppress supplying distutils for CPython (build and tests).\n        Ref #2965 and #3007.\n        \"\"\"\n        return os.path.isfile('pybuilddir.txt')\n\n    def spec_for_pip(self):\n        \"\"\"\n        Ensure stdlib distutils when running under pip.\n        See pypa/pip#8761 for rationale.\n        \"\"\"\n        if self.pip_imported_during_build():\n            return\n        clear_distutils()\n        self.spec_for_distutils = lambda: None\n\n    def spec_for_setuptools(self):\n        \"\"\"\n        get-pip imports setuptools solely for the purpose of\n        determining if it's installed. In this case, provide\n        a stubbed spec to represent setuptools being present\n        without invoking any behavior.\n\n        Workaround for pypa/get-pip#137. Ref #2993.\n        \"\"\"\n        if not self.is_script('get-pip'):\n            return\n\n        import importlib\n\n        class StubbedLoader(importlib.abc.Loader):\n\n            def create_module(self, spec):\n                import types\n                return types.ModuleType('setuptools')\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader(\n            'setuptools', StubbedLoader(),\n        )\n\n    @classmethod\n    def pip_imported_during_build(cls):\n        \"\"\"\n        Detect if pip is being imported in a build script. Ref #2355.\n        \"\"\"\n        import traceback\n        return any(\n            cls.frame_file_is_setup(frame)\n            for frame, line in traceback.walk_stack(None)\n        )\n\n    @staticmethod\n    def is_script(name):\n        try:\n            import __main__\n            return os.path.basename(__main__.__file__) == f'{name}.py'\n        except AttributeError:\n            pass\n\n    @staticmethod\n    def frame_file_is_setup(frame):\n        \"\"\"\n        Return True if the indicated frame suggests a setup.py file.\n        \"\"\"\n        # some frames may not have __file__ (#2940)\n        return frame.f_globals.get('__file__', '').endswith('setup.py')\n\n\nDISTUTILS_FINDER = DistutilsMetaFinder()\n\n\ndef add_shim():\n    DISTUTILS_FINDER in sys.meta_path or insert_shim()\n\n\nclass shim:\n    def __enter__(self):\n        insert_shim()\n\n    def __exit__(self, exc, value, tb):\n        remove_shim()\n\n\ndef insert_shim():\n    sys.meta_path.insert(0, DISTUTILS_FINDER)\n\n\ndef remove_shim():\n    try:\n        sys.meta_path.remove(DISTUTILS_FINDER)\n    except ValueError:\n        pass\n", "path": "_distutils_hack/__init__.py"}]}