We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[BUG] DistutilsMetaFinder appears multiple times on sys.meta_path
### setuptools version

setuptools==60.0.4

### Python version

python3.8

### OS

Any

### Additional environment information

N/A

### Description

The _DistutilsMetaFinder meta_path finder shim is installed multiple times, at least twice by `site.py` via the `.pth` shim, and once by `ensure_local_distutils` when `setuptools` is actually imported. It's unlikely to be a problem, especially since it's literally the same instance, but `add_shim` should be idempotent instead of blindly inserting the shim each time it's called. It also appears that the intent was to remove the shim entirely once distutils has been loaded, but since it's added more than once, the removal in the import leaves two references to it in `sys.meta_path` after setuptools has been imported.

### Expected behavior

After setuptools has been imported, the distutils shim finder is no longer on the meta path.

### How to Reproduce

(with setuptools>60 installed):
python -c "import sys; print(f'Before: {sys.meta_path}'); import setuptools; print(f'After: {sys.meta_path}')"


### Output

```console
Before: [<_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_virtualenv._Finder object at 0x7fe4d2806f70>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>]
After: [<_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_virtualenv._Finder object at 0x7fe4d2806f70>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>, <pkg_resources.extern.VendorImporter object at 0x7fe4d21c5460>, <setuptools.extern.VendorImporter object at 0x7fe4d1f2a100>]
```


### Code of Conduct

- [X] I agree to follow the PSF Code of Conduct
[BUG] DistutilsMetaFinder appears multiple times on sys.meta_path
### setuptools version

setuptools==60.0.4

### Python version

python3.8

### OS

Any

### Additional environment information

N/A

### Description

The _DistutilsMetaFinder meta_path finder shim is installed multiple times, at least twice by `site.py` via the `.pth` shim, and once by `ensure_local_distutils` when `setuptools` is actually imported. It's unlikely to be a problem, especially since it's literally the same instance, but `add_shim` should be idempotent instead of blindly inserting the shim each time it's called. It also appears that the intent was to remove the shim entirely once distutils has been loaded, but since it's added more than once, the removal in the import leaves two references to it in `sys.meta_path` after setuptools has been imported.

### Expected behavior

After setuptools has been imported, the distutils shim finder is no longer on the meta path.

### How to Reproduce

(with setuptools>60 installed):
python -c "import sys; print(f'Before: {sys.meta_path}'); import setuptools; print(f'After: {sys.meta_path}')"


### Output

```console
Before: [<_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_virtualenv._Finder object at 0x7fe4d2806f70>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>]
After: [<_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_virtualenv._Finder object at 0x7fe4d2806f70>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>, <pkg_resources.extern.VendorImporter object at 0x7fe4d21c5460>, <setuptools.extern.VendorImporter object at 0x7fe4d1f2a100>]
```


### Code of Conduct

- [X] 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 import sys
2 import os
3 import re
4 import importlib
5 import warnings
6 
7 
8 is_pypy = '__pypy__' in sys.builtin_module_names
9 
10 
11 warnings.filterwarnings('ignore',
12                         r'.+ distutils\b.+ deprecated',
13                         DeprecationWarning)
14 
15 
16 def warn_distutils_present():
17     if 'distutils' not in sys.modules:
18         return
19     if is_pypy and sys.version_info < (3, 7):
20         # PyPy for 3.6 unconditionally imports distutils, so bypass the warning
21         # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
22         return
23     warnings.warn(
24         "Distutils was imported before Setuptools, but importing Setuptools "
25         "also replaces the `distutils` module in `sys.modules`. This may lead "
26         "to undesirable behaviors or errors. To avoid these issues, avoid "
27         "using distutils directly, ensure that setuptools is installed in the "
28         "traditional way (e.g. not an editable install), and/or make sure "
29         "that setuptools is always imported before distutils.")
30 
31 
32 def clear_distutils():
33     if 'distutils' not in sys.modules:
34         return
35     warnings.warn("Setuptools is replacing distutils.")
36     mods = [name for name in sys.modules if re.match(r'distutils\b', name)]
37     for name in mods:
38         del sys.modules[name]
39 
40 
41 def enabled():
42     """
43     Allow selection of distutils by environment variable.
44     """
45     which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
46     return which == 'local'
47 
48 
49 def ensure_local_distutils():
50     clear_distutils()
51 
52     # With the DistutilsMetaFinder in place,
53     # perform an import to cause distutils to be
54     # loaded from setuptools._distutils. Ref #2906.
55     add_shim()
56     importlib.import_module('distutils')
57     remove_shim()
58 
59     # check that submodules load as expected
60     core = importlib.import_module('distutils.core')
61     assert '_distutils' in core.__file__, core.__file__
62 
63 
64 def do_override():
65     """
66     Ensure that the local copy of distutils is preferred over stdlib.
67 
68     See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
69     for more motivation.
70     """
71     if enabled():
72         warn_distutils_present()
73         ensure_local_distutils()
74 
75 
76 class DistutilsMetaFinder:
77     def find_spec(self, fullname, path, target=None):
78         if path is not None:
79             return
80 
81         method_name = 'spec_for_{fullname}'.format(**locals())
82         method = getattr(self, method_name, lambda: None)
83         return method()
84 
85     def spec_for_distutils(self):
86         import importlib.abc
87         import importlib.util
88 
89         class DistutilsLoader(importlib.abc.Loader):
90 
91             def create_module(self, spec):
92                 return importlib.import_module('setuptools._distutils')
93 
94             def exec_module(self, module):
95                 pass
96 
97         return importlib.util.spec_from_loader('distutils', DistutilsLoader())
98 
99     def spec_for_pip(self):
100         """
101         Ensure stdlib distutils when running under pip.
102         See pypa/pip#8761 for rationale.
103         """
104         if self.pip_imported_during_build():
105             return
106         clear_distutils()
107         self.spec_for_distutils = lambda: None
108 
109     @classmethod
110     def pip_imported_during_build(cls):
111         """
112         Detect if pip is being imported in a build script. Ref #2355.
113         """
114         import traceback
115         return any(
116             cls.frame_file_is_setup(frame)
117             for frame, line in traceback.walk_stack(None)
118         )
119 
120     @staticmethod
121     def frame_file_is_setup(frame):
122         """
123         Return True if the indicated frame suggests a setup.py file.
124         """
125         # some frames may not have __file__ (#2940)
126         return frame.f_globals.get('__file__', '').endswith('setup.py')
127 
128 
129 DISTUTILS_FINDER = DistutilsMetaFinder()
130 
131 
132 def add_shim():
133     sys.meta_path.insert(0, DISTUTILS_FINDER)
134 
135 
136 def remove_shim():
137     try:
138         sys.meta_path.remove(DISTUTILS_FINDER)
139     except ValueError:
140         pass
141
```

Path: `setup.py`
Content:
```
1 #!/usr/bin/env python
2 
3 import os
4 import sys
5 import textwrap
6 
7 import setuptools
8 from setuptools.command.install import install
9 
10 here = os.path.dirname(__file__)
11 
12 
13 package_data = dict(
14     setuptools=['script (dev).tmpl', 'script.tmpl', 'site-patch.py'],
15 )
16 
17 force_windows_specific_files = (
18     os.environ.get("SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES", "1").lower()
19     not in ("", "0", "false", "no")
20 )
21 
22 include_windows_files = sys.platform == 'win32' or force_windows_specific_files
23 
24 if include_windows_files:
25     package_data.setdefault('setuptools', []).extend(['*.exe'])
26     package_data.setdefault('setuptools.command', []).extend(['*.xml'])
27 
28 
29 def pypi_link(pkg_filename):
30     """
31     Given the filename, including md5 fragment, construct the
32     dependency link for PyPI.
33     """
34     root = 'https://files.pythonhosted.org/packages/source'
35     name, sep, rest = pkg_filename.partition('-')
36     parts = root, name[0], name, pkg_filename
37     return '/'.join(parts)
38 
39 
40 class install_with_pth(install):
41     """
42     Custom install command to install a .pth file for distutils patching.
43 
44     This hack is necessary because there's no standard way to install behavior
45     on startup (and it's debatable if there should be one). This hack (ab)uses
46     the `extra_path` behavior in Setuptools to install a `.pth` file with
47     implicit behavior on startup to give higher precedence to the local version
48     of `distutils` over the version from the standard library.
49 
50     Please do not replicate this behavior.
51     """
52 
53     _pth_name = 'distutils-precedence'
54     _pth_contents = textwrap.dedent("""
55         import os
56         var = 'SETUPTOOLS_USE_DISTUTILS'
57         enabled = os.environ.get(var, 'local') == 'local'
58         enabled and __import__('_distutils_hack').add_shim()
59         """).lstrip().replace('\n', '; ')
60 
61     def initialize_options(self):
62         install.initialize_options(self)
63         self.extra_path = self._pth_name, self._pth_contents
64 
65     def finalize_options(self):
66         install.finalize_options(self)
67         self._restore_install_lib()
68 
69     def _restore_install_lib(self):
70         """
71         Undo secondary effect of `extra_path` adding to `install_lib`
72         """
73         suffix = os.path.relpath(self.install_lib, self.install_libbase)
74 
75         if suffix.strip() == self._pth_contents.strip():
76             self.install_lib = self.install_libbase
77 
78 
79 setup_params = dict(
80     cmdclass={'install': install_with_pth},
81     package_data=package_data,
82 )
83 
84 if __name__ == '__main__':
85     # allow setup.py to run from another directory
86     here and os.chdir(here)
87     dist = setuptools.setup(**setup_params)
88
```
--- 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
@@ -3,6 +3,7 @@
 import re
 import importlib
 import warnings
+import contextlib
 
 
 is_pypy = '__pypy__' in sys.builtin_module_names
@@ -52,9 +53,8 @@
     # With the DistutilsMetaFinder in place,
     # perform an import to cause distutils to be
     # loaded from setuptools._distutils. Ref #2906.
-    add_shim()
-    importlib.import_module('distutils')
-    remove_shim()
+    with shim():
+        importlib.import_module('distutils')
 
     # check that submodules load as expected
     core = importlib.import_module('distutils.core')
@@ -129,6 +129,19 @@
 DISTUTILS_FINDER = DistutilsMetaFinder()
 
 
+def ensure_shim():
+    DISTUTILS_FINDER in sys.meta_path or add_shim()
+
+
+@contextlib.contextmanager
+def shim():
+    add_shim()
+    try:
+        yield
+    finally:
+        remove_shim()
+
+
 def add_shim():
     sys.meta_path.insert(0, DISTUTILS_FINDER)
 
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -55,7 +55,7 @@
         import os
         var = 'SETUPTOOLS_USE_DISTUTILS'
         enabled = os.environ.get(var, 'local') == 'local'
-        enabled and __import__('_distutils_hack').add_shim()
+        enabled and __import__('_distutils_hack').ensure_shim()
         """).lstrip().replace('\n', '; ')
 
     def initialize_options(self):

{"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@@ -3,6 +3,7 @@\n import re\n import importlib\n import warnings\n+import contextlib\n \n \n is_pypy = '__pypy__' in sys.builtin_module_names\n@@ -52,9 +53,8 @@\n     # With the DistutilsMetaFinder in place,\n     # perform an import to cause distutils to be\n     # loaded from setuptools._distutils. Ref #2906.\n-    add_shim()\n-    importlib.import_module('distutils')\n-    remove_shim()\n+    with shim():\n+        importlib.import_module('distutils')\n \n     # check that submodules load as expected\n     core = importlib.import_module('distutils.core')\n@@ -129,6 +129,19 @@\n DISTUTILS_FINDER = DistutilsMetaFinder()\n \n \n+def ensure_shim():\n+    DISTUTILS_FINDER in sys.meta_path or add_shim()\n+\n+\n+@contextlib.contextmanager\n+def shim():\n+    add_shim()\n+    try:\n+        yield\n+    finally:\n+        remove_shim()\n+\n+\n def add_shim():\n     sys.meta_path.insert(0, DISTUTILS_FINDER)\n \ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -55,7 +55,7 @@\n         import os\n         var = 'SETUPTOOLS_USE_DISTUTILS'\n         enabled = os.environ.get(var, 'local') == 'local'\n-        enabled and __import__('_distutils_hack').add_shim()\n+        enabled and __import__('_distutils_hack').ensure_shim()\n         \"\"\").lstrip().replace('\\n', '; ')\n \n     def initialize_options(self):\n", "issue": "[BUG] DistutilsMetaFinder appears multiple times on sys.meta_path\n### setuptools version\n\nsetuptools==60.0.4\n\n### Python version\n\npython3.8\n\n### OS\n\nAny\n\n### Additional environment information\n\nN/A\n\n### Description\n\nThe _DistutilsMetaFinder meta_path finder shim is installed multiple times, at least twice by `site.py` via the `.pth` shim, and once by `ensure_local_distutils` when `setuptools` is actually imported. It's unlikely to be a problem, especially since it's literally the same instance, but `add_shim` should be idempotent instead of blindly inserting the shim each time it's called. It also appears that the intent was to remove the shim entirely once distutils has been loaded, but since it's added more than once, the removal in the import leaves two references to it in `sys.meta_path` after setuptools has been imported.\n\n### Expected behavior\n\nAfter setuptools has been imported, the distutils shim finder is no longer on the meta path.\n\n### How to Reproduce\n\n(with setuptools>60 installed):\r\npython -c \"import sys; print(f'Before: {sys.meta_path}'); import setuptools; print(f'After: {sys.meta_path}')\"\r\n\n\n### Output\n\n```console\r\nBefore: [<_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_virtualenv._Finder object at 0x7fe4d2806f70>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>]\r\nAfter: [<_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_virtualenv._Finder object at 0x7fe4d2806f70>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>, <pkg_resources.extern.VendorImporter object at 0x7fe4d21c5460>, <setuptools.extern.VendorImporter object at 0x7fe4d1f2a100>]\r\n```\r\n\n\n### Code of Conduct\n\n- [X] I agree to follow the PSF Code of Conduct\n[BUG] DistutilsMetaFinder appears multiple times on sys.meta_path\n### setuptools version\n\nsetuptools==60.0.4\n\n### Python version\n\npython3.8\n\n### OS\n\nAny\n\n### Additional environment information\n\nN/A\n\n### Description\n\nThe _DistutilsMetaFinder meta_path finder shim is installed multiple times, at least twice by `site.py` via the `.pth` shim, and once by `ensure_local_distutils` when `setuptools` is actually imported. It's unlikely to be a problem, especially since it's literally the same instance, but `add_shim` should be idempotent instead of blindly inserting the shim each time it's called. It also appears that the intent was to remove the shim entirely once distutils has been loaded, but since it's added more than once, the removal in the import leaves two references to it in `sys.meta_path` after setuptools has been imported.\n\n### Expected behavior\n\nAfter setuptools has been imported, the distutils shim finder is no longer on the meta path.\n\n### How to Reproduce\n\n(with setuptools>60 installed):\r\npython -c \"import sys; print(f'Before: {sys.meta_path}'); import setuptools; print(f'After: {sys.meta_path}')\"\r\n\n\n### Output\n\n```console\r\nBefore: [<_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_virtualenv._Finder object at 0x7fe4d2806f70>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>]\r\nAfter: [<_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_distutils_hack.DistutilsMetaFinder object at 0x7fe4d2688700>, <_virtualenv._Finder object at 0x7fe4d2806f70>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>, <pkg_resources.extern.VendorImporter object at 0x7fe4d21c5460>, <setuptools.extern.VendorImporter object at 0x7fe4d1f2a100>]\r\n```\r\n\n\n### Code of Conduct\n\n- [X] I agree to follow the PSF Code of Conduct\n", "before_files": [{"content": "import sys\nimport os\nimport re\nimport importlib\nimport warnings\n\n\nis_pypy = '__pypy__' in sys.builtin_module_names\n\n\nwarnings.filterwarnings('ignore',\n                        r'.+ distutils\\b.+ deprecated',\n                        DeprecationWarning)\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    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    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [name for name in sys.modules if re.match(r'distutils\\b', name)]\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    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    add_shim()\n    importlib.import_module('distutils')\n    remove_shim()\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 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.abc\n        import importlib.util\n\n        class DistutilsLoader(importlib.abc.Loader):\n\n            def create_module(self, spec):\n                return importlib.import_module('setuptools._distutils')\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader('distutils', DistutilsLoader())\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    @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 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    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"}, {"content": "#!/usr/bin/env python\n\nimport os\nimport sys\nimport textwrap\n\nimport setuptools\nfrom setuptools.command.install import install\n\nhere = os.path.dirname(__file__)\n\n\npackage_data = dict(\n    setuptools=['script (dev).tmpl', 'script.tmpl', 'site-patch.py'],\n)\n\nforce_windows_specific_files = (\n    os.environ.get(\"SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES\", \"1\").lower()\n    not in (\"\", \"0\", \"false\", \"no\")\n)\n\ninclude_windows_files = sys.platform == 'win32' or force_windows_specific_files\n\nif include_windows_files:\n    package_data.setdefault('setuptools', []).extend(['*.exe'])\n    package_data.setdefault('setuptools.command', []).extend(['*.xml'])\n\n\ndef pypi_link(pkg_filename):\n    \"\"\"\n    Given the filename, including md5 fragment, construct the\n    dependency link for PyPI.\n    \"\"\"\n    root = 'https://files.pythonhosted.org/packages/source'\n    name, sep, rest = pkg_filename.partition('-')\n    parts = root, name[0], name, pkg_filename\n    return '/'.join(parts)\n\n\nclass install_with_pth(install):\n    \"\"\"\n    Custom install command to install a .pth file for distutils patching.\n\n    This hack is necessary because there's no standard way to install behavior\n    on startup (and it's debatable if there should be one). This hack (ab)uses\n    the `extra_path` behavior in Setuptools to install a `.pth` file with\n    implicit behavior on startup to give higher precedence to the local version\n    of `distutils` over the version from the standard library.\n\n    Please do not replicate this behavior.\n    \"\"\"\n\n    _pth_name = 'distutils-precedence'\n    _pth_contents = textwrap.dedent(\"\"\"\n        import os\n        var = 'SETUPTOOLS_USE_DISTUTILS'\n        enabled = os.environ.get(var, 'local') == 'local'\n        enabled and __import__('_distutils_hack').add_shim()\n        \"\"\").lstrip().replace('\\n', '; ')\n\n    def initialize_options(self):\n        install.initialize_options(self)\n        self.extra_path = self._pth_name, self._pth_contents\n\n    def finalize_options(self):\n        install.finalize_options(self)\n        self._restore_install_lib()\n\n    def _restore_install_lib(self):\n        \"\"\"\n        Undo secondary effect of `extra_path` adding to `install_lib`\n        \"\"\"\n        suffix = os.path.relpath(self.install_lib, self.install_libbase)\n\n        if suffix.strip() == self._pth_contents.strip():\n            self.install_lib = self.install_libbase\n\n\nsetup_params = dict(\n    cmdclass={'install': install_with_pth},\n    package_data=package_data,\n)\n\nif __name__ == '__main__':\n    # allow setup.py to run from another directory\n    here and os.chdir(here)\n    dist = setuptools.setup(**setup_params)\n", "path": "setup.py"}], "after_files": [{"content": "import sys\nimport os\nimport re\nimport importlib\nimport warnings\nimport contextlib\n\n\nis_pypy = '__pypy__' in sys.builtin_module_names\n\n\nwarnings.filterwarnings('ignore',\n                        r'.+ distutils\\b.+ deprecated',\n                        DeprecationWarning)\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    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    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [name for name in sys.modules if re.match(r'distutils\\b', name)]\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    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 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.abc\n        import importlib.util\n\n        class DistutilsLoader(importlib.abc.Loader):\n\n            def create_module(self, spec):\n                return importlib.import_module('setuptools._distutils')\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader('distutils', DistutilsLoader())\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    @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 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 ensure_shim():\n    DISTUTILS_FINDER in sys.meta_path or add_shim()\n\n\n@contextlib.contextmanager\ndef shim():\n    add_shim()\n    try:\n        yield\n    finally:\n        remove_shim()\n\n\ndef add_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"}, {"content": "#!/usr/bin/env python\n\nimport os\nimport sys\nimport textwrap\n\nimport setuptools\nfrom setuptools.command.install import install\n\nhere = os.path.dirname(__file__)\n\n\npackage_data = dict(\n    setuptools=['script (dev).tmpl', 'script.tmpl', 'site-patch.py'],\n)\n\nforce_windows_specific_files = (\n    os.environ.get(\"SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES\", \"1\").lower()\n    not in (\"\", \"0\", \"false\", \"no\")\n)\n\ninclude_windows_files = sys.platform == 'win32' or force_windows_specific_files\n\nif include_windows_files:\n    package_data.setdefault('setuptools', []).extend(['*.exe'])\n    package_data.setdefault('setuptools.command', []).extend(['*.xml'])\n\n\ndef pypi_link(pkg_filename):\n    \"\"\"\n    Given the filename, including md5 fragment, construct the\n    dependency link for PyPI.\n    \"\"\"\n    root = 'https://files.pythonhosted.org/packages/source'\n    name, sep, rest = pkg_filename.partition('-')\n    parts = root, name[0], name, pkg_filename\n    return '/'.join(parts)\n\n\nclass install_with_pth(install):\n    \"\"\"\n    Custom install command to install a .pth file for distutils patching.\n\n    This hack is necessary because there's no standard way to install behavior\n    on startup (and it's debatable if there should be one). This hack (ab)uses\n    the `extra_path` behavior in Setuptools to install a `.pth` file with\n    implicit behavior on startup to give higher precedence to the local version\n    of `distutils` over the version from the standard library.\n\n    Please do not replicate this behavior.\n    \"\"\"\n\n    _pth_name = 'distutils-precedence'\n    _pth_contents = textwrap.dedent(\"\"\"\n        import os\n        var = 'SETUPTOOLS_USE_DISTUTILS'\n        enabled = os.environ.get(var, 'local') == 'local'\n        enabled and __import__('_distutils_hack').ensure_shim()\n        \"\"\").lstrip().replace('\\n', '; ')\n\n    def initialize_options(self):\n        install.initialize_options(self)\n        self.extra_path = self._pth_name, self._pth_contents\n\n    def finalize_options(self):\n        install.finalize_options(self)\n        self._restore_install_lib()\n\n    def _restore_install_lib(self):\n        \"\"\"\n        Undo secondary effect of `extra_path` adding to `install_lib`\n        \"\"\"\n        suffix = os.path.relpath(self.install_lib, self.install_libbase)\n\n        if suffix.strip() == self._pth_contents.strip():\n            self.install_lib = self.install_libbase\n\n\nsetup_params = dict(\n    cmdclass={'install': install_with_pth},\n    package_data=package_data,\n)\n\nif __name__ == '__main__':\n    # allow setup.py to run from another directory\n    here and os.chdir(here)\n    dist = setuptools.setup(**setup_params)\n", "path": "setup.py"}]}