We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Plugins using setuptools entry points resolve to system and not setup_requires
Assume that you have e.g. setuptools_scm 3 installed system-wide, and try to to run the following setup.py:
```python
from setuptools import setup
setup(name="foo", setup_requires=["setuptools_scm>=4"])
```
you get the warning
```
/usr/lib/python3.8/site-packages/setuptools/dist.py:701: UserWarning: Module setuptools_scm was already imported from /usr/lib/python3.8/site-packages/setuptools_scm/__init__.py, but /tmp/foo/.eggs/setuptools_scm-4.1.1-py3.8.egg is being added to sys.path
```
(i.e. the system-wide setuptools_scm was loaded, even though it is too old).  One can confirm that the "correct" newer setuptools_scm indeed doesn't get used by changing setup.py to
```python
from setuptools import setup
setup(name="foo",
      setup_requires=["setuptools_scm>=4"],
      use_scm_version={"parentdir_prefix_version": "foo-"})
```
in which case one gets the same warning and then a traceback
```
TypeError: __init__() got an unexpected keyword argument 'parentdir_prefix_version'
```

I guess a solution may be e.g. to move the entry point (which is what gets eagerly loaded by setuptools) to a separate package (let's say `_setuptools_scm_helper`) which itself imports setuptools_scm only when actually needed with a pass-through shim so that setuptools only imports `_setuptools_scm_helper` and then the correct version of setuptools_scm can be loaded when needed.
Plugins using setuptools entry points resolve to system and not setup_requires
Assume that you have e.g. setuptools_scm 3 installed system-wide, and try to to run the following setup.py:
```python
from setuptools import setup
setup(name="foo", setup_requires=["setuptools_scm>=4"])
```
you get the warning
```
/usr/lib/python3.8/site-packages/setuptools/dist.py:701: UserWarning: Module setuptools_scm was already imported from /usr/lib/python3.8/site-packages/setuptools_scm/__init__.py, but /tmp/foo/.eggs/setuptools_scm-4.1.1-py3.8.egg is being added to sys.path
```
(i.e. the system-wide setuptools_scm was loaded, even though it is too old).  One can confirm that the "correct" newer setuptools_scm indeed doesn't get used by changing setup.py to
```python
from setuptools import setup
setup(name="foo",
      setup_requires=["setuptools_scm>=4"],
      use_scm_version={"parentdir_prefix_version": "foo-"})
```
in which case one gets the same warning and then a traceback
```
TypeError: __init__() got an unexpected keyword argument 'parentdir_prefix_version'
```

I guess a solution may be e.g. to move the entry point (which is what gets eagerly loaded by setuptools) to a separate package (let's say `_setuptools_scm_helper`) which itself imports setuptools_scm only when actually needed with a pass-through shim so that setuptools only imports `_setuptools_scm_helper` and then the correct version of setuptools_scm can be loaded when needed.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `setuptools/__init__.py`
Content:
```
1 """Extensions to the 'distutils' for large or complex distributions"""
2 
3 import os
4 import sys
5 import functools
6 import distutils.core
7 import distutils.filelist
8 import re
9 from distutils.errors import DistutilsOptionError
10 from distutils.util import convert_path
11 from fnmatch import fnmatchcase
12 
13 from ._deprecation_warning import SetuptoolsDeprecationWarning
14 
15 from setuptools.extern.six import PY3, string_types
16 from setuptools.extern.six.moves import filter, map
17 
18 import setuptools.version
19 from setuptools.extension import Extension
20 from setuptools.dist import Distribution, Feature
21 from setuptools.depends import Require
22 from . import monkey
23 
24 __metaclass__ = type
25 
26 
27 __all__ = [
28     'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require',
29     'SetuptoolsDeprecationWarning',
30     'find_packages'
31 ]
32 
33 if PY3:
34   __all__.append('find_namespace_packages')
35 
36 __version__ = setuptools.version.__version__
37 
38 bootstrap_install_from = None
39 
40 # If we run 2to3 on .py files, should we also convert docstrings?
41 # Default: yes; assume that we can detect doctests reliably
42 run_2to3_on_doctests = True
43 # Standard package names for fixer packages
44 lib2to3_fixer_packages = ['lib2to3.fixes']
45 
46 
47 class PackageFinder:
48     """
49     Generate a list of all Python packages found within a directory
50     """
51 
52     @classmethod
53     def find(cls, where='.', exclude=(), include=('*',)):
54         """Return a list all Python packages found within directory 'where'
55 
56         'where' is the root directory which will be searched for packages.  It
57         should be supplied as a "cross-platform" (i.e. URL-style) path; it will
58         be converted to the appropriate local path syntax.
59 
60         'exclude' is a sequence of package names to exclude; '*' can be used
61         as a wildcard in the names, such that 'foo.*' will exclude all
62         subpackages of 'foo' (but not 'foo' itself).
63 
64         'include' is a sequence of package names to include.  If it's
65         specified, only the named packages will be included.  If it's not
66         specified, all found packages will be included.  'include' can contain
67         shell style wildcard patterns just like 'exclude'.
68         """
69 
70         return list(cls._find_packages_iter(
71             convert_path(where),
72             cls._build_filter('ez_setup', '*__pycache__', *exclude),
73             cls._build_filter(*include)))
74 
75     @classmethod
76     def _find_packages_iter(cls, where, exclude, include):
77         """
78         All the packages found in 'where' that pass the 'include' filter, but
79         not the 'exclude' filter.
80         """
81         for root, dirs, files in os.walk(where, followlinks=True):
82             # Copy dirs to iterate over it, then empty dirs.
83             all_dirs = dirs[:]
84             dirs[:] = []
85 
86             for dir in all_dirs:
87                 full_path = os.path.join(root, dir)
88                 rel_path = os.path.relpath(full_path, where)
89                 package = rel_path.replace(os.path.sep, '.')
90 
91                 # Skip directory trees that are not valid packages
92                 if ('.' in dir or not cls._looks_like_package(full_path)):
93                     continue
94 
95                 # Should this package be included?
96                 if include(package) and not exclude(package):
97                     yield package
98 
99                 # Keep searching subdirectories, as there may be more packages
100                 # down there, even if the parent was excluded.
101                 dirs.append(dir)
102 
103     @staticmethod
104     def _looks_like_package(path):
105         """Does a directory look like a package?"""
106         return os.path.isfile(os.path.join(path, '__init__.py'))
107 
108     @staticmethod
109     def _build_filter(*patterns):
110         """
111         Given a list of patterns, return a callable that will be true only if
112         the input matches at least one of the patterns.
113         """
114         return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
115 
116 
117 class PEP420PackageFinder(PackageFinder):
118     @staticmethod
119     def _looks_like_package(path):
120         return True
121 
122 
123 find_packages = PackageFinder.find
124 
125 if PY3:
126   find_namespace_packages = PEP420PackageFinder.find
127 
128 
129 def _install_setup_requires(attrs):
130     # Note: do not use `setuptools.Distribution` directly, as
131     # our PEP 517 backend patch `distutils.core.Distribution`.
132     dist = distutils.core.Distribution(dict(
133         (k, v) for k, v in attrs.items()
134         if k in ('dependency_links', 'setup_requires')
135     ))
136     # Honor setup.cfg's options.
137     dist.parse_config_files(ignore_option_errors=True)
138     if dist.setup_requires:
139         dist.fetch_build_eggs(dist.setup_requires)
140 
141 
142 def setup(**attrs):
143     # Make sure we have any requirements needed to interpret 'attrs'.
144     _install_setup_requires(attrs)
145     return distutils.core.setup(**attrs)
146 
147 setup.__doc__ = distutils.core.setup.__doc__
148 
149 
150 _Command = monkey.get_unpatched(distutils.core.Command)
151 
152 
153 class Command(_Command):
154     __doc__ = _Command.__doc__
155 
156     command_consumes_arguments = False
157 
158     def __init__(self, dist, **kw):
159         """
160         Construct the command for dist, updating
161         vars(self) with any keyword parameters.
162         """
163         _Command.__init__(self, dist)
164         vars(self).update(kw)
165 
166     def _ensure_stringlike(self, option, what, default=None):
167         val = getattr(self, option)
168         if val is None:
169             setattr(self, option, default)
170             return default
171         elif not isinstance(val, string_types):
172             raise DistutilsOptionError("'%s' must be a %s (got `%s`)"
173                                        % (option, what, val))
174         return val
175 
176     def ensure_string_list(self, option):
177         r"""Ensure that 'option' is a list of strings.  If 'option' is
178         currently a string, we split it either on /,\s*/ or /\s+/, so
179         "foo bar baz", "foo,bar,baz", and "foo,   bar baz" all become
180         ["foo", "bar", "baz"].
181         """
182         val = getattr(self, option)
183         if val is None:
184             return
185         elif isinstance(val, string_types):
186             setattr(self, option, re.split(r',\s*|\s+', val))
187         else:
188             if isinstance(val, list):
189                 ok = all(isinstance(v, string_types) for v in val)
190             else:
191                 ok = False
192             if not ok:
193                 raise DistutilsOptionError(
194                       "'%s' must be a list of strings (got %r)"
195                       % (option, val))
196 
197     def reinitialize_command(self, command, reinit_subcommands=0, **kw):
198         cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
199         vars(cmd).update(kw)
200         return cmd
201 
202 
203 def _find_all_simple(path):
204     """
205     Find all files under 'path'
206     """
207     results = (
208         os.path.join(base, file)
209         for base, dirs, files in os.walk(path, followlinks=True)
210         for file in files
211     )
212     return filter(os.path.isfile, results)
213 
214 
215 def findall(dir=os.curdir):
216     """
217     Find all files under 'dir' and return the list of full filenames.
218     Unless dir is '.', return full filenames with dir prepended.
219     """
220     files = _find_all_simple(dir)
221     if dir == os.curdir:
222         make_rel = functools.partial(os.path.relpath, start=dir)
223         files = map(make_rel, files)
224     return list(files)
225 
226 
227 # Apply monkey patches
228 monkey.patch_all()
229
```
--- 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/setuptools/__init__.py b/setuptools/__init__.py
--- a/setuptools/__init__.py
+++ b/setuptools/__init__.py
@@ -129,10 +129,27 @@
 def _install_setup_requires(attrs):
     # Note: do not use `setuptools.Distribution` directly, as
     # our PEP 517 backend patch `distutils.core.Distribution`.
-    dist = distutils.core.Distribution(dict(
-        (k, v) for k, v in attrs.items()
-        if k in ('dependency_links', 'setup_requires')
-    ))
+    class MinimalDistribution(distutils.core.Distribution):
+        """
+        A minimal version of a distribution for supporting the
+        fetch_build_eggs interface.
+        """
+        def __init__(self, attrs):
+            _incl = 'dependency_links', 'setup_requires'
+            filtered = {
+                k: attrs[k]
+                for k in set(_incl) & set(attrs)
+            }
+            distutils.core.Distribution.__init__(self, filtered)
+
+        def finalize_options(self):
+            """
+            Disable finalize_options to avoid building the working set.
+            Ref #2158.
+            """
+
+    dist = MinimalDistribution(attrs)
+
     # Honor setup.cfg's options.
     dist.parse_config_files(ignore_option_errors=True)
     if dist.setup_requires:

{"golden_diff": "diff --git a/setuptools/__init__.py b/setuptools/__init__.py\n--- a/setuptools/__init__.py\n+++ b/setuptools/__init__.py\n@@ -129,10 +129,27 @@\n def _install_setup_requires(attrs):\n     # Note: do not use `setuptools.Distribution` directly, as\n     # our PEP 517 backend patch `distutils.core.Distribution`.\n-    dist = distutils.core.Distribution(dict(\n-        (k, v) for k, v in attrs.items()\n-        if k in ('dependency_links', 'setup_requires')\n-    ))\n+    class MinimalDistribution(distutils.core.Distribution):\n+        \"\"\"\n+        A minimal version of a distribution for supporting the\n+        fetch_build_eggs interface.\n+        \"\"\"\n+        def __init__(self, attrs):\n+            _incl = 'dependency_links', 'setup_requires'\n+            filtered = {\n+                k: attrs[k]\n+                for k in set(_incl) & set(attrs)\n+            }\n+            distutils.core.Distribution.__init__(self, filtered)\n+\n+        def finalize_options(self):\n+            \"\"\"\n+            Disable finalize_options to avoid building the working set.\n+            Ref #2158.\n+            \"\"\"\n+\n+    dist = MinimalDistribution(attrs)\n+\n     # Honor setup.cfg's options.\n     dist.parse_config_files(ignore_option_errors=True)\n     if dist.setup_requires:\n", "issue": "Plugins using setuptools entry points resolve to system and not setup_requires\nAssume that you have e.g. setuptools_scm 3 installed system-wide, and try to to run the following setup.py:\r\n```python\r\nfrom setuptools import setup\r\nsetup(name=\"foo\", setup_requires=[\"setuptools_scm>=4\"])\r\n```\r\nyou get the warning\r\n```\r\n/usr/lib/python3.8/site-packages/setuptools/dist.py:701: UserWarning: Module setuptools_scm was already imported from /usr/lib/python3.8/site-packages/setuptools_scm/__init__.py, but /tmp/foo/.eggs/setuptools_scm-4.1.1-py3.8.egg is being added to sys.path\r\n```\r\n(i.e. the system-wide setuptools_scm was loaded, even though it is too old).  One can confirm that the \"correct\" newer setuptools_scm indeed doesn't get used by changing setup.py to\r\n```python\r\nfrom setuptools import setup\r\nsetup(name=\"foo\",\r\n      setup_requires=[\"setuptools_scm>=4\"],\r\n      use_scm_version={\"parentdir_prefix_version\": \"foo-\"})\r\n```\r\nin which case one gets the same warning and then a traceback\r\n```\r\nTypeError: __init__() got an unexpected keyword argument 'parentdir_prefix_version'\r\n```\r\n\r\nI guess a solution may be e.g. to move the entry point (which is what gets eagerly loaded by setuptools) to a separate package (let's say `_setuptools_scm_helper`) which itself imports setuptools_scm only when actually needed with a pass-through shim so that setuptools only imports `_setuptools_scm_helper` and then the correct version of setuptools_scm can be loaded when needed.\nPlugins using setuptools entry points resolve to system and not setup_requires\nAssume that you have e.g. setuptools_scm 3 installed system-wide, and try to to run the following setup.py:\r\n```python\r\nfrom setuptools import setup\r\nsetup(name=\"foo\", setup_requires=[\"setuptools_scm>=4\"])\r\n```\r\nyou get the warning\r\n```\r\n/usr/lib/python3.8/site-packages/setuptools/dist.py:701: UserWarning: Module setuptools_scm was already imported from /usr/lib/python3.8/site-packages/setuptools_scm/__init__.py, but /tmp/foo/.eggs/setuptools_scm-4.1.1-py3.8.egg is being added to sys.path\r\n```\r\n(i.e. the system-wide setuptools_scm was loaded, even though it is too old).  One can confirm that the \"correct\" newer setuptools_scm indeed doesn't get used by changing setup.py to\r\n```python\r\nfrom setuptools import setup\r\nsetup(name=\"foo\",\r\n      setup_requires=[\"setuptools_scm>=4\"],\r\n      use_scm_version={\"parentdir_prefix_version\": \"foo-\"})\r\n```\r\nin which case one gets the same warning and then a traceback\r\n```\r\nTypeError: __init__() got an unexpected keyword argument 'parentdir_prefix_version'\r\n```\r\n\r\nI guess a solution may be e.g. to move the entry point (which is what gets eagerly loaded by setuptools) to a separate package (let's say `_setuptools_scm_helper`) which itself imports setuptools_scm only when actually needed with a pass-through shim so that setuptools only imports `_setuptools_scm_helper` and then the correct version of setuptools_scm can be loaded when needed.\n", "before_files": [{"content": "\"\"\"Extensions to the 'distutils' for large or complex distributions\"\"\"\n\nimport os\nimport sys\nimport functools\nimport distutils.core\nimport distutils.filelist\nimport re\nfrom distutils.errors import DistutilsOptionError\nfrom distutils.util import convert_path\nfrom fnmatch import fnmatchcase\n\nfrom ._deprecation_warning import SetuptoolsDeprecationWarning\n\nfrom setuptools.extern.six import PY3, string_types\nfrom setuptools.extern.six.moves import filter, map\n\nimport setuptools.version\nfrom setuptools.extension import Extension\nfrom setuptools.dist import Distribution, Feature\nfrom setuptools.depends import Require\nfrom . import monkey\n\n__metaclass__ = type\n\n\n__all__ = [\n    'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require',\n    'SetuptoolsDeprecationWarning',\n    'find_packages'\n]\n\nif PY3:\n  __all__.append('find_namespace_packages')\n\n__version__ = setuptools.version.__version__\n\nbootstrap_install_from = None\n\n# If we run 2to3 on .py files, should we also convert docstrings?\n# Default: yes; assume that we can detect doctests reliably\nrun_2to3_on_doctests = True\n# Standard package names for fixer packages\nlib2to3_fixer_packages = ['lib2to3.fixes']\n\n\nclass PackageFinder:\n    \"\"\"\n    Generate a list of all Python packages found within a directory\n    \"\"\"\n\n    @classmethod\n    def find(cls, where='.', exclude=(), include=('*',)):\n        \"\"\"Return a list all Python packages found within directory 'where'\n\n        'where' is the root directory which will be searched for packages.  It\n        should be supplied as a \"cross-platform\" (i.e. URL-style) path; it will\n        be converted to the appropriate local path syntax.\n\n        'exclude' is a sequence of package names to exclude; '*' can be used\n        as a wildcard in the names, such that 'foo.*' will exclude all\n        subpackages of 'foo' (but not 'foo' itself).\n\n        'include' is a sequence of package names to include.  If it's\n        specified, only the named packages will be included.  If it's not\n        specified, all found packages will be included.  'include' can contain\n        shell style wildcard patterns just like 'exclude'.\n        \"\"\"\n\n        return list(cls._find_packages_iter(\n            convert_path(where),\n            cls._build_filter('ez_setup', '*__pycache__', *exclude),\n            cls._build_filter(*include)))\n\n    @classmethod\n    def _find_packages_iter(cls, where, exclude, include):\n        \"\"\"\n        All the packages found in 'where' that pass the 'include' filter, but\n        not the 'exclude' filter.\n        \"\"\"\n        for root, dirs, files in os.walk(where, followlinks=True):\n            # Copy dirs to iterate over it, then empty dirs.\n            all_dirs = dirs[:]\n            dirs[:] = []\n\n            for dir in all_dirs:\n                full_path = os.path.join(root, dir)\n                rel_path = os.path.relpath(full_path, where)\n                package = rel_path.replace(os.path.sep, '.')\n\n                # Skip directory trees that are not valid packages\n                if ('.' in dir or not cls._looks_like_package(full_path)):\n                    continue\n\n                # Should this package be included?\n                if include(package) and not exclude(package):\n                    yield package\n\n                # Keep searching subdirectories, as there may be more packages\n                # down there, even if the parent was excluded.\n                dirs.append(dir)\n\n    @staticmethod\n    def _looks_like_package(path):\n        \"\"\"Does a directory look like a package?\"\"\"\n        return os.path.isfile(os.path.join(path, '__init__.py'))\n\n    @staticmethod\n    def _build_filter(*patterns):\n        \"\"\"\n        Given a list of patterns, return a callable that will be true only if\n        the input matches at least one of the patterns.\n        \"\"\"\n        return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)\n\n\nclass PEP420PackageFinder(PackageFinder):\n    @staticmethod\n    def _looks_like_package(path):\n        return True\n\n\nfind_packages = PackageFinder.find\n\nif PY3:\n  find_namespace_packages = PEP420PackageFinder.find\n\n\ndef _install_setup_requires(attrs):\n    # Note: do not use `setuptools.Distribution` directly, as\n    # our PEP 517 backend patch `distutils.core.Distribution`.\n    dist = distutils.core.Distribution(dict(\n        (k, v) for k, v in attrs.items()\n        if k in ('dependency_links', 'setup_requires')\n    ))\n    # Honor setup.cfg's options.\n    dist.parse_config_files(ignore_option_errors=True)\n    if dist.setup_requires:\n        dist.fetch_build_eggs(dist.setup_requires)\n\n\ndef setup(**attrs):\n    # Make sure we have any requirements needed to interpret 'attrs'.\n    _install_setup_requires(attrs)\n    return distutils.core.setup(**attrs)\n\nsetup.__doc__ = distutils.core.setup.__doc__\n\n\n_Command = monkey.get_unpatched(distutils.core.Command)\n\n\nclass Command(_Command):\n    __doc__ = _Command.__doc__\n\n    command_consumes_arguments = False\n\n    def __init__(self, dist, **kw):\n        \"\"\"\n        Construct the command for dist, updating\n        vars(self) with any keyword parameters.\n        \"\"\"\n        _Command.__init__(self, dist)\n        vars(self).update(kw)\n\n    def _ensure_stringlike(self, option, what, default=None):\n        val = getattr(self, option)\n        if val is None:\n            setattr(self, option, default)\n            return default\n        elif not isinstance(val, string_types):\n            raise DistutilsOptionError(\"'%s' must be a %s (got `%s`)\"\n                                       % (option, what, val))\n        return val\n\n    def ensure_string_list(self, option):\n        r\"\"\"Ensure that 'option' is a list of strings.  If 'option' is\n        currently a string, we split it either on /,\\s*/ or /\\s+/, so\n        \"foo bar baz\", \"foo,bar,baz\", and \"foo,   bar baz\" all become\n        [\"foo\", \"bar\", \"baz\"].\n        \"\"\"\n        val = getattr(self, option)\n        if val is None:\n            return\n        elif isinstance(val, string_types):\n            setattr(self, option, re.split(r',\\s*|\\s+', val))\n        else:\n            if isinstance(val, list):\n                ok = all(isinstance(v, string_types) for v in val)\n            else:\n                ok = False\n            if not ok:\n                raise DistutilsOptionError(\n                      \"'%s' must be a list of strings (got %r)\"\n                      % (option, val))\n\n    def reinitialize_command(self, command, reinit_subcommands=0, **kw):\n        cmd = _Command.reinitialize_command(self, command, reinit_subcommands)\n        vars(cmd).update(kw)\n        return cmd\n\n\ndef _find_all_simple(path):\n    \"\"\"\n    Find all files under 'path'\n    \"\"\"\n    results = (\n        os.path.join(base, file)\n        for base, dirs, files in os.walk(path, followlinks=True)\n        for file in files\n    )\n    return filter(os.path.isfile, results)\n\n\ndef findall(dir=os.curdir):\n    \"\"\"\n    Find all files under 'dir' and return the list of full filenames.\n    Unless dir is '.', return full filenames with dir prepended.\n    \"\"\"\n    files = _find_all_simple(dir)\n    if dir == os.curdir:\n        make_rel = functools.partial(os.path.relpath, start=dir)\n        files = map(make_rel, files)\n    return list(files)\n\n\n# Apply monkey patches\nmonkey.patch_all()\n", "path": "setuptools/__init__.py"}], "after_files": [{"content": "\"\"\"Extensions to the 'distutils' for large or complex distributions\"\"\"\n\nimport os\nimport sys\nimport functools\nimport distutils.core\nimport distutils.filelist\nimport re\nfrom distutils.errors import DistutilsOptionError\nfrom distutils.util import convert_path\nfrom fnmatch import fnmatchcase\n\nfrom ._deprecation_warning import SetuptoolsDeprecationWarning\n\nfrom setuptools.extern.six import PY3, string_types\nfrom setuptools.extern.six.moves import filter, map\n\nimport setuptools.version\nfrom setuptools.extension import Extension\nfrom setuptools.dist import Distribution, Feature\nfrom setuptools.depends import Require\nfrom . import monkey\n\n__metaclass__ = type\n\n\n__all__ = [\n    'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require',\n    'SetuptoolsDeprecationWarning',\n    'find_packages'\n]\n\nif PY3:\n  __all__.append('find_namespace_packages')\n\n__version__ = setuptools.version.__version__\n\nbootstrap_install_from = None\n\n# If we run 2to3 on .py files, should we also convert docstrings?\n# Default: yes; assume that we can detect doctests reliably\nrun_2to3_on_doctests = True\n# Standard package names for fixer packages\nlib2to3_fixer_packages = ['lib2to3.fixes']\n\n\nclass PackageFinder:\n    \"\"\"\n    Generate a list of all Python packages found within a directory\n    \"\"\"\n\n    @classmethod\n    def find(cls, where='.', exclude=(), include=('*',)):\n        \"\"\"Return a list all Python packages found within directory 'where'\n\n        'where' is the root directory which will be searched for packages.  It\n        should be supplied as a \"cross-platform\" (i.e. URL-style) path; it will\n        be converted to the appropriate local path syntax.\n\n        'exclude' is a sequence of package names to exclude; '*' can be used\n        as a wildcard in the names, such that 'foo.*' will exclude all\n        subpackages of 'foo' (but not 'foo' itself).\n\n        'include' is a sequence of package names to include.  If it's\n        specified, only the named packages will be included.  If it's not\n        specified, all found packages will be included.  'include' can contain\n        shell style wildcard patterns just like 'exclude'.\n        \"\"\"\n\n        return list(cls._find_packages_iter(\n            convert_path(where),\n            cls._build_filter('ez_setup', '*__pycache__', *exclude),\n            cls._build_filter(*include)))\n\n    @classmethod\n    def _find_packages_iter(cls, where, exclude, include):\n        \"\"\"\n        All the packages found in 'where' that pass the 'include' filter, but\n        not the 'exclude' filter.\n        \"\"\"\n        for root, dirs, files in os.walk(where, followlinks=True):\n            # Copy dirs to iterate over it, then empty dirs.\n            all_dirs = dirs[:]\n            dirs[:] = []\n\n            for dir in all_dirs:\n                full_path = os.path.join(root, dir)\n                rel_path = os.path.relpath(full_path, where)\n                package = rel_path.replace(os.path.sep, '.')\n\n                # Skip directory trees that are not valid packages\n                if ('.' in dir or not cls._looks_like_package(full_path)):\n                    continue\n\n                # Should this package be included?\n                if include(package) and not exclude(package):\n                    yield package\n\n                # Keep searching subdirectories, as there may be more packages\n                # down there, even if the parent was excluded.\n                dirs.append(dir)\n\n    @staticmethod\n    def _looks_like_package(path):\n        \"\"\"Does a directory look like a package?\"\"\"\n        return os.path.isfile(os.path.join(path, '__init__.py'))\n\n    @staticmethod\n    def _build_filter(*patterns):\n        \"\"\"\n        Given a list of patterns, return a callable that will be true only if\n        the input matches at least one of the patterns.\n        \"\"\"\n        return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)\n\n\nclass PEP420PackageFinder(PackageFinder):\n    @staticmethod\n    def _looks_like_package(path):\n        return True\n\n\nfind_packages = PackageFinder.find\n\nif PY3:\n  find_namespace_packages = PEP420PackageFinder.find\n\n\ndef _install_setup_requires(attrs):\n    # Note: do not use `setuptools.Distribution` directly, as\n    # our PEP 517 backend patch `distutils.core.Distribution`.\n    class MinimalDistribution(distutils.core.Distribution):\n        \"\"\"\n        A minimal version of a distribution for supporting the\n        fetch_build_eggs interface.\n        \"\"\"\n        def __init__(self, attrs):\n            _incl = 'dependency_links', 'setup_requires'\n            filtered = {\n                k: attrs[k]\n                for k in set(_incl) & set(attrs)\n            }\n            distutils.core.Distribution.__init__(self, filtered)\n\n        def finalize_options(self):\n            \"\"\"\n            Disable finalize_options to avoid building the working set.\n            Ref #2158.\n            \"\"\"\n\n    dist = MinimalDistribution(attrs)\n\n    # Honor setup.cfg's options.\n    dist.parse_config_files(ignore_option_errors=True)\n    if dist.setup_requires:\n        dist.fetch_build_eggs(dist.setup_requires)\n\n\ndef setup(**attrs):\n    # Make sure we have any requirements needed to interpret 'attrs'.\n    _install_setup_requires(attrs)\n    return distutils.core.setup(**attrs)\n\nsetup.__doc__ = distutils.core.setup.__doc__\n\n\n_Command = monkey.get_unpatched(distutils.core.Command)\n\n\nclass Command(_Command):\n    __doc__ = _Command.__doc__\n\n    command_consumes_arguments = False\n\n    def __init__(self, dist, **kw):\n        \"\"\"\n        Construct the command for dist, updating\n        vars(self) with any keyword parameters.\n        \"\"\"\n        _Command.__init__(self, dist)\n        vars(self).update(kw)\n\n    def _ensure_stringlike(self, option, what, default=None):\n        val = getattr(self, option)\n        if val is None:\n            setattr(self, option, default)\n            return default\n        elif not isinstance(val, string_types):\n            raise DistutilsOptionError(\"'%s' must be a %s (got `%s`)\"\n                                       % (option, what, val))\n        return val\n\n    def ensure_string_list(self, option):\n        r\"\"\"Ensure that 'option' is a list of strings.  If 'option' is\n        currently a string, we split it either on /,\\s*/ or /\\s+/, so\n        \"foo bar baz\", \"foo,bar,baz\", and \"foo,   bar baz\" all become\n        [\"foo\", \"bar\", \"baz\"].\n        \"\"\"\n        val = getattr(self, option)\n        if val is None:\n            return\n        elif isinstance(val, string_types):\n            setattr(self, option, re.split(r',\\s*|\\s+', val))\n        else:\n            if isinstance(val, list):\n                ok = all(isinstance(v, string_types) for v in val)\n            else:\n                ok = False\n            if not ok:\n                raise DistutilsOptionError(\n                      \"'%s' must be a list of strings (got %r)\"\n                      % (option, val))\n\n    def reinitialize_command(self, command, reinit_subcommands=0, **kw):\n        cmd = _Command.reinitialize_command(self, command, reinit_subcommands)\n        vars(cmd).update(kw)\n        return cmd\n\n\ndef _find_all_simple(path):\n    \"\"\"\n    Find all files under 'path'\n    \"\"\"\n    results = (\n        os.path.join(base, file)\n        for base, dirs, files in os.walk(path, followlinks=True)\n        for file in files\n    )\n    return filter(os.path.isfile, results)\n\n\ndef findall(dir=os.curdir):\n    \"\"\"\n    Find all files under 'dir' and return the list of full filenames.\n    Unless dir is '.', return full filenames with dir prepended.\n    \"\"\"\n    files = _find_all_simple(dir)\n    if dir == os.curdir:\n        make_rel = functools.partial(os.path.relpath, start=dir)\n        files = map(make_rel, files)\n    return list(files)\n\n\n# Apply monkey patches\nmonkey.patch_all()\n", "path": "setuptools/__init__.py"}]}