hxrron commited on
Commit
3ac1c98
·
verified ·
1 Parent(s): 34db625

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. python_embeded/Lib/site-packages/setuptools-80.9.0.dist-info/licenses/LICENSE +17 -0
  2. python_embeded/Lib/site-packages/setuptools/command/__init__.py +21 -0
  3. python_embeded/Lib/site-packages/setuptools/command/_requirestxt.py +131 -0
  4. python_embeded/Lib/site-packages/setuptools/command/alias.py +77 -0
  5. python_embeded/Lib/site-packages/setuptools/command/bdist_egg.py +477 -0
  6. python_embeded/Lib/site-packages/setuptools/command/bdist_rpm.py +42 -0
  7. python_embeded/Lib/site-packages/setuptools/command/bdist_wheel.py +604 -0
  8. python_embeded/Lib/site-packages/setuptools/command/build.py +135 -0
  9. python_embeded/Lib/site-packages/setuptools/command/build_clib.py +103 -0
  10. python_embeded/Lib/site-packages/setuptools/command/build_ext.py +470 -0
  11. python_embeded/Lib/site-packages/setuptools/command/build_py.py +400 -0
  12. python_embeded/Lib/site-packages/setuptools/command/develop.py +55 -0
  13. python_embeded/Lib/site-packages/setuptools/command/dist_info.py +103 -0
  14. python_embeded/Lib/site-packages/setuptools/command/easy_install.py +30 -0
  15. python_embeded/Lib/site-packages/setuptools/command/editable_wheel.py +908 -0
  16. python_embeded/Lib/site-packages/setuptools/command/egg_info.py +718 -0
  17. python_embeded/Lib/site-packages/setuptools/command/install.py +131 -0
  18. python_embeded/Lib/site-packages/setuptools/command/install_egg_info.py +58 -0
  19. python_embeded/Lib/site-packages/setuptools/command/install_lib.py +137 -0
  20. python_embeded/Lib/site-packages/setuptools/command/install_scripts.py +67 -0
  21. python_embeded/Lib/site-packages/setuptools/command/launcher manifest.xml +15 -0
  22. python_embeded/Lib/site-packages/setuptools/command/rotate.py +65 -0
  23. python_embeded/Lib/site-packages/setuptools/command/saveopts.py +21 -0
  24. python_embeded/Lib/site-packages/setuptools/command/sdist.py +217 -0
  25. python_embeded/Lib/site-packages/setuptools/command/setopt.py +141 -0
  26. python_embeded/Lib/site-packages/setuptools/command/test.py +45 -0
  27. python_embeded/Lib/site-packages/setuptools/compat/__init__.py +0 -0
  28. python_embeded/Lib/site-packages/setuptools/compat/py310.py +20 -0
  29. python_embeded/Lib/site-packages/setuptools/compat/py311.py +27 -0
  30. python_embeded/Lib/site-packages/setuptools/compat/py312.py +13 -0
  31. python_embeded/Lib/site-packages/setuptools/compat/py39.py +9 -0
  32. python_embeded/Lib/site-packages/setuptools/config/NOTICE +10 -0
  33. python_embeded/Lib/site-packages/setuptools/config/__init__.py +43 -0
  34. python_embeded/Lib/site-packages/setuptools/config/_apply_pyprojecttoml.py +526 -0
  35. python_embeded/Lib/site-packages/setuptools/config/distutils.schema.json +26 -0
  36. python_embeded/Lib/site-packages/setuptools/config/expand.py +452 -0
  37. python_embeded/Lib/site-packages/setuptools/config/pyprojecttoml.py +468 -0
  38. python_embeded/Lib/site-packages/setuptools/config/setupcfg.py +780 -0
  39. python_embeded/Lib/site-packages/setuptools/config/setuptools.schema.json +433 -0
  40. python_embeded/Lib/site-packages/setuptools/tests/contexts.py +131 -0
  41. python_embeded/Lib/site-packages/setuptools/tests/environment.py +95 -0
  42. python_embeded/Lib/site-packages/setuptools/tests/fixtures.py +392 -0
  43. python_embeded/Lib/site-packages/setuptools/tests/mod_with_constant.py +1 -0
  44. python_embeded/Lib/site-packages/setuptools/tests/namespaces.py +90 -0
  45. python_embeded/Lib/site-packages/setuptools/tests/script-with-bom.py +1 -0
  46. python_embeded/Lib/site-packages/setuptools/tests/test_archive_util.py +36 -0
  47. python_embeded/Lib/site-packages/setuptools/tests/test_bdist_deprecations.py +28 -0
  48. python_embeded/Lib/site-packages/setuptools/tests/test_bdist_egg.py +73 -0
  49. python_embeded/Lib/site-packages/setuptools/tests/test_bdist_wheel.py +708 -0
  50. python_embeded/Lib/site-packages/setuptools/tests/test_build.py +33 -0
python_embeded/Lib/site-packages/setuptools-80.9.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Permission is hereby granted, free of charge, to any person obtaining a copy
2
+ of this software and associated documentation files (the "Software"), to
3
+ deal in the Software without restriction, including without limitation the
4
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
5
+ sell copies of the Software, and to permit persons to whom the Software is
6
+ furnished to do so, subject to the following conditions:
7
+
8
+ The above copyright notice and this permission notice shall be included in
9
+ all copies or substantial portions of the Software.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
16
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
17
+ IN THE SOFTWARE.
python_embeded/Lib/site-packages/setuptools/command/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disable_error_code=call-overload
2
+ # pyright: reportCallIssue=false, reportArgumentType=false
3
+ # Can't disable on the exact line because distutils doesn't exists on Python 3.12
4
+ # and type-checkers aren't aware of distutils_hack,
5
+ # causing distutils.command.bdist.bdist.format_commands to be Any.
6
+
7
+ import sys
8
+
9
+ from distutils.command.bdist import bdist
10
+
11
+ if 'egg' not in bdist.format_commands:
12
+ try:
13
+ # format_commands is a dict in vendored distutils
14
+ # It used to be a list in older (stdlib) distutils
15
+ # We support both for backwards compatibility
16
+ bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
17
+ except TypeError:
18
+ bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
19
+ bdist.format_commands.append('egg')
20
+
21
+ del bdist, sys
python_embeded/Lib/site-packages/setuptools/command/_requirestxt.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper code used to generate ``requires.txt`` files in the egg-info directory.
2
+
3
+ The ``requires.txt`` file has an specific format:
4
+ - Environment markers need to be part of the section headers and
5
+ should not be part of the requirement spec itself.
6
+
7
+ See https://setuptools.pypa.io/en/latest/deprecated/python_eggs.html#requires-txt
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import io
13
+ from collections import defaultdict
14
+ from collections.abc import Mapping
15
+ from itertools import filterfalse
16
+ from typing import TypeVar
17
+
18
+ from jaraco.text import yield_lines
19
+ from packaging.requirements import Requirement
20
+
21
+ from .. import _reqs
22
+ from .._reqs import _StrOrIter
23
+
24
+ # dict can work as an ordered set
25
+ _T = TypeVar("_T")
26
+ _Ordered = dict[_T, None]
27
+
28
+
29
+ def _prepare(
30
+ install_requires: _StrOrIter, extras_require: Mapping[str, _StrOrIter]
31
+ ) -> tuple[list[str], dict[str, list[str]]]:
32
+ """Given values for ``install_requires`` and ``extras_require``
33
+ create modified versions in a way that can be written in ``requires.txt``
34
+ """
35
+ extras = _convert_extras_requirements(extras_require)
36
+ return _move_install_requirements_markers(install_requires, extras)
37
+
38
+
39
+ def _convert_extras_requirements(
40
+ extras_require: Mapping[str, _StrOrIter],
41
+ ) -> defaultdict[str, _Ordered[Requirement]]:
42
+ """
43
+ Convert requirements in `extras_require` of the form
44
+ `"extra": ["barbazquux; {marker}"]` to
45
+ `"extra:{marker}": ["barbazquux"]`.
46
+ """
47
+ output = defaultdict[str, _Ordered[Requirement]](dict)
48
+ for section, v in extras_require.items():
49
+ # Do not strip empty sections.
50
+ output[section]
51
+ for r in _reqs.parse(v):
52
+ output[section + _suffix_for(r)].setdefault(r)
53
+
54
+ return output
55
+
56
+
57
+ def _move_install_requirements_markers(
58
+ install_requires: _StrOrIter, extras_require: Mapping[str, _Ordered[Requirement]]
59
+ ) -> tuple[list[str], dict[str, list[str]]]:
60
+ """
61
+ The ``requires.txt`` file has an specific format:
62
+ - Environment markers need to be part of the section headers and
63
+ should not be part of the requirement spec itself.
64
+
65
+ Move requirements in ``install_requires`` that are using environment
66
+ markers ``extras_require``.
67
+ """
68
+
69
+ # divide the install_requires into two sets, simple ones still
70
+ # handled by install_requires and more complex ones handled by extras_require.
71
+
72
+ inst_reqs = list(_reqs.parse(install_requires))
73
+ simple_reqs = filter(_no_marker, inst_reqs)
74
+ complex_reqs = filterfalse(_no_marker, inst_reqs)
75
+ simple_install_requires = list(map(str, simple_reqs))
76
+
77
+ for r in complex_reqs:
78
+ extras_require[':' + str(r.marker)].setdefault(r)
79
+
80
+ expanded_extras = dict(
81
+ # list(dict.fromkeys(...)) ensures a list of unique strings
82
+ (k, list(dict.fromkeys(str(r) for r in map(_clean_req, v))))
83
+ for k, v in extras_require.items()
84
+ )
85
+
86
+ return simple_install_requires, expanded_extras
87
+
88
+
89
+ def _suffix_for(req):
90
+ """Return the 'extras_require' suffix for a given requirement."""
91
+ return ':' + str(req.marker) if req.marker else ''
92
+
93
+
94
+ def _clean_req(req):
95
+ """Given a Requirement, remove environment markers and return it"""
96
+ r = Requirement(str(req)) # create a copy before modifying
97
+ r.marker = None
98
+ return r
99
+
100
+
101
+ def _no_marker(req):
102
+ return not req.marker
103
+
104
+
105
+ def _write_requirements(stream, reqs):
106
+ lines = yield_lines(reqs or ())
107
+
108
+ def append_cr(line):
109
+ return line + '\n'
110
+
111
+ lines = map(append_cr, lines)
112
+ stream.writelines(lines)
113
+
114
+
115
+ def write_requirements(cmd, basename, filename):
116
+ dist = cmd.distribution
117
+ data = io.StringIO()
118
+ install_requires, extras_require = _prepare(
119
+ dist.install_requires or (), dist.extras_require or {}
120
+ )
121
+ _write_requirements(data, install_requires)
122
+ for extra in sorted(extras_require):
123
+ data.write('\n[{extra}]\n'.format(**vars()))
124
+ _write_requirements(data, extras_require[extra])
125
+ cmd.write_or_delete_file("requirements", filename, data.getvalue())
126
+
127
+
128
+ def write_setup_requirements(cmd, basename, filename):
129
+ data = io.StringIO()
130
+ _write_requirements(data, cmd.distribution.setup_requires)
131
+ cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
python_embeded/Lib/site-packages/setuptools/command/alias.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools.command.setopt import config_file, edit_config, option_base
2
+
3
+ from distutils.errors import DistutilsOptionError
4
+
5
+
6
+ def shquote(arg):
7
+ """Quote an argument for later parsing by shlex.split()"""
8
+ for c in '"', "'", "\\", "#":
9
+ if c in arg:
10
+ return repr(arg)
11
+ if arg.split() != [arg]:
12
+ return repr(arg)
13
+ return arg
14
+
15
+
16
+ class alias(option_base):
17
+ """Define a shortcut that invokes one or more commands"""
18
+
19
+ description = "define a shortcut to invoke one or more commands"
20
+ command_consumes_arguments = True
21
+
22
+ user_options = [
23
+ ('remove', 'r', 'remove (unset) the alias'),
24
+ ] + option_base.user_options
25
+
26
+ boolean_options = option_base.boolean_options + ['remove']
27
+
28
+ def initialize_options(self):
29
+ option_base.initialize_options(self)
30
+ self.args = None
31
+ self.remove = None
32
+
33
+ def finalize_options(self) -> None:
34
+ option_base.finalize_options(self)
35
+ if self.remove and len(self.args) != 1:
36
+ raise DistutilsOptionError(
37
+ "Must specify exactly one argument (the alias name) when using --remove"
38
+ )
39
+
40
+ def run(self) -> None:
41
+ aliases = self.distribution.get_option_dict('aliases')
42
+
43
+ if not self.args:
44
+ print("Command Aliases")
45
+ print("---------------")
46
+ for alias in aliases:
47
+ print("setup.py alias", format_alias(alias, aliases))
48
+ return
49
+
50
+ elif len(self.args) == 1:
51
+ (alias,) = self.args
52
+ if self.remove:
53
+ command = None
54
+ elif alias in aliases:
55
+ print("setup.py alias", format_alias(alias, aliases))
56
+ return
57
+ else:
58
+ print(f"No alias definition found for {alias!r}")
59
+ return
60
+ else:
61
+ alias = self.args[0]
62
+ command = ' '.join(map(shquote, self.args[1:]))
63
+
64
+ edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)
65
+
66
+
67
+ def format_alias(name, aliases):
68
+ source, command = aliases[name]
69
+ if source == config_file('global'):
70
+ source = '--global-config '
71
+ elif source == config_file('user'):
72
+ source = '--user-config '
73
+ elif source == config_file('local'):
74
+ source = ''
75
+ else:
76
+ source = f'--filename={source!r}'
77
+ return source + name + ' ' + command
python_embeded/Lib/site-packages/setuptools/command/bdist_egg.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """setuptools.command.bdist_egg
2
+
3
+ Build .egg distributions"""
4
+
5
+ from __future__ import annotations
6
+
7
+ import marshal
8
+ import os
9
+ import re
10
+ import sys
11
+ import textwrap
12
+ from sysconfig import get_path, get_platform, get_python_version
13
+ from types import CodeType
14
+ from typing import TYPE_CHECKING, Literal
15
+
16
+ from setuptools import Command
17
+ from setuptools.extension import Library
18
+
19
+ from .._path import StrPathT, ensure_directory
20
+
21
+ from distutils import log
22
+ from distutils.dir_util import mkpath, remove_tree
23
+
24
+ if TYPE_CHECKING:
25
+ from typing_extensions import TypeAlias
26
+
27
+ # Same as zipfile._ZipFileMode from typeshed
28
+ _ZipFileMode: TypeAlias = Literal["r", "w", "x", "a"]
29
+
30
+
31
+ def _get_purelib():
32
+ return get_path("purelib")
33
+
34
+
35
+ def strip_module(filename):
36
+ if '.' in filename:
37
+ filename = os.path.splitext(filename)[0]
38
+ if filename.endswith('module'):
39
+ filename = filename[:-6]
40
+ return filename
41
+
42
+
43
+ def sorted_walk(dir):
44
+ """Do os.walk in a reproducible way,
45
+ independent of indeterministic filesystem readdir order
46
+ """
47
+ for base, dirs, files in os.walk(dir):
48
+ dirs.sort()
49
+ files.sort()
50
+ yield base, dirs, files
51
+
52
+
53
+ def write_stub(resource, pyfile) -> None:
54
+ _stub_template = textwrap.dedent(
55
+ """
56
+ def __bootstrap__():
57
+ global __bootstrap__, __loader__, __file__
58
+ import sys, importlib.resources as irs, importlib.util
59
+ with irs.as_file(irs.files(__name__).joinpath(%r)) as __file__:
60
+ __loader__ = None; del __bootstrap__, __loader__
61
+ spec = importlib.util.spec_from_file_location(__name__,__file__)
62
+ mod = importlib.util.module_from_spec(spec)
63
+ spec.loader.exec_module(mod)
64
+ __bootstrap__()
65
+ """
66
+ ).lstrip()
67
+ with open(pyfile, 'w', encoding="utf-8") as f:
68
+ f.write(_stub_template % resource)
69
+
70
+
71
+ class bdist_egg(Command):
72
+ description = 'create an "egg" distribution'
73
+
74
+ user_options = [
75
+ ('bdist-dir=', 'b', "temporary directory for creating the distribution"),
76
+ (
77
+ 'plat-name=',
78
+ 'p',
79
+ "platform name to embed in generated filenames "
80
+ "(by default uses `sysconfig.get_platform()`)",
81
+ ),
82
+ ('exclude-source-files', None, "remove all .py files from the generated egg"),
83
+ (
84
+ 'keep-temp',
85
+ 'k',
86
+ "keep the pseudo-installation tree around after "
87
+ "creating the distribution archive",
88
+ ),
89
+ ('dist-dir=', 'd', "directory to put final built distributions in"),
90
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
91
+ ]
92
+
93
+ boolean_options = ['keep-temp', 'skip-build', 'exclude-source-files']
94
+
95
+ def initialize_options(self):
96
+ self.bdist_dir = None
97
+ self.plat_name = None
98
+ self.keep_temp = False
99
+ self.dist_dir = None
100
+ self.skip_build = False
101
+ self.egg_output = None
102
+ self.exclude_source_files = None
103
+
104
+ def finalize_options(self) -> None:
105
+ ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info")
106
+ self.egg_info = ei_cmd.egg_info
107
+
108
+ if self.bdist_dir is None:
109
+ bdist_base = self.get_finalized_command('bdist').bdist_base
110
+ self.bdist_dir = os.path.join(bdist_base, 'egg')
111
+
112
+ if self.plat_name is None:
113
+ self.plat_name = get_platform()
114
+
115
+ self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
116
+
117
+ if self.egg_output is None:
118
+ # Compute filename of the output egg
119
+ basename = ei_cmd._get_egg_basename(
120
+ py_version=get_python_version(),
121
+ platform=self.distribution.has_ext_modules() and self.plat_name,
122
+ )
123
+
124
+ self.egg_output = os.path.join(self.dist_dir, basename + '.egg')
125
+
126
+ def do_install_data(self) -> None:
127
+ # Hack for packages that install data to install's --install-lib
128
+ self.get_finalized_command('install').install_lib = self.bdist_dir
129
+
130
+ site_packages = os.path.normcase(os.path.realpath(_get_purelib()))
131
+ old, self.distribution.data_files = self.distribution.data_files, []
132
+
133
+ for item in old:
134
+ if isinstance(item, tuple) and len(item) == 2:
135
+ if os.path.isabs(item[0]):
136
+ realpath = os.path.realpath(item[0])
137
+ normalized = os.path.normcase(realpath)
138
+ if normalized == site_packages or normalized.startswith(
139
+ site_packages + os.sep
140
+ ):
141
+ item = realpath[len(site_packages) + 1 :], item[1]
142
+ # XXX else: raise ???
143
+ self.distribution.data_files.append(item)
144
+
145
+ try:
146
+ log.info("installing package data to %s", self.bdist_dir)
147
+ self.call_command('install_data', force=False, root=None)
148
+ finally:
149
+ self.distribution.data_files = old
150
+
151
+ def get_outputs(self):
152
+ return [self.egg_output]
153
+
154
+ def call_command(self, cmdname, **kw):
155
+ """Invoke reinitialized command `cmdname` with keyword args"""
156
+ for dirname in INSTALL_DIRECTORY_ATTRS:
157
+ kw.setdefault(dirname, self.bdist_dir)
158
+ kw.setdefault('skip_build', self.skip_build)
159
+ kw.setdefault('dry_run', self.dry_run)
160
+ cmd = self.reinitialize_command(cmdname, **kw)
161
+ self.run_command(cmdname)
162
+ return cmd
163
+
164
+ def run(self): # noqa: C901 # is too complex (14) # FIXME
165
+ # Generate metadata first
166
+ self.run_command("egg_info")
167
+ # We run install_lib before install_data, because some data hacks
168
+ # pull their data path from the install_lib command.
169
+ log.info("installing library code to %s", self.bdist_dir)
170
+ instcmd = self.get_finalized_command('install')
171
+ old_root = instcmd.root
172
+ instcmd.root = None
173
+ if self.distribution.has_c_libraries() and not self.skip_build:
174
+ self.run_command('build_clib')
175
+ cmd = self.call_command('install_lib', warn_dir=False)
176
+ instcmd.root = old_root
177
+
178
+ all_outputs, ext_outputs = self.get_ext_outputs()
179
+ self.stubs = []
180
+ to_compile = []
181
+ for p, ext_name in enumerate(ext_outputs):
182
+ filename, _ext = os.path.splitext(ext_name)
183
+ pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py')
184
+ self.stubs.append(pyfile)
185
+ log.info("creating stub loader for %s", ext_name)
186
+ if not self.dry_run:
187
+ write_stub(os.path.basename(ext_name), pyfile)
188
+ to_compile.append(pyfile)
189
+ ext_outputs[p] = ext_name.replace(os.sep, '/')
190
+
191
+ if to_compile:
192
+ cmd.byte_compile(to_compile)
193
+ if self.distribution.data_files:
194
+ self.do_install_data()
195
+
196
+ # Make the EGG-INFO directory
197
+ archive_root = self.bdist_dir
198
+ egg_info = os.path.join(archive_root, 'EGG-INFO')
199
+ self.mkpath(egg_info)
200
+ if self.distribution.scripts:
201
+ script_dir = os.path.join(egg_info, 'scripts')
202
+ log.info("installing scripts to %s", script_dir)
203
+ self.call_command('install_scripts', install_dir=script_dir, no_ep=True)
204
+
205
+ self.copy_metadata_to(egg_info)
206
+ native_libs = os.path.join(egg_info, "native_libs.txt")
207
+ if all_outputs:
208
+ log.info("writing %s", native_libs)
209
+ if not self.dry_run:
210
+ ensure_directory(native_libs)
211
+ with open(native_libs, 'wt', encoding="utf-8") as libs_file:
212
+ libs_file.write('\n'.join(all_outputs))
213
+ libs_file.write('\n')
214
+ elif os.path.isfile(native_libs):
215
+ log.info("removing %s", native_libs)
216
+ if not self.dry_run:
217
+ os.unlink(native_libs)
218
+
219
+ write_safety_flag(os.path.join(archive_root, 'EGG-INFO'), self.zip_safe())
220
+
221
+ if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):
222
+ log.warn(
223
+ "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n"
224
+ "Use the install_requires/extras_require setup() args instead."
225
+ )
226
+
227
+ if self.exclude_source_files:
228
+ self.zap_pyfiles()
229
+
230
+ # Make the archive
231
+ make_zipfile(
232
+ self.egg_output,
233
+ archive_root,
234
+ verbose=self.verbose,
235
+ dry_run=self.dry_run,
236
+ mode=self.gen_header(),
237
+ )
238
+ if not self.keep_temp:
239
+ remove_tree(self.bdist_dir, dry_run=self.dry_run)
240
+
241
+ # Add to 'Distribution.dist_files' so that the "upload" command works
242
+ getattr(self.distribution, 'dist_files', []).append((
243
+ 'bdist_egg',
244
+ get_python_version(),
245
+ self.egg_output,
246
+ ))
247
+
248
+ def zap_pyfiles(self):
249
+ log.info("Removing .py files from temporary directory")
250
+ for base, dirs, files in walk_egg(self.bdist_dir):
251
+ for name in files:
252
+ path = os.path.join(base, name)
253
+
254
+ if name.endswith('.py'):
255
+ log.debug("Deleting %s", path)
256
+ os.unlink(path)
257
+
258
+ if base.endswith('__pycache__'):
259
+ path_old = path
260
+
261
+ pattern = r'(?P<name>.+)\.(?P<magic>[^.]+)\.pyc'
262
+ m = re.match(pattern, name)
263
+ path_new = os.path.join(base, os.pardir, m.group('name') + '.pyc')
264
+ log.info(f"Renaming file from [{path_old}] to [{path_new}]")
265
+ try:
266
+ os.remove(path_new)
267
+ except OSError:
268
+ pass
269
+ os.rename(path_old, path_new)
270
+
271
+ def zip_safe(self):
272
+ safe = getattr(self.distribution, 'zip_safe', None)
273
+ if safe is not None:
274
+ return safe
275
+ log.warn("zip_safe flag not set; analyzing archive contents...")
276
+ return analyze_egg(self.bdist_dir, self.stubs)
277
+
278
+ def gen_header(self) -> Literal["w"]:
279
+ return 'w'
280
+
281
+ def copy_metadata_to(self, target_dir) -> None:
282
+ "Copy metadata (egg info) to the target_dir"
283
+ # normalize the path (so that a forward-slash in egg_info will
284
+ # match using startswith below)
285
+ norm_egg_info = os.path.normpath(self.egg_info)
286
+ prefix = os.path.join(norm_egg_info, '')
287
+ for path in self.ei_cmd.filelist.files:
288
+ if path.startswith(prefix):
289
+ target = os.path.join(target_dir, path[len(prefix) :])
290
+ ensure_directory(target)
291
+ self.copy_file(path, target)
292
+
293
+ def get_ext_outputs(self):
294
+ """Get a list of relative paths to C extensions in the output distro"""
295
+
296
+ all_outputs = []
297
+ ext_outputs = []
298
+
299
+ paths = {self.bdist_dir: ''}
300
+ for base, dirs, files in sorted_walk(self.bdist_dir):
301
+ all_outputs.extend(
302
+ paths[base] + filename
303
+ for filename in files
304
+ if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS
305
+ )
306
+ for filename in dirs:
307
+ paths[os.path.join(base, filename)] = paths[base] + filename + '/'
308
+
309
+ if self.distribution.has_ext_modules():
310
+ build_cmd = self.get_finalized_command('build_ext')
311
+ for ext in build_cmd.extensions:
312
+ if isinstance(ext, Library):
313
+ continue
314
+ fullname = build_cmd.get_ext_fullname(ext.name)
315
+ filename = build_cmd.get_ext_filename(fullname)
316
+ if not os.path.basename(filename).startswith('dl-'):
317
+ if os.path.exists(os.path.join(self.bdist_dir, filename)):
318
+ ext_outputs.append(filename)
319
+
320
+ return all_outputs, ext_outputs
321
+
322
+
323
+ NATIVE_EXTENSIONS: dict[str, None] = dict.fromkeys('.dll .so .dylib .pyd'.split())
324
+
325
+
326
+ def walk_egg(egg_dir):
327
+ """Walk an unpacked egg's contents, skipping the metadata directory"""
328
+ walker = sorted_walk(egg_dir)
329
+ base, dirs, files = next(walker)
330
+ if 'EGG-INFO' in dirs:
331
+ dirs.remove('EGG-INFO')
332
+ yield base, dirs, files
333
+ yield from walker
334
+
335
+
336
+ def analyze_egg(egg_dir, stubs):
337
+ # check for existing flag in EGG-INFO
338
+ for flag, fn in safety_flags.items():
339
+ if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
340
+ return flag
341
+ if not can_scan():
342
+ return False
343
+ safe = True
344
+ for base, dirs, files in walk_egg(egg_dir):
345
+ for name in files:
346
+ if name.endswith('.py') or name.endswith('.pyw'):
347
+ continue
348
+ elif name.endswith('.pyc') or name.endswith('.pyo'):
349
+ # always scan, even if we already know we're not safe
350
+ safe = scan_module(egg_dir, base, name, stubs) and safe
351
+ return safe
352
+
353
+
354
+ def write_safety_flag(egg_dir, safe) -> None:
355
+ # Write or remove zip safety flag file(s)
356
+ for flag, fn in safety_flags.items():
357
+ fn = os.path.join(egg_dir, fn)
358
+ if os.path.exists(fn):
359
+ if safe is None or bool(safe) != flag:
360
+ os.unlink(fn)
361
+ elif safe is not None and bool(safe) == flag:
362
+ with open(fn, 'wt', encoding="utf-8") as f:
363
+ f.write('\n')
364
+
365
+
366
+ safety_flags = {
367
+ True: 'zip-safe',
368
+ False: 'not-zip-safe',
369
+ }
370
+
371
+
372
+ def scan_module(egg_dir, base, name, stubs):
373
+ """Check whether module possibly uses unsafe-for-zipfile stuff"""
374
+
375
+ filename = os.path.join(base, name)
376
+ if filename[:-1] in stubs:
377
+ return True # Extension module
378
+ pkg = base[len(egg_dir) + 1 :].replace(os.sep, '.')
379
+ module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]
380
+ skip = 16 # skip magic & reserved? & date & file size
381
+ f = open(filename, 'rb')
382
+ f.read(skip)
383
+ code = marshal.load(f)
384
+ f.close()
385
+ safe = True
386
+ symbols = dict.fromkeys(iter_symbols(code))
387
+ for bad in ['__file__', '__path__']:
388
+ if bad in symbols:
389
+ log.warn("%s: module references %s", module, bad)
390
+ safe = False
391
+ if 'inspect' in symbols:
392
+ for bad in [
393
+ 'getsource',
394
+ 'getabsfile',
395
+ 'getfile',
396
+ 'getsourcefile',
397
+ 'getsourcelines',
398
+ 'findsource',
399
+ 'getcomments',
400
+ 'getframeinfo',
401
+ 'getinnerframes',
402
+ 'getouterframes',
403
+ 'stack',
404
+ 'trace',
405
+ ]:
406
+ if bad in symbols:
407
+ log.warn("%s: module MAY be using inspect.%s", module, bad)
408
+ safe = False
409
+ return safe
410
+
411
+
412
+ def iter_symbols(code):
413
+ """Yield names and strings used by `code` and its nested code objects"""
414
+ yield from code.co_names
415
+ for const in code.co_consts:
416
+ if isinstance(const, str):
417
+ yield const
418
+ elif isinstance(const, CodeType):
419
+ yield from iter_symbols(const)
420
+
421
+
422
+ def can_scan() -> bool:
423
+ if not sys.platform.startswith('java') and sys.platform != 'cli':
424
+ # CPython, PyPy, etc.
425
+ return True
426
+ log.warn("Unable to analyze compiled code on this platform.")
427
+ log.warn(
428
+ "Please ask the author to include a 'zip_safe'"
429
+ " setting (either True or False) in the package's setup.py"
430
+ )
431
+ return False
432
+
433
+
434
+ # Attribute names of options for commands that might need to be convinced to
435
+ # install to the egg build directory
436
+
437
+ INSTALL_DIRECTORY_ATTRS = ['install_lib', 'install_dir', 'install_data', 'install_base']
438
+
439
+
440
+ def make_zipfile(
441
+ zip_filename: StrPathT,
442
+ base_dir,
443
+ verbose: bool = False,
444
+ dry_run: bool = False,
445
+ compress=True,
446
+ mode: _ZipFileMode = 'w',
447
+ ) -> StrPathT:
448
+ """Create a zip file from all the files under 'base_dir'. The output
449
+ zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
450
+ Python module (if available) or the InfoZIP "zip" utility (if installed
451
+ and found on the default search path). If neither tool is available,
452
+ raises DistutilsExecError. Returns the name of the output zip file.
453
+ """
454
+ import zipfile
455
+
456
+ mkpath(os.path.dirname(zip_filename), dry_run=dry_run) # type: ignore[arg-type] # python/mypy#18075
457
+ log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
458
+
459
+ def visit(z, dirname, names):
460
+ for name in names:
461
+ path = os.path.normpath(os.path.join(dirname, name))
462
+ if os.path.isfile(path):
463
+ p = path[len(base_dir) + 1 :]
464
+ if not dry_run:
465
+ z.write(path, p)
466
+ log.debug("adding '%s'", p)
467
+
468
+ compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
469
+ if not dry_run:
470
+ z = zipfile.ZipFile(zip_filename, mode, compression=compression)
471
+ for dirname, dirs, files in sorted_walk(base_dir):
472
+ visit(z, dirname, files)
473
+ z.close()
474
+ else:
475
+ for dirname, dirs, files in sorted_walk(base_dir):
476
+ visit(None, dirname, files)
477
+ return zip_filename
python_embeded/Lib/site-packages/setuptools/command/bdist_rpm.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..dist import Distribution
2
+ from ..warnings import SetuptoolsDeprecationWarning
3
+
4
+ import distutils.command.bdist_rpm as orig
5
+
6
+
7
+ class bdist_rpm(orig.bdist_rpm):
8
+ """
9
+ Override the default bdist_rpm behavior to do the following:
10
+
11
+ 1. Run egg_info to ensure the name and version are properly calculated.
12
+ 2. Always run 'install' using --single-version-externally-managed to
13
+ disable eggs in RPM distributions.
14
+ """
15
+
16
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
17
+
18
+ def run(self) -> None:
19
+ SetuptoolsDeprecationWarning.emit(
20
+ "Deprecated command",
21
+ """
22
+ bdist_rpm is deprecated and will be removed in a future version.
23
+ Use bdist_wheel (wheel packages) instead.
24
+ """,
25
+ see_url="https://github.com/pypa/setuptools/issues/1988",
26
+ due_date=(2023, 10, 30), # Deprecation introduced in 22 Oct 2021.
27
+ )
28
+
29
+ # ensure distro name is up-to-date
30
+ self.run_command('egg_info')
31
+
32
+ orig.bdist_rpm.run(self)
33
+
34
+ def _make_spec_file(self):
35
+ spec = orig.bdist_rpm._make_spec_file(self)
36
+ return [
37
+ line.replace(
38
+ "setup.py install ",
39
+ "setup.py install --single-version-externally-managed ",
40
+ ).replace("%setup", "%setup -n %{name}-%{unmangled_version}")
41
+ for line in spec
42
+ ]
python_embeded/Lib/site-packages/setuptools/command/bdist_wheel.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Create a wheel (.whl) distribution.
3
+
4
+ A wheel is a built archive format.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+ import shutil
12
+ import struct
13
+ import sys
14
+ import sysconfig
15
+ import warnings
16
+ from collections.abc import Iterable, Sequence
17
+ from email.generator import BytesGenerator
18
+ from glob import iglob
19
+ from typing import Literal, cast
20
+ from zipfile import ZIP_DEFLATED, ZIP_STORED
21
+
22
+ from packaging import tags, version as _packaging_version
23
+ from wheel.wheelfile import WheelFile
24
+
25
+ from .. import Command, __version__, _shutil
26
+ from .._core_metadata import _safe_license_file
27
+ from .._normalization import safer_name
28
+ from ..warnings import SetuptoolsDeprecationWarning
29
+ from .egg_info import egg_info as egg_info_cls
30
+
31
+ from distutils import log
32
+
33
+
34
+ def safe_version(version: str) -> str:
35
+ """
36
+ Convert an arbitrary string to a standard version string
37
+ """
38
+ try:
39
+ # normalize the version
40
+ return str(_packaging_version.Version(version))
41
+ except _packaging_version.InvalidVersion:
42
+ version = version.replace(" ", ".")
43
+ return re.sub("[^A-Za-z0-9.]+", "-", version)
44
+
45
+
46
+ setuptools_major_version = int(__version__.split(".")[0])
47
+
48
+ PY_LIMITED_API_PATTERN = r"cp3\d"
49
+
50
+
51
+ def _is_32bit_interpreter() -> bool:
52
+ return struct.calcsize("P") == 4
53
+
54
+
55
+ def python_tag() -> str:
56
+ return f"py{sys.version_info.major}"
57
+
58
+
59
+ def get_platform(archive_root: str | None) -> str:
60
+ """Return our platform name 'win32', 'linux_x86_64'"""
61
+ result = sysconfig.get_platform()
62
+ if result.startswith("macosx") and archive_root is not None: # pragma: no cover
63
+ from wheel.macosx_libfile import calculate_macosx_platform_tag
64
+
65
+ result = calculate_macosx_platform_tag(archive_root, result)
66
+ elif _is_32bit_interpreter():
67
+ if result == "linux-x86_64":
68
+ # pip pull request #3497
69
+ result = "linux-i686"
70
+ elif result == "linux-aarch64":
71
+ # packaging pull request #234
72
+ # TODO armv8l, packaging pull request #690 => this did not land
73
+ # in pip/packaging yet
74
+ result = "linux-armv7l"
75
+
76
+ return result.replace("-", "_")
77
+
78
+
79
+ def get_flag(
80
+ var: str, fallback: bool, expected: bool = True, warn: bool = True
81
+ ) -> bool:
82
+ """Use a fallback value for determining SOABI flags if the needed config
83
+ var is unset or unavailable."""
84
+ val = sysconfig.get_config_var(var)
85
+ if val is None:
86
+ if warn:
87
+ warnings.warn(
88
+ f"Config variable '{var}' is unset, Python ABI tag may be incorrect",
89
+ RuntimeWarning,
90
+ stacklevel=2,
91
+ )
92
+ return fallback
93
+ return val == expected
94
+
95
+
96
+ def get_abi_tag() -> str | None:
97
+ """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2)."""
98
+ soabi: str = sysconfig.get_config_var("SOABI")
99
+ impl = tags.interpreter_name()
100
+ if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"):
101
+ d = ""
102
+ u = ""
103
+ if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")):
104
+ d = "d"
105
+
106
+ abi = f"{impl}{tags.interpreter_version()}{d}{u}"
107
+ elif soabi and impl == "cp" and soabi.startswith("cpython"):
108
+ # non-Windows
109
+ abi = "cp" + soabi.split("-")[1]
110
+ elif soabi and impl == "cp" and soabi.startswith("cp"):
111
+ # Windows
112
+ abi = soabi.split("-")[0]
113
+ if hasattr(sys, "gettotalrefcount"):
114
+ # using debug build; append "d" flag
115
+ abi += "d"
116
+ elif soabi and impl == "pp":
117
+ # we want something like pypy36-pp73
118
+ abi = "-".join(soabi.split("-")[:2])
119
+ abi = abi.replace(".", "_").replace("-", "_")
120
+ elif soabi and impl == "graalpy":
121
+ abi = "-".join(soabi.split("-")[:3])
122
+ abi = abi.replace(".", "_").replace("-", "_")
123
+ elif soabi:
124
+ abi = soabi.replace(".", "_").replace("-", "_")
125
+ else:
126
+ abi = None
127
+
128
+ return abi
129
+
130
+
131
+ def safer_version(version: str) -> str:
132
+ return safe_version(version).replace("-", "_")
133
+
134
+
135
+ class bdist_wheel(Command):
136
+ description = "create a wheel distribution"
137
+
138
+ supported_compressions = {
139
+ "stored": ZIP_STORED,
140
+ "deflated": ZIP_DEFLATED,
141
+ }
142
+
143
+ user_options = [
144
+ ("bdist-dir=", "b", "temporary directory for creating the distribution"),
145
+ (
146
+ "plat-name=",
147
+ "p",
148
+ "platform name to embed in generated filenames "
149
+ f"[default: {get_platform(None)}]",
150
+ ),
151
+ (
152
+ "keep-temp",
153
+ "k",
154
+ "keep the pseudo-installation tree around after "
155
+ "creating the distribution archive",
156
+ ),
157
+ ("dist-dir=", "d", "directory to put final built distributions in"),
158
+ ("skip-build", None, "skip rebuilding everything (for testing/debugging)"),
159
+ (
160
+ "relative",
161
+ None,
162
+ "build the archive using relative paths [default: false]",
163
+ ),
164
+ (
165
+ "owner=",
166
+ "u",
167
+ "Owner name used when creating a tar file [default: current user]",
168
+ ),
169
+ (
170
+ "group=",
171
+ "g",
172
+ "Group name used when creating a tar file [default: current group]",
173
+ ),
174
+ ("universal", None, "*DEPRECATED* make a universal wheel [default: false]"),
175
+ (
176
+ "compression=",
177
+ None,
178
+ f"zipfile compression (one of: {', '.join(supported_compressions)}) [default: 'deflated']",
179
+ ),
180
+ (
181
+ "python-tag=",
182
+ None,
183
+ f"Python implementation compatibility tag [default: '{python_tag()}']",
184
+ ),
185
+ (
186
+ "build-number=",
187
+ None,
188
+ "Build number for this particular version. "
189
+ "As specified in PEP-0427, this must start with a digit. "
190
+ "[default: None]",
191
+ ),
192
+ (
193
+ "py-limited-api=",
194
+ None,
195
+ "Python tag (cp32|cp33|cpNN) for abi3 wheel tag [default: false]",
196
+ ),
197
+ (
198
+ "dist-info-dir=",
199
+ None,
200
+ "directory where a pre-generated dist-info can be found (e.g. as a "
201
+ "result of calling the PEP517 'prepare_metadata_for_build_wheel' "
202
+ "method)",
203
+ ),
204
+ ]
205
+
206
+ boolean_options = ["keep-temp", "skip-build", "relative", "universal"]
207
+
208
+ def initialize_options(self) -> None:
209
+ self.bdist_dir: str | None = None
210
+ self.data_dir = ""
211
+ self.plat_name: str | None = None
212
+ self.plat_tag: str | None = None
213
+ self.format = "zip"
214
+ self.keep_temp = False
215
+ self.dist_dir: str | None = None
216
+ self.dist_info_dir = None
217
+ self.egginfo_dir: str | None = None
218
+ self.root_is_pure: bool | None = None
219
+ self.skip_build = False
220
+ self.relative = False
221
+ self.owner = None
222
+ self.group = None
223
+ self.universal = False
224
+ self.compression: str | int = "deflated"
225
+ self.python_tag = python_tag()
226
+ self.build_number: str | None = None
227
+ self.py_limited_api: str | Literal[False] = False
228
+ self.plat_name_supplied = False
229
+
230
+ def finalize_options(self) -> None:
231
+ if not self.bdist_dir:
232
+ bdist_base = self.get_finalized_command("bdist").bdist_base
233
+ self.bdist_dir = os.path.join(bdist_base, "wheel")
234
+
235
+ if self.dist_info_dir is None:
236
+ egg_info = cast(egg_info_cls, self.distribution.get_command_obj("egg_info"))
237
+ egg_info.ensure_finalized() # needed for correct `wheel_dist_name`
238
+
239
+ self.data_dir = self.wheel_dist_name + ".data"
240
+ self.plat_name_supplied = bool(self.plat_name)
241
+
242
+ need_options = ("dist_dir", "plat_name", "skip_build")
243
+
244
+ self.set_undefined_options("bdist", *zip(need_options, need_options))
245
+
246
+ self.root_is_pure = not (
247
+ self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
248
+ )
249
+
250
+ self._validate_py_limited_api()
251
+
252
+ # Support legacy [wheel] section for setting universal
253
+ wheel = self.distribution.get_option_dict("wheel")
254
+ if "universal" in wheel: # pragma: no cover
255
+ # please don't define this in your global configs
256
+ log.warn("The [wheel] section is deprecated. Use [bdist_wheel] instead.")
257
+ val = wheel["universal"][1].strip()
258
+ if val.lower() in ("1", "true", "yes"):
259
+ self.universal = True
260
+
261
+ if self.universal:
262
+ SetuptoolsDeprecationWarning.emit(
263
+ "bdist_wheel.universal is deprecated",
264
+ """
265
+ With Python 2.7 end-of-life, support for building universal wheels
266
+ (i.e., wheels that support both Python 2 and Python 3)
267
+ is being obviated.
268
+ Please discontinue using this option, or if you still need it,
269
+ file an issue with pypa/setuptools describing your use case.
270
+ """,
271
+ due_date=(2025, 8, 30), # Introduced in 2024-08-30
272
+ )
273
+
274
+ if self.build_number is not None and not self.build_number[:1].isdigit():
275
+ raise ValueError("Build tag (build-number) must start with a digit.")
276
+
277
+ def _validate_py_limited_api(self) -> None:
278
+ if not self.py_limited_api:
279
+ return
280
+
281
+ if not re.match(PY_LIMITED_API_PATTERN, self.py_limited_api):
282
+ raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'")
283
+
284
+ if sysconfig.get_config_var("Py_GIL_DISABLED"):
285
+ raise ValueError(
286
+ f"`py_limited_api={self.py_limited_api!r}` not supported. "
287
+ "`Py_LIMITED_API` is currently incompatible with "
288
+ "`Py_GIL_DISABLED`. "
289
+ "See https://github.com/python/cpython/issues/111506."
290
+ )
291
+
292
+ @property
293
+ def wheel_dist_name(self) -> str:
294
+ """Return distribution full name with - replaced with _"""
295
+ components = [
296
+ safer_name(self.distribution.get_name()),
297
+ safer_version(self.distribution.get_version()),
298
+ ]
299
+ if self.build_number:
300
+ components.append(self.build_number)
301
+ return "-".join(components)
302
+
303
+ def get_tag(self) -> tuple[str, str, str]:
304
+ # bdist sets self.plat_name if unset, we should only use it for purepy
305
+ # wheels if the user supplied it.
306
+ if self.plat_name_supplied and self.plat_name:
307
+ plat_name = self.plat_name
308
+ elif self.root_is_pure:
309
+ plat_name = "any"
310
+ else:
311
+ # macosx contains system version in platform name so need special handle
312
+ if self.plat_name and not self.plat_name.startswith("macosx"):
313
+ plat_name = self.plat_name
314
+ else:
315
+ # on macosx always limit the platform name to comply with any
316
+ # c-extension modules in bdist_dir, since the user can specify
317
+ # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake
318
+
319
+ # on other platforms, and on macosx if there are no c-extension
320
+ # modules, use the default platform name.
321
+ plat_name = get_platform(self.bdist_dir)
322
+
323
+ if _is_32bit_interpreter():
324
+ if plat_name in ("linux-x86_64", "linux_x86_64"):
325
+ plat_name = "linux_i686"
326
+ if plat_name in ("linux-aarch64", "linux_aarch64"):
327
+ # TODO armv8l, packaging pull request #690 => this did not land
328
+ # in pip/packaging yet
329
+ plat_name = "linux_armv7l"
330
+
331
+ plat_name = (
332
+ plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
333
+ )
334
+
335
+ if self.root_is_pure:
336
+ if self.universal:
337
+ impl = "py2.py3"
338
+ else:
339
+ impl = self.python_tag
340
+ tag = (impl, "none", plat_name)
341
+ else:
342
+ impl_name = tags.interpreter_name()
343
+ impl_ver = tags.interpreter_version()
344
+ impl = impl_name + impl_ver
345
+ # We don't work on CPython 3.1, 3.0.
346
+ if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"):
347
+ impl = self.py_limited_api
348
+ abi_tag = "abi3"
349
+ else:
350
+ abi_tag = str(get_abi_tag()).lower()
351
+ tag = (impl, abi_tag, plat_name)
352
+ # issue gh-374: allow overriding plat_name
353
+ supported_tags = [
354
+ (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()
355
+ ]
356
+ assert tag in supported_tags, (
357
+ f"would build wheel with unsupported tag {tag}"
358
+ )
359
+ return tag
360
+
361
+ def run(self):
362
+ build_scripts = self.reinitialize_command("build_scripts")
363
+ build_scripts.executable = "python"
364
+ build_scripts.force = True
365
+
366
+ build_ext = self.reinitialize_command("build_ext")
367
+ build_ext.inplace = False
368
+
369
+ if not self.skip_build:
370
+ self.run_command("build")
371
+
372
+ install = self.reinitialize_command("install", reinit_subcommands=True)
373
+ install.root = self.bdist_dir
374
+ install.compile = False
375
+ install.skip_build = self.skip_build
376
+ install.warn_dir = False
377
+
378
+ # A wheel without setuptools scripts is more cross-platform.
379
+ # Use the (undocumented) `no_ep` option to setuptools'
380
+ # install_scripts command to avoid creating entry point scripts.
381
+ install_scripts = self.reinitialize_command("install_scripts")
382
+ install_scripts.no_ep = True
383
+
384
+ # Use a custom scheme for the archive, because we have to decide
385
+ # at installation time which scheme to use.
386
+ for key in ("headers", "scripts", "data", "purelib", "platlib"):
387
+ setattr(install, "install_" + key, os.path.join(self.data_dir, key))
388
+
389
+ basedir_observed = ""
390
+
391
+ if os.name == "nt":
392
+ # win32 barfs if any of these are ''; could be '.'?
393
+ # (distutils.command.install:change_roots bug)
394
+ basedir_observed = os.path.normpath(os.path.join(self.data_dir, ".."))
395
+ self.install_libbase = self.install_lib = basedir_observed
396
+
397
+ setattr(
398
+ install,
399
+ "install_purelib" if self.root_is_pure else "install_platlib",
400
+ basedir_observed,
401
+ )
402
+
403
+ log.info(f"installing to {self.bdist_dir}")
404
+
405
+ self.run_command("install")
406
+
407
+ impl_tag, abi_tag, plat_tag = self.get_tag()
408
+ archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
409
+ if not self.relative:
410
+ archive_root = self.bdist_dir
411
+ else:
412
+ archive_root = os.path.join(
413
+ self.bdist_dir, self._ensure_relative(install.install_base)
414
+ )
415
+
416
+ self.set_undefined_options("install_egg_info", ("target", "egginfo_dir"))
417
+ distinfo_dirname = (
418
+ f"{safer_name(self.distribution.get_name())}-"
419
+ f"{safer_version(self.distribution.get_version())}.dist-info"
420
+ )
421
+ distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
422
+ if self.dist_info_dir:
423
+ # Use the given dist-info directly.
424
+ log.debug(f"reusing {self.dist_info_dir}")
425
+ shutil.copytree(self.dist_info_dir, distinfo_dir)
426
+ # Egg info is still generated, so remove it now to avoid it getting
427
+ # copied into the wheel.
428
+ _shutil.rmtree(self.egginfo_dir)
429
+ else:
430
+ # Convert the generated egg-info into dist-info.
431
+ self.egg2dist(self.egginfo_dir, distinfo_dir)
432
+
433
+ self.write_wheelfile(distinfo_dir)
434
+
435
+ # Make the archive
436
+ if not os.path.exists(self.dist_dir):
437
+ os.makedirs(self.dist_dir)
438
+
439
+ wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
440
+ with WheelFile(wheel_path, "w", self._zip_compression()) as wf:
441
+ wf.write_files(archive_root)
442
+
443
+ # Add to 'Distribution.dist_files' so that the "upload" command works
444
+ getattr(self.distribution, "dist_files", []).append((
445
+ "bdist_wheel",
446
+ f"{sys.version_info.major}.{sys.version_info.minor}",
447
+ wheel_path,
448
+ ))
449
+
450
+ if not self.keep_temp:
451
+ log.info(f"removing {self.bdist_dir}")
452
+ if not self.dry_run:
453
+ _shutil.rmtree(self.bdist_dir)
454
+
455
+ def write_wheelfile(
456
+ self, wheelfile_base: str, generator: str = f"setuptools ({__version__})"
457
+ ) -> None:
458
+ from email.message import Message
459
+
460
+ msg = Message()
461
+ msg["Wheel-Version"] = "1.0" # of the spec
462
+ msg["Generator"] = generator
463
+ msg["Root-Is-Purelib"] = str(self.root_is_pure).lower()
464
+ if self.build_number is not None:
465
+ msg["Build"] = self.build_number
466
+
467
+ # Doesn't work for bdist_wininst
468
+ impl_tag, abi_tag, plat_tag = self.get_tag()
469
+ for impl in impl_tag.split("."):
470
+ for abi in abi_tag.split("."):
471
+ for plat in plat_tag.split("."):
472
+ msg["Tag"] = "-".join((impl, abi, plat))
473
+
474
+ wheelfile_path = os.path.join(wheelfile_base, "WHEEL")
475
+ log.info(f"creating {wheelfile_path}")
476
+ with open(wheelfile_path, "wb") as f:
477
+ BytesGenerator(f, maxheaderlen=0).flatten(msg)
478
+
479
+ def _ensure_relative(self, path: str) -> str:
480
+ # copied from dir_util, deleted
481
+ drive, path = os.path.splitdrive(path)
482
+ if path[0:1] == os.sep:
483
+ path = drive + path[1:]
484
+ return path
485
+
486
+ @property
487
+ def license_paths(self) -> Iterable[str]:
488
+ if setuptools_major_version >= 57:
489
+ # Setuptools has resolved any patterns to actual file names
490
+ return self.distribution.metadata.license_files or ()
491
+
492
+ files = set[str]()
493
+ metadata = self.distribution.get_option_dict("metadata")
494
+ if setuptools_major_version >= 42:
495
+ # Setuptools recognizes the license_files option but does not do globbing
496
+ patterns = cast(Sequence[str], self.distribution.metadata.license_files)
497
+ else:
498
+ # Prior to those, wheel is entirely responsible for handling license files
499
+ if "license_files" in metadata:
500
+ patterns = metadata["license_files"][1].split()
501
+ else:
502
+ patterns = ()
503
+
504
+ if "license_file" in metadata:
505
+ warnings.warn(
506
+ 'The "license_file" option is deprecated. Use "license_files" instead.',
507
+ DeprecationWarning,
508
+ stacklevel=2,
509
+ )
510
+ files.add(metadata["license_file"][1])
511
+
512
+ if not files and not patterns and not isinstance(patterns, list):
513
+ patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*")
514
+
515
+ for pattern in patterns:
516
+ for path in iglob(pattern):
517
+ if path.endswith("~"):
518
+ log.debug(
519
+ f'ignoring license file "{path}" as it looks like a backup'
520
+ )
521
+ continue
522
+
523
+ if path not in files and os.path.isfile(path):
524
+ log.info(
525
+ f'adding license file "{path}" (matched pattern "{pattern}")'
526
+ )
527
+ files.add(path)
528
+
529
+ return files
530
+
531
+ def egg2dist(self, egginfo_path: str, distinfo_path: str) -> None:
532
+ """Convert an .egg-info directory into a .dist-info directory"""
533
+
534
+ def adios(p: str) -> None:
535
+ """Appropriately delete directory, file or link."""
536
+ if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
537
+ _shutil.rmtree(p)
538
+ elif os.path.exists(p):
539
+ os.unlink(p)
540
+
541
+ adios(distinfo_path)
542
+
543
+ if not os.path.exists(egginfo_path):
544
+ # There is no egg-info. This is probably because the egg-info
545
+ # file/directory is not named matching the distribution name used
546
+ # to name the archive file. Check for this case and report
547
+ # accordingly.
548
+ import glob
549
+
550
+ pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info")
551
+ possible = glob.glob(pat)
552
+ err = f"Egg metadata expected at {egginfo_path} but not found"
553
+ if possible:
554
+ alt = os.path.basename(possible[0])
555
+ err += f" ({alt} found - possible misnamed archive file?)"
556
+
557
+ raise ValueError(err)
558
+
559
+ # .egg-info is a directory
560
+ pkginfo_path = os.path.join(egginfo_path, "PKG-INFO")
561
+
562
+ # ignore common egg metadata that is useless to wheel
563
+ shutil.copytree(
564
+ egginfo_path,
565
+ distinfo_path,
566
+ ignore=lambda x, y: {
567
+ "PKG-INFO",
568
+ "requires.txt",
569
+ "SOURCES.txt",
570
+ "not-zip-safe",
571
+ },
572
+ )
573
+
574
+ # delete dependency_links if it is only whitespace
575
+ dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt")
576
+ with open(dependency_links_path, encoding="utf-8") as dependency_links_file:
577
+ dependency_links = dependency_links_file.read().strip()
578
+ if not dependency_links:
579
+ adios(dependency_links_path)
580
+
581
+ metadata_path = os.path.join(distinfo_path, "METADATA")
582
+ shutil.copy(pkginfo_path, metadata_path)
583
+
584
+ licenses_folder_path = os.path.join(distinfo_path, "licenses")
585
+ for license_path in self.license_paths:
586
+ safe_path = _safe_license_file(license_path)
587
+ dist_info_license_path = os.path.join(licenses_folder_path, safe_path)
588
+ os.makedirs(os.path.dirname(dist_info_license_path), exist_ok=True)
589
+ shutil.copy(license_path, dist_info_license_path)
590
+
591
+ adios(egginfo_path)
592
+
593
+ def _zip_compression(self) -> int:
594
+ if (
595
+ isinstance(self.compression, int)
596
+ and self.compression in self.supported_compressions.values()
597
+ ):
598
+ return self.compression
599
+
600
+ compression = self.supported_compressions.get(str(self.compression))
601
+ if compression is not None:
602
+ return compression
603
+
604
+ raise ValueError(f"Unsupported compression: {self.compression!r}")
python_embeded/Lib/site-packages/setuptools/command/build.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Protocol
4
+
5
+ from ..dist import Distribution
6
+
7
+ from distutils.command.build import build as _build
8
+
9
+ _ORIGINAL_SUBCOMMANDS = {"build_py", "build_clib", "build_ext", "build_scripts"}
10
+
11
+
12
+ class build(_build):
13
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
14
+
15
+ # copy to avoid sharing the object with parent class
16
+ sub_commands = _build.sub_commands[:]
17
+
18
+
19
+ class SubCommand(Protocol):
20
+ """In order to support editable installations (see :pep:`660`) all
21
+ build subcommands **SHOULD** implement this protocol. They also **MUST** inherit
22
+ from ``setuptools.Command``.
23
+
24
+ When creating an :pep:`editable wheel <660>`, ``setuptools`` will try to evaluate
25
+ custom ``build`` subcommands using the following procedure:
26
+
27
+ 1. ``setuptools`` will set the ``editable_mode`` attribute to ``True``
28
+ 2. ``setuptools`` will execute the ``run()`` command.
29
+
30
+ .. important::
31
+ Subcommands **SHOULD** take advantage of ``editable_mode=True`` to adequate
32
+ its behaviour or perform optimisations.
33
+
34
+ For example, if a subcommand doesn't need to generate an extra file and
35
+ all it does is to copy a source file into the build directory,
36
+ ``run()`` **SHOULD** simply "early return".
37
+
38
+ Similarly, if the subcommand creates files that would be placed alongside
39
+ Python files in the final distribution, during an editable install
40
+ the command **SHOULD** generate these files "in place" (i.e. write them to
41
+ the original source directory, instead of using the build directory).
42
+ Note that ``get_output_mapping()`` should reflect that and include mappings
43
+ for "in place" builds accordingly.
44
+
45
+ 3. ``setuptools`` use any knowledge it can derive from the return values of
46
+ ``get_outputs()`` and ``get_output_mapping()`` to create an editable wheel.
47
+ When relevant ``setuptools`` **MAY** attempt to use file links based on the value
48
+ of ``get_output_mapping()``. Alternatively, ``setuptools`` **MAY** attempt to use
49
+ :doc:`import hooks <python:reference/import>` to redirect any attempt to import
50
+ to the directory with the original source code and other files built in place.
51
+
52
+ Please note that custom sub-commands **SHOULD NOT** rely on ``run()`` being
53
+ executed (or not) to provide correct return values for ``get_outputs()``,
54
+ ``get_output_mapping()`` or ``get_source_files()``. The ``get_*`` methods should
55
+ work independently of ``run()``.
56
+ """
57
+
58
+ editable_mode: bool = False
59
+ """Boolean flag that will be set to ``True`` when setuptools is used for an
60
+ editable installation (see :pep:`660`).
61
+ Implementations **SHOULD** explicitly set the default value of this attribute to
62
+ ``False``.
63
+ When subcommands run, they can use this flag to perform optimizations or change
64
+ their behaviour accordingly.
65
+ """
66
+
67
+ build_lib: str
68
+ """String representing the directory where the build artifacts should be stored,
69
+ e.g. ``build/lib``.
70
+ For example, if a distribution wants to provide a Python module named ``pkg.mod``,
71
+ then a corresponding file should be written to ``{build_lib}/package/module.py``.
72
+ A way of thinking about this is that the files saved under ``build_lib``
73
+ would be eventually copied to one of the directories in :obj:`site.PREFIXES`
74
+ upon installation.
75
+
76
+ A command that produces platform-independent files (e.g. compiling text templates
77
+ into Python functions), **CAN** initialize ``build_lib`` by copying its value from
78
+ the ``build_py`` command. On the other hand, a command that produces
79
+ platform-specific files **CAN** initialize ``build_lib`` by copying its value from
80
+ the ``build_ext`` command. In general this is done inside the ``finalize_options``
81
+ method with the help of the ``set_undefined_options`` command::
82
+
83
+ def finalize_options(self):
84
+ self.set_undefined_options("build_py", ("build_lib", "build_lib"))
85
+ ...
86
+ """
87
+
88
+ def initialize_options(self) -> None:
89
+ """(Required by the original :class:`setuptools.Command` interface)"""
90
+ ...
91
+
92
+ def finalize_options(self) -> None:
93
+ """(Required by the original :class:`setuptools.Command` interface)"""
94
+ ...
95
+
96
+ def run(self) -> None:
97
+ """(Required by the original :class:`setuptools.Command` interface)"""
98
+ ...
99
+
100
+ def get_source_files(self) -> list[str]:
101
+ """
102
+ Return a list of all files that are used by the command to create the expected
103
+ outputs.
104
+ For example, if your build command transpiles Java files into Python, you should
105
+ list here all the Java files.
106
+ The primary purpose of this function is to help populating the ``sdist``
107
+ with all the files necessary to build the distribution.
108
+ All files should be strings relative to the project root directory.
109
+ """
110
+ ...
111
+
112
+ def get_outputs(self) -> list[str]:
113
+ """
114
+ Return a list of files intended for distribution as they would have been
115
+ produced by the build.
116
+ These files should be strings in the form of
117
+ ``"{build_lib}/destination/file/path"``.
118
+
119
+ .. note::
120
+ The return value of ``get_output()`` should include all files used as keys
121
+ in ``get_output_mapping()`` plus files that are generated during the build
122
+ and don't correspond to any source file already present in the project.
123
+ """
124
+ ...
125
+
126
+ def get_output_mapping(self) -> dict[str, str]:
127
+ """
128
+ Return a mapping between destination files as they would be produced by the
129
+ build (dict keys) into the respective existing (source) files (dict values).
130
+ Existing (source) files should be represented as strings relative to the project
131
+ root directory.
132
+ Destination files should be strings in the form of
133
+ ``"{build_lib}/destination/file/path"``.
134
+ """
135
+ ...
python_embeded/Lib/site-packages/setuptools/command/build_clib.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..dist import Distribution
2
+ from ..modified import newer_pairwise_group
3
+
4
+ import distutils.command.build_clib as orig
5
+ from distutils import log
6
+ from distutils.errors import DistutilsSetupError
7
+
8
+
9
+ class build_clib(orig.build_clib):
10
+ """
11
+ Override the default build_clib behaviour to do the following:
12
+
13
+ 1. Implement a rudimentary timestamp-based dependency system
14
+ so 'compile()' doesn't run every time.
15
+ 2. Add more keys to the 'build_info' dictionary:
16
+ * obj_deps - specify dependencies for each object compiled.
17
+ this should be a dictionary mapping a key
18
+ with the source filename to a list of
19
+ dependencies. Use an empty string for global
20
+ dependencies.
21
+ * cflags - specify a list of additional flags to pass to
22
+ the compiler.
23
+ """
24
+
25
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
26
+
27
+ def build_libraries(self, libraries) -> None:
28
+ for lib_name, build_info in libraries:
29
+ sources = build_info.get('sources')
30
+ if sources is None or not isinstance(sources, (list, tuple)):
31
+ raise DistutilsSetupError(
32
+ f"in 'libraries' option (library '{lib_name}'), "
33
+ "'sources' must be present and must be "
34
+ "a list of source filenames"
35
+ )
36
+ sources = sorted(list(sources))
37
+
38
+ log.info("building '%s' library", lib_name)
39
+
40
+ # Make sure everything is the correct type.
41
+ # obj_deps should be a dictionary of keys as sources
42
+ # and a list/tuple of files that are its dependencies.
43
+ obj_deps = build_info.get('obj_deps', dict())
44
+ if not isinstance(obj_deps, dict):
45
+ raise DistutilsSetupError(
46
+ f"in 'libraries' option (library '{lib_name}'), "
47
+ "'obj_deps' must be a dictionary of "
48
+ "type 'source: list'"
49
+ )
50
+ dependencies = []
51
+
52
+ # Get the global dependencies that are specified by the '' key.
53
+ # These will go into every source's dependency list.
54
+ global_deps = obj_deps.get('', list())
55
+ if not isinstance(global_deps, (list, tuple)):
56
+ raise DistutilsSetupError(
57
+ f"in 'libraries' option (library '{lib_name}'), "
58
+ "'obj_deps' must be a dictionary of "
59
+ "type 'source: list'"
60
+ )
61
+
62
+ # Build the list to be used by newer_pairwise_group
63
+ # each source will be auto-added to its dependencies.
64
+ for source in sources:
65
+ src_deps = [source]
66
+ src_deps.extend(global_deps)
67
+ extra_deps = obj_deps.get(source, list())
68
+ if not isinstance(extra_deps, (list, tuple)):
69
+ raise DistutilsSetupError(
70
+ f"in 'libraries' option (library '{lib_name}'), "
71
+ "'obj_deps' must be a dictionary of "
72
+ "type 'source: list'"
73
+ )
74
+ src_deps.extend(extra_deps)
75
+ dependencies.append(src_deps)
76
+
77
+ expected_objects = self.compiler.object_filenames(
78
+ sources,
79
+ output_dir=self.build_temp,
80
+ )
81
+
82
+ if newer_pairwise_group(dependencies, expected_objects) != ([], []):
83
+ # First, compile the source code to object files in the library
84
+ # directory. (This should probably change to putting object
85
+ # files in a temporary build directory.)
86
+ macros = build_info.get('macros')
87
+ include_dirs = build_info.get('include_dirs')
88
+ cflags = build_info.get('cflags')
89
+ self.compiler.compile(
90
+ sources,
91
+ output_dir=self.build_temp,
92
+ macros=macros,
93
+ include_dirs=include_dirs,
94
+ extra_postargs=cflags,
95
+ debug=self.debug,
96
+ )
97
+
98
+ # Now "link" the object files together into a static library.
99
+ # (On Unix at least, this isn't really linking -- it just
100
+ # builds an archive. Whatever.)
101
+ self.compiler.create_static_lib(
102
+ expected_objects, lib_name, output_dir=self.build_clib, debug=self.debug
103
+ )
python_embeded/Lib/site-packages/setuptools/command/build_ext.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import os
5
+ import sys
6
+ import textwrap
7
+ from collections.abc import Iterator
8
+ from importlib.machinery import EXTENSION_SUFFIXES
9
+ from importlib.util import cache_from_source as _compiled_file_name
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING
12
+
13
+ from setuptools.dist import Distribution
14
+ from setuptools.errors import BaseError
15
+ from setuptools.extension import Extension, Library
16
+
17
+ from distutils import log
18
+ from distutils.ccompiler import new_compiler
19
+ from distutils.sysconfig import customize_compiler, get_config_var
20
+
21
+ if TYPE_CHECKING:
22
+ # Cython not installed on CI tests, causing _build_ext to be `Any`
23
+ from distutils.command.build_ext import build_ext as _build_ext
24
+ else:
25
+ try:
26
+ # Attempt to use Cython for building extensions, if available
27
+ from Cython.Distutils.build_ext import build_ext as _build_ext
28
+
29
+ # Additionally, assert that the compiler module will load
30
+ # also. Ref #1229.
31
+ __import__('Cython.Compiler.Main')
32
+ except ImportError:
33
+ from distutils.command.build_ext import build_ext as _build_ext
34
+
35
+ # make sure _config_vars is initialized
36
+ get_config_var("LDSHARED")
37
+ # Not publicly exposed in typeshed distutils stubs, but this is done on purpose
38
+ # See https://github.com/pypa/setuptools/pull/4228#issuecomment-1959856400
39
+ from distutils.sysconfig import _config_vars as _CONFIG_VARS # noqa: E402
40
+
41
+
42
+ def _customize_compiler_for_shlib(compiler):
43
+ if sys.platform == "darwin":
44
+ # building .dylib requires additional compiler flags on OSX; here we
45
+ # temporarily substitute the pyconfig.h variables so that distutils'
46
+ # 'customize_compiler' uses them before we build the shared libraries.
47
+ tmp = _CONFIG_VARS.copy()
48
+ try:
49
+ # XXX Help! I don't have any idea whether these are right...
50
+ _CONFIG_VARS['LDSHARED'] = (
51
+ "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup"
52
+ )
53
+ _CONFIG_VARS['CCSHARED'] = " -dynamiclib"
54
+ _CONFIG_VARS['SO'] = ".dylib"
55
+ customize_compiler(compiler)
56
+ finally:
57
+ _CONFIG_VARS.clear()
58
+ _CONFIG_VARS.update(tmp)
59
+ else:
60
+ customize_compiler(compiler)
61
+
62
+
63
+ have_rtld = False
64
+ use_stubs = False
65
+ libtype = 'shared'
66
+
67
+ if sys.platform == "darwin":
68
+ use_stubs = True
69
+ elif os.name != 'nt':
70
+ try:
71
+ import dl # type: ignore[import-not-found] # https://github.com/python/mypy/issues/13002
72
+
73
+ use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
74
+ except ImportError:
75
+ pass
76
+
77
+
78
+ def get_abi3_suffix():
79
+ """Return the file extension for an abi3-compliant Extension()"""
80
+ for suffix in EXTENSION_SUFFIXES:
81
+ if '.abi3' in suffix: # Unix
82
+ return suffix
83
+ elif suffix == '.pyd': # Windows
84
+ return suffix
85
+ return None
86
+
87
+
88
+ class build_ext(_build_ext):
89
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
90
+ editable_mode = False
91
+ inplace = False
92
+
93
+ def run(self):
94
+ """Build extensions in build directory, then copy if --inplace"""
95
+ old_inplace, self.inplace = self.inplace, False
96
+ _build_ext.run(self)
97
+ self.inplace = old_inplace
98
+ if old_inplace:
99
+ self.copy_extensions_to_source()
100
+
101
+ def _get_inplace_equivalent(self, build_py, ext: Extension) -> tuple[str, str]:
102
+ fullname = self.get_ext_fullname(ext.name)
103
+ filename = self.get_ext_filename(fullname)
104
+ modpath = fullname.split('.')
105
+ package = '.'.join(modpath[:-1])
106
+ package_dir = build_py.get_package_dir(package)
107
+ inplace_file = os.path.join(package_dir, os.path.basename(filename))
108
+ regular_file = os.path.join(self.build_lib, filename)
109
+ return (inplace_file, regular_file)
110
+
111
+ def copy_extensions_to_source(self) -> None:
112
+ build_py = self.get_finalized_command('build_py')
113
+ for ext in self.extensions:
114
+ inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)
115
+
116
+ # Always copy, even if source is older than destination, to ensure
117
+ # that the right extensions for the current Python/platform are
118
+ # used.
119
+ if os.path.exists(regular_file) or not ext.optional:
120
+ self.copy_file(regular_file, inplace_file, level=self.verbose)
121
+
122
+ if ext._needs_stub:
123
+ inplace_stub = self._get_equivalent_stub(ext, inplace_file)
124
+ self._write_stub_file(inplace_stub, ext, compile=True)
125
+ # Always compile stub and remove the original (leave the cache behind)
126
+ # (this behaviour was observed in previous iterations of the code)
127
+
128
+ def _get_equivalent_stub(self, ext: Extension, output_file: str) -> str:
129
+ dir_ = os.path.dirname(output_file)
130
+ _, _, name = ext.name.rpartition(".")
131
+ return f"{os.path.join(dir_, name)}.py"
132
+
133
+ def _get_output_mapping(self) -> Iterator[tuple[str, str]]:
134
+ if not self.inplace:
135
+ return
136
+
137
+ build_py = self.get_finalized_command('build_py')
138
+ opt = self.get_finalized_command('install_lib').optimize or ""
139
+
140
+ for ext in self.extensions:
141
+ inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)
142
+ yield (regular_file, inplace_file)
143
+
144
+ if ext._needs_stub:
145
+ # This version of `build_ext` always builds artifacts in another dir,
146
+ # when "inplace=True" is given it just copies them back.
147
+ # This is done in the `copy_extensions_to_source` function, which
148
+ # always compile stub files via `_compile_and_remove_stub`.
149
+ # At the end of the process, a `.pyc` stub file is created without the
150
+ # corresponding `.py`.
151
+
152
+ inplace_stub = self._get_equivalent_stub(ext, inplace_file)
153
+ regular_stub = self._get_equivalent_stub(ext, regular_file)
154
+ inplace_cache = _compiled_file_name(inplace_stub, optimization=opt)
155
+ output_cache = _compiled_file_name(regular_stub, optimization=opt)
156
+ yield (output_cache, inplace_cache)
157
+
158
+ def get_ext_filename(self, fullname: str) -> str:
159
+ so_ext = os.getenv('SETUPTOOLS_EXT_SUFFIX')
160
+ if so_ext:
161
+ filename = os.path.join(*fullname.split('.')) + so_ext
162
+ else:
163
+ filename = _build_ext.get_ext_filename(self, fullname)
164
+ ext_suffix = get_config_var('EXT_SUFFIX')
165
+ if not isinstance(ext_suffix, str):
166
+ raise OSError(
167
+ "Configuration variable EXT_SUFFIX not found for this platform "
168
+ "and environment variable SETUPTOOLS_EXT_SUFFIX is missing"
169
+ )
170
+ so_ext = ext_suffix
171
+
172
+ if fullname in self.ext_map:
173
+ ext = self.ext_map[fullname]
174
+ abi3_suffix = get_abi3_suffix()
175
+ if ext.py_limited_api and abi3_suffix: # Use abi3
176
+ filename = filename[: -len(so_ext)] + abi3_suffix
177
+ if isinstance(ext, Library):
178
+ fn, ext = os.path.splitext(filename)
179
+ return self.shlib_compiler.library_filename(fn, libtype)
180
+ elif use_stubs and ext._links_to_dynamic:
181
+ d, fn = os.path.split(filename)
182
+ return os.path.join(d, 'dl-' + fn)
183
+ return filename
184
+
185
+ def initialize_options(self):
186
+ _build_ext.initialize_options(self)
187
+ self.shlib_compiler = None
188
+ self.shlibs = []
189
+ self.ext_map = {}
190
+ self.editable_mode = False
191
+
192
+ def finalize_options(self) -> None:
193
+ _build_ext.finalize_options(self)
194
+ self.extensions = self.extensions or []
195
+ self.check_extensions_list(self.extensions)
196
+ self.shlibs = [ext for ext in self.extensions if isinstance(ext, Library)]
197
+ if self.shlibs:
198
+ self.setup_shlib_compiler()
199
+ for ext in self.extensions:
200
+ ext._full_name = self.get_ext_fullname(ext.name)
201
+ for ext in self.extensions:
202
+ fullname = ext._full_name
203
+ self.ext_map[fullname] = ext
204
+
205
+ # distutils 3.1 will also ask for module names
206
+ # XXX what to do with conflicts?
207
+ self.ext_map[fullname.split('.')[-1]] = ext
208
+
209
+ ltd = self.shlibs and self.links_to_dynamic(ext) or False
210
+ ns = ltd and use_stubs and not isinstance(ext, Library)
211
+ ext._links_to_dynamic = ltd
212
+ ext._needs_stub = ns
213
+ filename = ext._file_name = self.get_ext_filename(fullname)
214
+ libdir = os.path.dirname(os.path.join(self.build_lib, filename))
215
+ if ltd and libdir not in ext.library_dirs:
216
+ ext.library_dirs.append(libdir)
217
+ if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
218
+ ext.runtime_library_dirs.append(os.curdir)
219
+
220
+ if self.editable_mode:
221
+ self.inplace = True
222
+
223
+ def setup_shlib_compiler(self):
224
+ compiler = self.shlib_compiler = new_compiler(
225
+ compiler=self.compiler, dry_run=self.dry_run, force=self.force
226
+ )
227
+ _customize_compiler_for_shlib(compiler)
228
+
229
+ if self.include_dirs is not None:
230
+ compiler.set_include_dirs(self.include_dirs)
231
+ if self.define is not None:
232
+ # 'define' option is a list of (name,value) tuples
233
+ for name, value in self.define:
234
+ compiler.define_macro(name, value)
235
+ if self.undef is not None:
236
+ for macro in self.undef:
237
+ compiler.undefine_macro(macro)
238
+ if self.libraries is not None:
239
+ compiler.set_libraries(self.libraries)
240
+ if self.library_dirs is not None:
241
+ compiler.set_library_dirs(self.library_dirs)
242
+ if self.rpath is not None:
243
+ compiler.set_runtime_library_dirs(self.rpath)
244
+ if self.link_objects is not None:
245
+ compiler.set_link_objects(self.link_objects)
246
+
247
+ # hack so distutils' build_extension() builds a library instead
248
+ compiler.link_shared_object = link_shared_object.__get__(compiler) # type: ignore[method-assign]
249
+
250
+ def get_export_symbols(self, ext):
251
+ if isinstance(ext, Library):
252
+ return ext.export_symbols
253
+ return _build_ext.get_export_symbols(self, ext)
254
+
255
+ def build_extension(self, ext) -> None:
256
+ ext._convert_pyx_sources_to_lang()
257
+ _compiler = self.compiler
258
+ try:
259
+ if isinstance(ext, Library):
260
+ self.compiler = self.shlib_compiler
261
+ _build_ext.build_extension(self, ext)
262
+ if ext._needs_stub:
263
+ build_lib = self.get_finalized_command('build_py').build_lib
264
+ self.write_stub(build_lib, ext)
265
+ finally:
266
+ self.compiler = _compiler
267
+
268
+ def links_to_dynamic(self, ext):
269
+ """Return true if 'ext' links to a dynamic lib in the same package"""
270
+ # XXX this should check to ensure the lib is actually being built
271
+ # XXX as dynamic, and not just using a locally-found version or a
272
+ # XXX static-compiled version
273
+ libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
274
+ pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
275
+ return any(pkg + libname in libnames for libname in ext.libraries)
276
+
277
+ def get_source_files(self) -> list[str]:
278
+ return [*_build_ext.get_source_files(self), *self._get_internal_depends()]
279
+
280
+ def _get_internal_depends(self) -> Iterator[str]:
281
+ """Yield ``ext.depends`` that are contained by the project directory"""
282
+ project_root = Path(self.distribution.src_root or os.curdir).resolve()
283
+ depends = (dep for ext in self.extensions for dep in ext.depends)
284
+
285
+ def skip(orig_path: str, reason: str) -> None:
286
+ log.info(
287
+ "dependency %s won't be automatically "
288
+ "included in the manifest: the path %s",
289
+ orig_path,
290
+ reason,
291
+ )
292
+
293
+ for dep in depends:
294
+ path = Path(dep)
295
+
296
+ if path.is_absolute():
297
+ skip(dep, "must be relative")
298
+ continue
299
+
300
+ if ".." in path.parts:
301
+ skip(dep, "can't have `..` segments")
302
+ continue
303
+
304
+ try:
305
+ resolved = (project_root / path).resolve(strict=True)
306
+ except OSError:
307
+ skip(dep, "doesn't exist")
308
+ continue
309
+
310
+ try:
311
+ resolved.relative_to(project_root)
312
+ except ValueError:
313
+ skip(dep, "must be inside the project root")
314
+ continue
315
+
316
+ yield path.as_posix()
317
+
318
+ def get_outputs(self) -> list[str]:
319
+ if self.inplace:
320
+ return list(self.get_output_mapping().keys())
321
+ return sorted(_build_ext.get_outputs(self) + self.__get_stubs_outputs())
322
+
323
+ def get_output_mapping(self) -> dict[str, str]:
324
+ """See :class:`setuptools.commands.build.SubCommand`"""
325
+ mapping = self._get_output_mapping()
326
+ return dict(sorted(mapping, key=lambda x: x[0]))
327
+
328
+ def __get_stubs_outputs(self):
329
+ # assemble the base name for each extension that needs a stub
330
+ ns_ext_bases = (
331
+ os.path.join(self.build_lib, *ext._full_name.split('.'))
332
+ for ext in self.extensions
333
+ if ext._needs_stub
334
+ )
335
+ # pair each base with the extension
336
+ pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
337
+ return list(base + fnext for base, fnext in pairs)
338
+
339
+ def __get_output_extensions(self):
340
+ yield '.py'
341
+ yield '.pyc'
342
+ if self.get_finalized_command('build_py').optimize:
343
+ yield '.pyo'
344
+
345
+ def write_stub(self, output_dir, ext, compile=False) -> None:
346
+ stub_file = os.path.join(output_dir, *ext._full_name.split('.')) + '.py'
347
+ self._write_stub_file(stub_file, ext, compile)
348
+
349
+ def _write_stub_file(self, stub_file: str, ext: Extension, compile=False):
350
+ log.info("writing stub loader for %s to %s", ext._full_name, stub_file)
351
+ if compile and os.path.exists(stub_file):
352
+ raise BaseError(stub_file + " already exists! Please delete.")
353
+ if not self.dry_run:
354
+ with open(stub_file, 'w', encoding="utf-8") as f:
355
+ content = (
356
+ textwrap.dedent(f"""
357
+ def __bootstrap__():
358
+ global __bootstrap__, __file__, __loader__
359
+ import sys, os, importlib.resources as irs, importlib.util
360
+ #rtld import dl
361
+ with irs.files(__name__).joinpath(
362
+ {os.path.basename(ext._file_name)!r}) as __file__:
363
+ del __bootstrap__
364
+ if '__loader__' in globals():
365
+ del __loader__
366
+ #rtld old_flags = sys.getdlopenflags()
367
+ old_dir = os.getcwd()
368
+ try:
369
+ os.chdir(os.path.dirname(__file__))
370
+ #rtld sys.setdlopenflags(dl.RTLD_NOW)
371
+ spec = importlib.util.spec_from_file_location(
372
+ __name__, __file__)
373
+ mod = importlib.util.module_from_spec(spec)
374
+ spec.loader.exec_module(mod)
375
+ finally:
376
+ #rtld sys.setdlopenflags(old_flags)
377
+ os.chdir(old_dir)
378
+ __bootstrap__()
379
+ """)
380
+ .lstrip()
381
+ .replace('#rtld', '#rtld' * (not have_rtld))
382
+ )
383
+ f.write(content)
384
+ if compile:
385
+ self._compile_and_remove_stub(stub_file)
386
+
387
+ def _compile_and_remove_stub(self, stub_file: str):
388
+ from distutils.util import byte_compile
389
+
390
+ byte_compile([stub_file], optimize=0, force=True, dry_run=self.dry_run)
391
+ optimize = self.get_finalized_command('install_lib').optimize
392
+ if optimize > 0:
393
+ byte_compile(
394
+ [stub_file],
395
+ optimize=optimize,
396
+ force=True,
397
+ dry_run=self.dry_run,
398
+ )
399
+ if os.path.exists(stub_file) and not self.dry_run:
400
+ os.unlink(stub_file)
401
+
402
+
403
+ if use_stubs or os.name == 'nt':
404
+ # Build shared libraries
405
+ #
406
+ def link_shared_object(
407
+ self,
408
+ objects,
409
+ output_libname,
410
+ output_dir=None,
411
+ libraries=None,
412
+ library_dirs=None,
413
+ runtime_library_dirs=None,
414
+ export_symbols=None,
415
+ debug: bool = False,
416
+ extra_preargs=None,
417
+ extra_postargs=None,
418
+ build_temp=None,
419
+ target_lang=None,
420
+ ) -> None:
421
+ self.link(
422
+ self.SHARED_LIBRARY,
423
+ objects,
424
+ output_libname,
425
+ output_dir,
426
+ libraries,
427
+ library_dirs,
428
+ runtime_library_dirs,
429
+ export_symbols,
430
+ debug,
431
+ extra_preargs,
432
+ extra_postargs,
433
+ build_temp,
434
+ target_lang,
435
+ )
436
+
437
+ else:
438
+ # Build static libraries everywhere else
439
+ libtype = 'static'
440
+
441
+ def link_shared_object(
442
+ self,
443
+ objects,
444
+ output_libname,
445
+ output_dir=None,
446
+ libraries=None,
447
+ library_dirs=None,
448
+ runtime_library_dirs=None,
449
+ export_symbols=None,
450
+ debug: bool = False,
451
+ extra_preargs=None,
452
+ extra_postargs=None,
453
+ build_temp=None,
454
+ target_lang=None,
455
+ ) -> None:
456
+ # XXX we need to either disallow these attrs on Library instances,
457
+ # or warn/abort here if set, or something...
458
+ # libraries=None, library_dirs=None, runtime_library_dirs=None,
459
+ # export_symbols=None, extra_preargs=None, extra_postargs=None,
460
+ # build_temp=None
461
+
462
+ assert output_dir is None # distutils build_ext doesn't pass this
463
+ output_dir, filename = os.path.split(output_libname)
464
+ basename, _ext = os.path.splitext(filename)
465
+ if self.library_filename("x").startswith('lib'):
466
+ # strip 'lib' prefix; this is kludgy if some platform uses
467
+ # a different prefix
468
+ basename = basename[3:]
469
+
470
+ self.create_static_lib(objects, basename, output_dir, debug, target_lang)
python_embeded/Lib/site-packages/setuptools/command/build_py.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import fnmatch
4
+ import itertools
5
+ import os
6
+ import stat
7
+ import textwrap
8
+ from collections.abc import Iterable, Iterator
9
+ from functools import partial
10
+ from glob import glob
11
+ from pathlib import Path
12
+
13
+ from more_itertools import unique_everseen
14
+
15
+ from .._path import StrPath, StrPathT
16
+ from ..dist import Distribution
17
+ from ..warnings import SetuptoolsDeprecationWarning
18
+
19
+ import distutils.command.build_py as orig
20
+ import distutils.errors
21
+ from distutils.util import convert_path
22
+
23
+ _IMPLICIT_DATA_FILES = ('*.pyi', 'py.typed')
24
+
25
+
26
+ def make_writable(target) -> None:
27
+ os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE)
28
+
29
+
30
+ class build_py(orig.build_py):
31
+ """Enhanced 'build_py' command that includes data files with packages
32
+
33
+ The data files are specified via a 'package_data' argument to 'setup()'.
34
+ See 'setuptools.dist.Distribution' for more details.
35
+
36
+ Also, this version of the 'build_py' command allows you to specify both
37
+ 'py_modules' and 'packages' in the same setup operation.
38
+ """
39
+
40
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
41
+ editable_mode: bool = False
42
+ existing_egg_info_dir: StrPath | None = None #: Private API, internal use only.
43
+
44
+ def finalize_options(self):
45
+ orig.build_py.finalize_options(self)
46
+ self.package_data = self.distribution.package_data
47
+ self.exclude_package_data = self.distribution.exclude_package_data or {}
48
+ if 'data_files' in self.__dict__:
49
+ del self.__dict__['data_files']
50
+
51
+ def copy_file( # type: ignore[override] # No overload, no bytes support
52
+ self,
53
+ infile: StrPath,
54
+ outfile: StrPathT,
55
+ preserve_mode: bool = True,
56
+ preserve_times: bool = True,
57
+ link: str | None = None,
58
+ level: object = 1,
59
+ ) -> tuple[StrPathT | str, bool]:
60
+ # Overwrite base class to allow using links
61
+ if link:
62
+ infile = str(Path(infile).resolve())
63
+ outfile = str(Path(outfile).resolve()) # type: ignore[assignment] # Re-assigning a str when outfile is StrPath is ok
64
+ return super().copy_file( # pyright: ignore[reportReturnType] # pypa/distutils#309
65
+ infile, outfile, preserve_mode, preserve_times, link, level
66
+ )
67
+
68
+ def run(self) -> None:
69
+ """Build modules, packages, and copy data files to build directory"""
70
+ if not (self.py_modules or self.packages) or self.editable_mode:
71
+ return
72
+
73
+ if self.py_modules:
74
+ self.build_modules()
75
+
76
+ if self.packages:
77
+ self.build_packages()
78
+ self.build_package_data()
79
+
80
+ # Only compile actual .py files, using our base class' idea of what our
81
+ # output files are.
82
+ self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=False))
83
+
84
+ def __getattr__(self, attr: str):
85
+ "lazily compute data files"
86
+ if attr == 'data_files':
87
+ self.data_files = self._get_data_files()
88
+ return self.data_files
89
+ return orig.build_py.__getattr__(self, attr)
90
+
91
+ def _get_data_files(self):
92
+ """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
93
+ self.analyze_manifest()
94
+ return list(map(self._get_pkg_data_files, self.packages or ()))
95
+
96
+ def get_data_files_without_manifest(self):
97
+ """
98
+ Generate list of ``(package,src_dir,build_dir,filenames)`` tuples,
99
+ but without triggering any attempt to analyze or build the manifest.
100
+ """
101
+ # Prevent eventual errors from unset `manifest_files`
102
+ # (that would otherwise be set by `analyze_manifest`)
103
+ self.__dict__.setdefault('manifest_files', {})
104
+ return list(map(self._get_pkg_data_files, self.packages or ()))
105
+
106
+ def _get_pkg_data_files(self, package):
107
+ # Locate package source directory
108
+ src_dir = self.get_package_dir(package)
109
+
110
+ # Compute package build directory
111
+ build_dir = os.path.join(*([self.build_lib] + package.split('.')))
112
+
113
+ # Strip directory from globbed filenames
114
+ filenames = [
115
+ os.path.relpath(file, src_dir)
116
+ for file in self.find_data_files(package, src_dir)
117
+ ]
118
+ return package, src_dir, build_dir, filenames
119
+
120
+ def find_data_files(self, package, src_dir):
121
+ """Return filenames for package's data files in 'src_dir'"""
122
+ patterns = self._get_platform_patterns(
123
+ self.package_data,
124
+ package,
125
+ src_dir,
126
+ extra_patterns=_IMPLICIT_DATA_FILES,
127
+ )
128
+ globs_expanded = map(partial(glob, recursive=True), patterns)
129
+ # flatten the expanded globs into an iterable of matches
130
+ globs_matches = itertools.chain.from_iterable(globs_expanded)
131
+ glob_files = filter(os.path.isfile, globs_matches)
132
+ files = itertools.chain(
133
+ self.manifest_files.get(package, []),
134
+ glob_files,
135
+ )
136
+ return self.exclude_data_files(package, src_dir, files)
137
+
138
+ def get_outputs(self, include_bytecode: bool = True) -> list[str]: # type: ignore[override] # Using a real boolean instead of 0|1
139
+ """See :class:`setuptools.commands.build.SubCommand`"""
140
+ if self.editable_mode:
141
+ return list(self.get_output_mapping().keys())
142
+ return super().get_outputs(include_bytecode)
143
+
144
+ def get_output_mapping(self) -> dict[str, str]:
145
+ """See :class:`setuptools.commands.build.SubCommand`"""
146
+ mapping = itertools.chain(
147
+ self._get_package_data_output_mapping(),
148
+ self._get_module_mapping(),
149
+ )
150
+ return dict(sorted(mapping, key=lambda x: x[0]))
151
+
152
+ def _get_module_mapping(self) -> Iterator[tuple[str, str]]:
153
+ """Iterate over all modules producing (dest, src) pairs."""
154
+ for package, module, module_file in self.find_all_modules():
155
+ package = package.split('.')
156
+ filename = self.get_module_outfile(self.build_lib, package, module)
157
+ yield (filename, module_file)
158
+
159
+ def _get_package_data_output_mapping(self) -> Iterator[tuple[str, str]]:
160
+ """Iterate over package data producing (dest, src) pairs."""
161
+ for package, src_dir, build_dir, filenames in self.data_files:
162
+ for filename in filenames:
163
+ target = os.path.join(build_dir, filename)
164
+ srcfile = os.path.join(src_dir, filename)
165
+ yield (target, srcfile)
166
+
167
+ def build_package_data(self) -> None:
168
+ """Copy data files into build directory"""
169
+ for target, srcfile in self._get_package_data_output_mapping():
170
+ self.mkpath(os.path.dirname(target))
171
+ _outf, _copied = self.copy_file(srcfile, target)
172
+ make_writable(target)
173
+
174
+ def analyze_manifest(self) -> None:
175
+ self.manifest_files: dict[str, list[str]] = {}
176
+ if not self.distribution.include_package_data:
177
+ return
178
+ src_dirs: dict[str, str] = {}
179
+ for package in self.packages or ():
180
+ # Locate package source directory
181
+ src_dirs[assert_relative(self.get_package_dir(package))] = package
182
+
183
+ if (
184
+ self.existing_egg_info_dir
185
+ and Path(self.existing_egg_info_dir, "SOURCES.txt").exists()
186
+ ):
187
+ egg_info_dir = self.existing_egg_info_dir
188
+ manifest = Path(egg_info_dir, "SOURCES.txt")
189
+ files = manifest.read_text(encoding="utf-8").splitlines()
190
+ else:
191
+ self.run_command('egg_info')
192
+ ei_cmd = self.get_finalized_command('egg_info')
193
+ egg_info_dir = ei_cmd.egg_info
194
+ files = ei_cmd.filelist.files
195
+
196
+ check = _IncludePackageDataAbuse()
197
+ for path in self._filter_build_files(files, egg_info_dir):
198
+ d, f = os.path.split(assert_relative(path))
199
+ prev = None
200
+ oldf = f
201
+ while d and d != prev and d not in src_dirs:
202
+ prev = d
203
+ d, df = os.path.split(d)
204
+ f = os.path.join(df, f)
205
+ if d in src_dirs:
206
+ if f == oldf:
207
+ if check.is_module(f):
208
+ continue # it's a module, not data
209
+ else:
210
+ importable = check.importable_subpackage(src_dirs[d], f)
211
+ if importable:
212
+ check.warn(importable)
213
+ self.manifest_files.setdefault(src_dirs[d], []).append(path)
214
+
215
+ def _filter_build_files(
216
+ self, files: Iterable[str], egg_info: StrPath
217
+ ) -> Iterator[str]:
218
+ """
219
+ ``build_meta`` may try to create egg_info outside of the project directory,
220
+ and this can be problematic for certain plugins (reported in issue #3500).
221
+
222
+ Extensions might also include between their sources files created on the
223
+ ``build_lib`` and ``build_temp`` directories.
224
+
225
+ This function should filter this case of invalid files out.
226
+ """
227
+ build = self.get_finalized_command("build")
228
+ build_dirs = (egg_info, self.build_lib, build.build_temp, build.build_base)
229
+ norm_dirs = [os.path.normpath(p) for p in build_dirs if p]
230
+
231
+ for file in files:
232
+ norm_path = os.path.normpath(file)
233
+ if not os.path.isabs(file) or all(d not in norm_path for d in norm_dirs):
234
+ yield file
235
+
236
+ def get_data_files(self) -> None:
237
+ pass # Lazily compute data files in _get_data_files() function.
238
+
239
+ def check_package(self, package, package_dir):
240
+ """Check namespace packages' __init__ for declare_namespace"""
241
+ try:
242
+ return self.packages_checked[package]
243
+ except KeyError:
244
+ pass
245
+
246
+ init_py = orig.build_py.check_package(self, package, package_dir)
247
+ self.packages_checked[package] = init_py
248
+
249
+ if not init_py or not self.distribution.namespace_packages:
250
+ return init_py
251
+
252
+ for pkg in self.distribution.namespace_packages:
253
+ if pkg == package or pkg.startswith(package + '.'):
254
+ break
255
+ else:
256
+ return init_py
257
+
258
+ with open(init_py, 'rb') as f:
259
+ contents = f.read()
260
+ if b'declare_namespace' not in contents:
261
+ raise distutils.errors.DistutilsError(
262
+ f"Namespace package problem: {package} is a namespace package, but "
263
+ "its\n__init__.py does not call declare_namespace()! Please "
264
+ 'fix it.\n(See the setuptools manual under '
265
+ '"Namespace Packages" for details.)\n"'
266
+ )
267
+ return init_py
268
+
269
+ def initialize_options(self):
270
+ self.packages_checked = {}
271
+ orig.build_py.initialize_options(self)
272
+ self.editable_mode = False
273
+ self.existing_egg_info_dir = None
274
+
275
+ def get_package_dir(self, package):
276
+ res = orig.build_py.get_package_dir(self, package)
277
+ if self.distribution.src_root is not None:
278
+ return os.path.join(self.distribution.src_root, res)
279
+ return res
280
+
281
+ def exclude_data_files(self, package, src_dir, files):
282
+ """Filter filenames for package's data files in 'src_dir'"""
283
+ files = list(files)
284
+ patterns = self._get_platform_patterns(
285
+ self.exclude_package_data,
286
+ package,
287
+ src_dir,
288
+ )
289
+ match_groups = (fnmatch.filter(files, pattern) for pattern in patterns)
290
+ # flatten the groups of matches into an iterable of matches
291
+ matches = itertools.chain.from_iterable(match_groups)
292
+ bad = set(matches)
293
+ keepers = (fn for fn in files if fn not in bad)
294
+ # ditch dupes
295
+ return list(unique_everseen(keepers))
296
+
297
+ @staticmethod
298
+ def _get_platform_patterns(spec, package, src_dir, extra_patterns=()):
299
+ """
300
+ yield platform-specific path patterns (suitable for glob
301
+ or fn_match) from a glob-based spec (such as
302
+ self.package_data or self.exclude_package_data)
303
+ matching package in src_dir.
304
+ """
305
+ raw_patterns = itertools.chain(
306
+ extra_patterns,
307
+ spec.get('', []),
308
+ spec.get(package, []),
309
+ )
310
+ return (
311
+ # Each pattern has to be converted to a platform-specific path
312
+ os.path.join(src_dir, convert_path(pattern))
313
+ for pattern in raw_patterns
314
+ )
315
+
316
+
317
+ def assert_relative(path):
318
+ if not os.path.isabs(path):
319
+ return path
320
+ from distutils.errors import DistutilsSetupError
321
+
322
+ msg = (
323
+ textwrap.dedent(
324
+ """
325
+ Error: setup script specifies an absolute path:
326
+
327
+ %s
328
+
329
+ setup() arguments must *always* be /-separated paths relative to the
330
+ setup.py directory, *never* absolute paths.
331
+ """
332
+ ).lstrip()
333
+ % path
334
+ )
335
+ raise DistutilsSetupError(msg)
336
+
337
+
338
+ class _IncludePackageDataAbuse:
339
+ """Inform users that package or module is included as 'data file'"""
340
+
341
+ class _Warning(SetuptoolsDeprecationWarning):
342
+ _SUMMARY = """
343
+ Package {importable!r} is absent from the `packages` configuration.
344
+ """
345
+
346
+ _DETAILS = """
347
+ ############################
348
+ # Package would be ignored #
349
+ ############################
350
+ Python recognizes {importable!r} as an importable package[^1],
351
+ but it is absent from setuptools' `packages` configuration.
352
+
353
+ This leads to an ambiguous overall configuration. If you want to distribute this
354
+ package, please make sure that {importable!r} is explicitly added
355
+ to the `packages` configuration field.
356
+
357
+ Alternatively, you can also rely on setuptools' discovery methods
358
+ (for example by using `find_namespace_packages(...)`/`find_namespace:`
359
+ instead of `find_packages(...)`/`find:`).
360
+
361
+ You can read more about "package discovery" on setuptools documentation page:
362
+
363
+ - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html
364
+
365
+ If you don't want {importable!r} to be distributed and are
366
+ already explicitly excluding {importable!r} via
367
+ `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`,
368
+ you can try to use `exclude_package_data`, or `include-package-data=False` in
369
+ combination with a more fine grained `package-data` configuration.
370
+
371
+ You can read more about "package data files" on setuptools documentation page:
372
+
373
+ - https://setuptools.pypa.io/en/latest/userguide/datafiles.html
374
+
375
+
376
+ [^1]: For Python, any directory (with suitable naming) can be imported,
377
+ even if it does not contain any `.py` files.
378
+ On the other hand, currently there is no concept of package data
379
+ directory, all directories are treated like packages.
380
+ """
381
+ # _DUE_DATE: still not defined as this is particularly controversial.
382
+ # Warning initially introduced in May 2022. See issue #3340 for discussion.
383
+
384
+ def __init__(self):
385
+ self._already_warned = set()
386
+
387
+ def is_module(self, file):
388
+ return file.endswith(".py") and file[: -len(".py")].isidentifier()
389
+
390
+ def importable_subpackage(self, parent, file):
391
+ pkg = Path(file).parent
392
+ parts = list(itertools.takewhile(str.isidentifier, pkg.parts))
393
+ if parts:
394
+ return ".".join([parent, *parts])
395
+ return None
396
+
397
+ def warn(self, importable):
398
+ if importable not in self._already_warned:
399
+ self._Warning.emit(importable=importable)
400
+ self._already_warned.add(importable)
python_embeded/Lib/site-packages/setuptools/command/develop.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import site
2
+ import subprocess
3
+ import sys
4
+
5
+ from setuptools import Command
6
+ from setuptools.warnings import SetuptoolsDeprecationWarning
7
+
8
+
9
+ class develop(Command):
10
+ """Set up package for development"""
11
+
12
+ user_options = [
13
+ ("install-dir=", "d", "install package to DIR"),
14
+ ('no-deps', 'N', "don't install dependencies"),
15
+ ('user', None, f"install in user site-package '{site.USER_SITE}'"),
16
+ ('prefix=', None, "installation prefix"),
17
+ ("index-url=", "i", "base URL of Python Package Index"),
18
+ ]
19
+ boolean_options = [
20
+ 'no-deps',
21
+ 'user',
22
+ ]
23
+
24
+ install_dir = None
25
+ no_deps = False
26
+ user = False
27
+ prefix = None
28
+ index_url = None
29
+
30
+ def run(self):
31
+ cmd = (
32
+ [sys.executable, '-m', 'pip', 'install', '-e', '.', '--use-pep517']
33
+ + ['--target', self.install_dir] * bool(self.install_dir)
34
+ + ['--no-deps'] * self.no_deps
35
+ + ['--user'] * self.user
36
+ + ['--prefix', self.prefix] * bool(self.prefix)
37
+ + ['--index-url', self.index_url] * bool(self.index_url)
38
+ )
39
+ subprocess.check_call(cmd)
40
+
41
+ def initialize_options(self):
42
+ DevelopDeprecationWarning.emit()
43
+
44
+ def finalize_options(self) -> None:
45
+ pass
46
+
47
+
48
+ class DevelopDeprecationWarning(SetuptoolsDeprecationWarning):
49
+ _SUMMARY = "develop command is deprecated."
50
+ _DETAILS = """
51
+ Please avoid running ``setup.py`` and ``develop``.
52
+ Instead, use standards-based tools like pip or uv.
53
+ """
54
+ _SEE_URL = "https://github.com/pypa/setuptools/issues/917"
55
+ _DUE_DATE = 2025, 10, 31
python_embeded/Lib/site-packages/setuptools/command/dist_info.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Create a dist_info directory
3
+ As defined in the wheel specification
4
+ """
5
+
6
+ import os
7
+ import shutil
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+ from typing import cast
11
+
12
+ from .. import _normalization
13
+ from .._shutil import rmdir as _rm
14
+ from .egg_info import egg_info as egg_info_cls
15
+
16
+ from distutils import log
17
+ from distutils.core import Command
18
+
19
+
20
+ class dist_info(Command):
21
+ """
22
+ This command is private and reserved for internal use of setuptools,
23
+ users should rely on ``setuptools.build_meta`` APIs.
24
+ """
25
+
26
+ description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create .dist-info directory"
27
+
28
+ user_options = [
29
+ (
30
+ 'output-dir=',
31
+ 'o',
32
+ "directory inside of which the .dist-info will be"
33
+ "created [default: top of the source tree]",
34
+ ),
35
+ ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
36
+ ('tag-build=', 'b', "Specify explicit tag to add to version number"),
37
+ ('no-date', 'D', "Don't include date stamp [default]"),
38
+ ('keep-egg-info', None, "*TRANSITIONAL* will be removed in the future"),
39
+ ]
40
+
41
+ boolean_options = ['tag-date', 'keep-egg-info']
42
+ negative_opt = {'no-date': 'tag-date'}
43
+
44
+ def initialize_options(self):
45
+ self.output_dir = None
46
+ self.name = None
47
+ self.dist_info_dir = None
48
+ self.tag_date = None
49
+ self.tag_build = None
50
+ self.keep_egg_info = False
51
+
52
+ def finalize_options(self) -> None:
53
+ dist = self.distribution
54
+ project_dir = dist.src_root or os.curdir
55
+ self.output_dir = Path(self.output_dir or project_dir)
56
+
57
+ egg_info = cast(egg_info_cls, self.reinitialize_command("egg_info"))
58
+ egg_info.egg_base = str(self.output_dir)
59
+
60
+ if self.tag_date:
61
+ egg_info.tag_date = self.tag_date
62
+ else:
63
+ self.tag_date = egg_info.tag_date
64
+
65
+ if self.tag_build:
66
+ egg_info.tag_build = self.tag_build
67
+ else:
68
+ self.tag_build = egg_info.tag_build
69
+
70
+ egg_info.finalize_options()
71
+ self.egg_info = egg_info
72
+
73
+ name = _normalization.safer_name(dist.get_name())
74
+ version = _normalization.safer_best_effort_version(dist.get_version())
75
+ self.name = f"{name}-{version}"
76
+ self.dist_info_dir = os.path.join(self.output_dir, f"{self.name}.dist-info")
77
+
78
+ @contextmanager
79
+ def _maybe_bkp_dir(self, dir_path: str, requires_bkp: bool):
80
+ if requires_bkp:
81
+ bkp_name = f"{dir_path}.__bkp__"
82
+ _rm(bkp_name, ignore_errors=True)
83
+ shutil.copytree(dir_path, bkp_name, dirs_exist_ok=True, symlinks=True)
84
+ try:
85
+ yield
86
+ finally:
87
+ _rm(dir_path, ignore_errors=True)
88
+ shutil.move(bkp_name, dir_path)
89
+ else:
90
+ yield
91
+
92
+ def run(self) -> None:
93
+ self.output_dir.mkdir(parents=True, exist_ok=True)
94
+ self.egg_info.run()
95
+ egg_info_dir = self.egg_info.egg_info
96
+ assert os.path.isdir(egg_info_dir), ".egg-info dir should have been created"
97
+
98
+ log.info(f"creating '{os.path.abspath(self.dist_info_dir)}'")
99
+ bdist_wheel = self.get_finalized_command('bdist_wheel')
100
+
101
+ # TODO: if bdist_wheel if merged into setuptools, just add "keep_egg_info" there
102
+ with self._maybe_bkp_dir(egg_info_dir, self.keep_egg_info):
103
+ bdist_wheel.egg2dist(egg_info_dir, self.dist_info_dir)
python_embeded/Lib/site-packages/setuptools/command/easy_install.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import types
4
+
5
+ from setuptools import Command
6
+
7
+ from .. import _scripts, warnings
8
+
9
+
10
+ class easy_install(Command):
11
+ """Stubbed command for temporary pbr compatibility."""
12
+
13
+
14
+ def __getattr__(name):
15
+ attr = getattr(
16
+ types.SimpleNamespace(
17
+ ScriptWriter=_scripts.ScriptWriter,
18
+ sys_executable=os.environ.get(
19
+ "__PYVENV_LAUNCHER__", os.path.normpath(sys.executable)
20
+ ),
21
+ ),
22
+ name,
23
+ )
24
+ warnings.SetuptoolsDeprecationWarning.emit(
25
+ summary="easy_install module is deprecated",
26
+ details="Avoid accessing attributes of setuptools.command.easy_install.",
27
+ due_date=(2025, 10, 31),
28
+ see_url="https://github.com/pypa/setuptools/issues/4976",
29
+ )
30
+ return attr
python_embeded/Lib/site-packages/setuptools/command/editable_wheel.py ADDED
@@ -0,0 +1,908 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Create a wheel that, when installed, will make the source package 'editable'
3
+ (add it to the interpreter's path, including metadata) per PEP 660. Replaces
4
+ 'setup.py develop'.
5
+
6
+ .. note::
7
+ One of the mechanisms briefly mentioned in PEP 660 to implement editable installs is
8
+ to create a separated directory inside ``build`` and use a .pth file to point to that
9
+ directory. In the context of this file such directory is referred as
10
+ *auxiliary build directory* or ``auxiliary_dir``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import io
16
+ import logging
17
+ import os
18
+ import shutil
19
+ import traceback
20
+ from collections.abc import Iterable, Iterator, Mapping
21
+ from contextlib import suppress
22
+ from enum import Enum
23
+ from inspect import cleandoc
24
+ from itertools import chain, starmap
25
+ from pathlib import Path
26
+ from tempfile import TemporaryDirectory
27
+ from types import TracebackType
28
+ from typing import TYPE_CHECKING, Protocol, TypeVar, cast
29
+
30
+ from .. import Command, _normalization, _path, _shutil, errors, namespaces
31
+ from .._path import StrPath
32
+ from ..compat import py310, py312
33
+ from ..discovery import find_package_path
34
+ from ..dist import Distribution
35
+ from ..warnings import InformationOnly, SetuptoolsDeprecationWarning
36
+ from .build import build as build_cls
37
+ from .build_py import build_py as build_py_cls
38
+ from .dist_info import dist_info as dist_info_cls
39
+ from .egg_info import egg_info as egg_info_cls
40
+ from .install import install as install_cls
41
+ from .install_scripts import install_scripts as install_scripts_cls
42
+
43
+ if TYPE_CHECKING:
44
+ from typing_extensions import Self
45
+
46
+ from .._vendor.wheel.wheelfile import WheelFile
47
+
48
+ _P = TypeVar("_P", bound=StrPath)
49
+ _logger = logging.getLogger(__name__)
50
+
51
+
52
+ class _EditableMode(Enum):
53
+ """
54
+ Possible editable installation modes:
55
+ `lenient` (new files automatically added to the package - DEFAULT);
56
+ `strict` (requires a new installation when files are added/removed); or
57
+ `compat` (attempts to emulate `python setup.py develop` - DEPRECATED).
58
+ """
59
+
60
+ STRICT = "strict"
61
+ LENIENT = "lenient"
62
+ COMPAT = "compat" # TODO: Remove `compat` after Dec/2022.
63
+
64
+ @classmethod
65
+ def convert(cls, mode: str | None) -> _EditableMode:
66
+ if not mode:
67
+ return _EditableMode.LENIENT # default
68
+
69
+ _mode = mode.upper()
70
+ if _mode not in _EditableMode.__members__:
71
+ raise errors.OptionError(f"Invalid editable mode: {mode!r}. Try: 'strict'.")
72
+
73
+ if _mode == "COMPAT":
74
+ SetuptoolsDeprecationWarning.emit(
75
+ "Compat editable installs",
76
+ """
77
+ The 'compat' editable mode is transitional and will be removed
78
+ in future versions of `setuptools`.
79
+ Please adapt your code accordingly to use either the 'strict' or the
80
+ 'lenient' modes.
81
+ """,
82
+ see_docs="userguide/development_mode.html",
83
+ # TODO: define due_date
84
+ # There is a series of shortcomings with the available editable install
85
+ # methods, and they are very controversial. This is something that still
86
+ # needs work.
87
+ # Moreover, `pip` is still hiding this warning, so users are not aware.
88
+ )
89
+
90
+ return _EditableMode[_mode]
91
+
92
+
93
+ _STRICT_WARNING = """
94
+ New or renamed files may not be automatically picked up without a new installation.
95
+ """
96
+
97
+ _LENIENT_WARNING = """
98
+ Options like `package-data`, `include/exclude-package-data` or
99
+ `packages.find.exclude/include` may have no effect.
100
+ """
101
+
102
+
103
+ class editable_wheel(Command):
104
+ """Build 'editable' wheel for development.
105
+ This command is private and reserved for internal use of setuptools,
106
+ users should rely on ``setuptools.build_meta`` APIs.
107
+ """
108
+
109
+ description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create PEP 660 editable wheel"
110
+
111
+ user_options = [
112
+ ("dist-dir=", "d", "directory to put final built distributions in"),
113
+ ("dist-info-dir=", "I", "path to a pre-build .dist-info directory"),
114
+ ("mode=", None, cleandoc(_EditableMode.__doc__ or "")),
115
+ ]
116
+
117
+ def initialize_options(self):
118
+ self.dist_dir = None
119
+ self.dist_info_dir = None
120
+ self.project_dir = None
121
+ self.mode = None
122
+
123
+ def finalize_options(self) -> None:
124
+ dist = self.distribution
125
+ self.project_dir = dist.src_root or os.curdir
126
+ self.package_dir = dist.package_dir or {}
127
+ self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, "dist"))
128
+
129
+ def run(self) -> None:
130
+ try:
131
+ self.dist_dir.mkdir(exist_ok=True)
132
+ self._ensure_dist_info()
133
+
134
+ # Add missing dist_info files
135
+ self.reinitialize_command("bdist_wheel")
136
+ bdist_wheel = self.get_finalized_command("bdist_wheel")
137
+ bdist_wheel.write_wheelfile(self.dist_info_dir)
138
+
139
+ self._create_wheel_file(bdist_wheel)
140
+ except Exception as ex:
141
+ project = self.distribution.name or self.distribution.get_name()
142
+ py310.add_note(
143
+ ex,
144
+ f"An error occurred when building editable wheel for {project}.\n"
145
+ "See debugging tips in: "
146
+ "https://setuptools.pypa.io/en/latest/userguide/development_mode.html#debugging-tips",
147
+ )
148
+ raise
149
+
150
+ def _ensure_dist_info(self):
151
+ if self.dist_info_dir is None:
152
+ dist_info = cast(dist_info_cls, self.reinitialize_command("dist_info"))
153
+ dist_info.output_dir = self.dist_dir
154
+ dist_info.ensure_finalized()
155
+ dist_info.run()
156
+ self.dist_info_dir = dist_info.dist_info_dir
157
+ else:
158
+ assert str(self.dist_info_dir).endswith(".dist-info")
159
+ assert Path(self.dist_info_dir, "METADATA").exists()
160
+
161
+ def _install_namespaces(self, installation_dir, pth_prefix):
162
+ # XXX: Only required to support the deprecated namespace practice
163
+ dist = self.distribution
164
+ if not dist.namespace_packages:
165
+ return
166
+
167
+ src_root = Path(self.project_dir, self.package_dir.get("", ".")).resolve()
168
+ installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root)
169
+ installer.install_namespaces()
170
+
171
+ def _find_egg_info_dir(self) -> str | None:
172
+ parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path()
173
+ candidates = map(str, parent_dir.glob("*.egg-info"))
174
+ return next(candidates, None)
175
+
176
+ def _configure_build(
177
+ self, name: str, unpacked_wheel: StrPath, build_lib: StrPath, tmp_dir: StrPath
178
+ ):
179
+ """Configure commands to behave in the following ways:
180
+
181
+ - Build commands can write to ``build_lib`` if they really want to...
182
+ (but this folder is expected to be ignored and modules are expected to live
183
+ in the project directory...)
184
+ - Binary extensions should be built in-place (editable_mode = True)
185
+ - Data/header/script files are not part of the "editable" specification
186
+ so they are written directly to the unpacked_wheel directory.
187
+ """
188
+ # Non-editable files (data, headers, scripts) are written directly to the
189
+ # unpacked_wheel
190
+
191
+ dist = self.distribution
192
+ wheel = str(unpacked_wheel)
193
+ build_lib = str(build_lib)
194
+ data = str(Path(unpacked_wheel, f"{name}.data", "data"))
195
+ headers = str(Path(unpacked_wheel, f"{name}.data", "headers"))
196
+ scripts = str(Path(unpacked_wheel, f"{name}.data", "scripts"))
197
+
198
+ # egg-info may be generated again to create a manifest (used for package data)
199
+ egg_info = cast(
200
+ egg_info_cls, dist.reinitialize_command("egg_info", reinit_subcommands=True)
201
+ )
202
+ egg_info.egg_base = str(tmp_dir)
203
+ egg_info.ignore_egg_info_in_manifest = True
204
+
205
+ build = cast(
206
+ build_cls, dist.reinitialize_command("build", reinit_subcommands=True)
207
+ )
208
+ install = cast(
209
+ install_cls, dist.reinitialize_command("install", reinit_subcommands=True)
210
+ )
211
+
212
+ build.build_platlib = build.build_purelib = build.build_lib = build_lib
213
+ install.install_purelib = install.install_platlib = install.install_lib = wheel
214
+ install.install_scripts = build.build_scripts = scripts
215
+ install.install_headers = headers
216
+ install.install_data = data
217
+
218
+ # For portability, ensure scripts are built with #!python shebang
219
+ # pypa/setuptools#4863
220
+ build_scripts = dist.get_command_obj("build_scripts")
221
+ build_scripts.executable = 'python'
222
+
223
+ install_scripts = cast(
224
+ install_scripts_cls, dist.get_command_obj("install_scripts")
225
+ )
226
+ install_scripts.no_ep = True
227
+
228
+ build.build_temp = str(tmp_dir)
229
+
230
+ build_py = cast(build_py_cls, dist.get_command_obj("build_py"))
231
+ build_py.compile = False
232
+ build_py.existing_egg_info_dir = self._find_egg_info_dir()
233
+
234
+ self._set_editable_mode()
235
+
236
+ build.ensure_finalized()
237
+ install.ensure_finalized()
238
+
239
+ def _set_editable_mode(self):
240
+ """Set the ``editable_mode`` flag in the build sub-commands"""
241
+ dist = self.distribution
242
+ build = dist.get_command_obj("build")
243
+ for cmd_name in build.get_sub_commands():
244
+ cmd = dist.get_command_obj(cmd_name)
245
+ if hasattr(cmd, "editable_mode"):
246
+ cmd.editable_mode = True
247
+ elif hasattr(cmd, "inplace"):
248
+ cmd.inplace = True # backward compatibility with distutils
249
+
250
+ def _collect_build_outputs(self) -> tuple[list[str], dict[str, str]]:
251
+ files: list[str] = []
252
+ mapping: dict[str, str] = {}
253
+ build = self.get_finalized_command("build")
254
+
255
+ for cmd_name in build.get_sub_commands():
256
+ cmd = self.get_finalized_command(cmd_name)
257
+ if hasattr(cmd, "get_outputs"):
258
+ files.extend(cmd.get_outputs() or [])
259
+ if hasattr(cmd, "get_output_mapping"):
260
+ mapping.update(cmd.get_output_mapping() or {})
261
+
262
+ return files, mapping
263
+
264
+ def _run_build_commands(
265
+ self,
266
+ dist_name: str,
267
+ unpacked_wheel: StrPath,
268
+ build_lib: StrPath,
269
+ tmp_dir: StrPath,
270
+ ) -> tuple[list[str], dict[str, str]]:
271
+ self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir)
272
+ self._run_build_subcommands()
273
+ files, mapping = self._collect_build_outputs()
274
+ self._run_install("headers")
275
+ self._run_install("scripts")
276
+ self._run_install("data")
277
+ return files, mapping
278
+
279
+ def _run_build_subcommands(self) -> None:
280
+ """
281
+ Issue #3501 indicates that some plugins/customizations might rely on:
282
+
283
+ 1. ``build_py`` not running
284
+ 2. ``build_py`` always copying files to ``build_lib``
285
+
286
+ However both these assumptions may be false in editable_wheel.
287
+ This method implements a temporary workaround to support the ecosystem
288
+ while the implementations catch up.
289
+ """
290
+ # TODO: Once plugins/customizations had the chance to catch up, replace
291
+ # `self._run_build_subcommands()` with `self.run_command("build")`.
292
+ # Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023.
293
+ build = self.get_finalized_command("build")
294
+ for name in build.get_sub_commands():
295
+ cmd = self.get_finalized_command(name)
296
+ if name == "build_py" and type(cmd) is not build_py_cls:
297
+ self._safely_run(name)
298
+ else:
299
+ self.run_command(name)
300
+
301
+ def _safely_run(self, cmd_name: str):
302
+ try:
303
+ return self.run_command(cmd_name)
304
+ except Exception:
305
+ SetuptoolsDeprecationWarning.emit(
306
+ "Customization incompatible with editable install",
307
+ f"""
308
+ {traceback.format_exc()}
309
+
310
+ If you are seeing this warning it is very likely that a setuptools
311
+ plugin or customization overrides the `{cmd_name}` command, without
312
+ taking into consideration how editable installs run build steps
313
+ starting from setuptools v64.0.0.
314
+
315
+ Plugin authors and developers relying on custom build steps are
316
+ encouraged to update their `{cmd_name}` implementation considering the
317
+ information about editable installs in
318
+ https://setuptools.pypa.io/en/latest/userguide/extension.html.
319
+
320
+ For the time being `setuptools` will silence this error and ignore
321
+ the faulty command, but this behavior will change in future versions.
322
+ """,
323
+ # TODO: define due_date
324
+ # There is a series of shortcomings with the available editable install
325
+ # methods, and they are very controversial. This is something that still
326
+ # needs work.
327
+ )
328
+
329
+ def _create_wheel_file(self, bdist_wheel):
330
+ from wheel.wheelfile import WheelFile
331
+
332
+ dist_info = self.get_finalized_command("dist_info")
333
+ dist_name = dist_info.name
334
+ tag = "-".join(bdist_wheel.get_tag())
335
+ build_tag = "0.editable" # According to PEP 427 needs to start with digit
336
+ archive_name = f"{dist_name}-{build_tag}-{tag}.whl"
337
+ wheel_path = Path(self.dist_dir, archive_name)
338
+ if wheel_path.exists():
339
+ wheel_path.unlink()
340
+
341
+ unpacked_wheel = TemporaryDirectory(suffix=archive_name)
342
+ build_lib = TemporaryDirectory(suffix=".build-lib")
343
+ build_tmp = TemporaryDirectory(suffix=".build-temp")
344
+
345
+ with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp:
346
+ unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name)
347
+ shutil.copytree(self.dist_info_dir, unpacked_dist_info)
348
+ self._install_namespaces(unpacked, dist_name)
349
+ files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)
350
+ strategy = self._select_strategy(dist_name, tag, lib)
351
+ with strategy, WheelFile(wheel_path, "w") as wheel_obj:
352
+ strategy(wheel_obj, files, mapping)
353
+ wheel_obj.write_files(unpacked)
354
+
355
+ return wheel_path
356
+
357
+ def _run_install(self, category: str):
358
+ has_category = getattr(self.distribution, f"has_{category}", None)
359
+ if has_category and has_category():
360
+ _logger.info(f"Installing {category} as non editable")
361
+ self.run_command(f"install_{category}")
362
+
363
+ def _select_strategy(
364
+ self,
365
+ name: str,
366
+ tag: str,
367
+ build_lib: StrPath,
368
+ ) -> EditableStrategy:
369
+ """Decides which strategy to use to implement an editable installation."""
370
+ build_name = f"__editable__.{name}-{tag}"
371
+ project_dir = Path(self.project_dir)
372
+ mode = _EditableMode.convert(self.mode)
373
+
374
+ if mode is _EditableMode.STRICT:
375
+ auxiliary_dir = _empty_dir(Path(self.project_dir, "build", build_name))
376
+ return _LinkTree(self.distribution, name, auxiliary_dir, build_lib)
377
+
378
+ packages = _find_packages(self.distribution)
379
+ has_simple_layout = _simple_layout(packages, self.package_dir, project_dir)
380
+ is_compat_mode = mode is _EditableMode.COMPAT
381
+ if set(self.package_dir) == {""} and has_simple_layout or is_compat_mode:
382
+ # src-layout(ish) is relatively safe for a simple pth file
383
+ src_dir = self.package_dir.get("", ".")
384
+ return _StaticPth(self.distribution, name, [Path(project_dir, src_dir)])
385
+
386
+ # Use a MetaPathFinder to avoid adding accidental top-level packages/modules
387
+ return _TopLevelFinder(self.distribution, name)
388
+
389
+
390
+ class EditableStrategy(Protocol):
391
+ def __call__(
392
+ self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
393
+ ) -> object: ...
394
+ def __enter__(self) -> Self: ...
395
+ def __exit__(
396
+ self,
397
+ _exc_type: type[BaseException] | None,
398
+ _exc_value: BaseException | None,
399
+ _traceback: TracebackType | None,
400
+ ) -> object: ...
401
+
402
+
403
+ class _StaticPth:
404
+ def __init__(self, dist: Distribution, name: str, path_entries: list[Path]) -> None:
405
+ self.dist = dist
406
+ self.name = name
407
+ self.path_entries = path_entries
408
+
409
+ def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
410
+ entries = "\n".join(str(p.resolve()) for p in self.path_entries)
411
+ contents = _encode_pth(f"{entries}\n")
412
+ wheel.writestr(f"__editable__.{self.name}.pth", contents)
413
+
414
+ def __enter__(self) -> Self:
415
+ msg = f"""
416
+ Editable install will be performed using .pth file to extend `sys.path` with:
417
+ {list(map(os.fspath, self.path_entries))!r}
418
+ """
419
+ _logger.warning(msg + _LENIENT_WARNING)
420
+ return self
421
+
422
+ def __exit__(
423
+ self,
424
+ _exc_type: object,
425
+ _exc_value: object,
426
+ _traceback: object,
427
+ ) -> None:
428
+ pass
429
+
430
+
431
+ class _LinkTree(_StaticPth):
432
+ """
433
+ Creates a ``.pth`` file that points to a link tree in the ``auxiliary_dir``.
434
+
435
+ This strategy will only link files (not dirs), so it can be implemented in
436
+ any OS, even if that means using hardlinks instead of symlinks.
437
+
438
+ By collocating ``auxiliary_dir`` and the original source code, limitations
439
+ with hardlinks should be avoided.
440
+ """
441
+
442
+ def __init__(
443
+ self,
444
+ dist: Distribution,
445
+ name: str,
446
+ auxiliary_dir: StrPath,
447
+ build_lib: StrPath,
448
+ ) -> None:
449
+ self.auxiliary_dir = Path(auxiliary_dir)
450
+ self.build_lib = Path(build_lib).resolve()
451
+ self._file = dist.get_command_obj("build_py").copy_file
452
+ super().__init__(dist, name, [self.auxiliary_dir])
453
+
454
+ def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
455
+ self._create_links(files, mapping)
456
+ super().__call__(wheel, files, mapping)
457
+
458
+ def _normalize_output(self, file: str) -> str | None:
459
+ # Files relative to build_lib will be normalized to None
460
+ with suppress(ValueError):
461
+ path = Path(file).resolve().relative_to(self.build_lib)
462
+ return str(path).replace(os.sep, '/')
463
+ return None
464
+
465
+ def _create_file(self, relative_output: str, src_file: str, link=None):
466
+ dest = self.auxiliary_dir / relative_output
467
+ if not dest.parent.is_dir():
468
+ dest.parent.mkdir(parents=True)
469
+ self._file(src_file, dest, link=link)
470
+
471
+ def _create_links(self, outputs, output_mapping: Mapping[str, str]):
472
+ self.auxiliary_dir.mkdir(parents=True, exist_ok=True)
473
+ link_type = "sym" if _can_symlink_files(self.auxiliary_dir) else "hard"
474
+ normalised = ((self._normalize_output(k), v) for k, v in output_mapping.items())
475
+ # remove files that are not relative to build_lib
476
+ mappings = {k: v for k, v in normalised if k is not None}
477
+
478
+ for output in outputs:
479
+ relative = self._normalize_output(output)
480
+ if relative and relative not in mappings:
481
+ self._create_file(relative, output)
482
+
483
+ for relative, src in mappings.items():
484
+ self._create_file(relative, src, link=link_type)
485
+
486
+ def __enter__(self) -> Self:
487
+ msg = "Strict editable install will be performed using a link tree.\n"
488
+ _logger.warning(msg + _STRICT_WARNING)
489
+ return self
490
+
491
+ def __exit__(
492
+ self,
493
+ _exc_type: object,
494
+ _exc_value: object,
495
+ _traceback: object,
496
+ ) -> None:
497
+ msg = f"""\n
498
+ Strict editable installation performed using the auxiliary directory:
499
+ {self.auxiliary_dir}
500
+
501
+ Please be careful to not remove this directory, otherwise you might not be able
502
+ to import/use your package.
503
+ """
504
+ InformationOnly.emit("Editable installation.", msg)
505
+
506
+
507
+ class _TopLevelFinder:
508
+ def __init__(self, dist: Distribution, name: str) -> None:
509
+ self.dist = dist
510
+ self.name = name
511
+
512
+ def template_vars(self) -> tuple[str, str, dict[str, str], dict[str, list[str]]]:
513
+ src_root = self.dist.src_root or os.curdir
514
+ top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist))
515
+ package_dir = self.dist.package_dir or {}
516
+ roots = _find_package_roots(top_level, package_dir, src_root)
517
+
518
+ namespaces_ = dict(
519
+ chain(
520
+ _find_namespaces(self.dist.packages or [], roots),
521
+ ((ns, []) for ns in _find_virtual_namespaces(roots)),
522
+ )
523
+ )
524
+
525
+ legacy_namespaces = {
526
+ pkg: find_package_path(pkg, roots, self.dist.src_root or "")
527
+ for pkg in self.dist.namespace_packages or []
528
+ }
529
+
530
+ mapping = {**roots, **legacy_namespaces}
531
+ # ^-- We need to explicitly add the legacy_namespaces to the mapping to be
532
+ # able to import their modules even if another package sharing the same
533
+ # namespace is installed in a conventional (non-editable) way.
534
+
535
+ name = f"__editable__.{self.name}.finder"
536
+ finder = _normalization.safe_identifier(name)
537
+ return finder, name, mapping, namespaces_
538
+
539
+ def get_implementation(self) -> Iterator[tuple[str, bytes]]:
540
+ finder, name, mapping, namespaces_ = self.template_vars()
541
+
542
+ content = bytes(_finder_template(name, mapping, namespaces_), "utf-8")
543
+ yield (f"{finder}.py", content)
544
+
545
+ content = _encode_pth(f"import {finder}; {finder}.install()")
546
+ yield (f"__editable__.{self.name}.pth", content)
547
+
548
+ def __call__(self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]):
549
+ for file, content in self.get_implementation():
550
+ wheel.writestr(file, content)
551
+
552
+ def __enter__(self) -> Self:
553
+ msg = "Editable install will be performed using a meta path finder.\n"
554
+ _logger.warning(msg + _LENIENT_WARNING)
555
+ return self
556
+
557
+ def __exit__(
558
+ self,
559
+ _exc_type: object,
560
+ _exc_value: object,
561
+ _traceback: object,
562
+ ) -> None:
563
+ msg = """\n
564
+ Please be careful with folders in your working directory with the same
565
+ name as your package as they may take precedence during imports.
566
+ """
567
+ InformationOnly.emit("Editable installation.", msg)
568
+
569
+
570
+ def _encode_pth(content: str) -> bytes:
571
+ """
572
+ Prior to Python 3.13 (see https://github.com/python/cpython/issues/77102),
573
+ .pth files are always read with 'locale' encoding, the recommendation
574
+ from the cpython core developers is to write them as ``open(path, "w")``
575
+ and ignore warnings (see python/cpython#77102, pypa/setuptools#3937).
576
+ This function tries to simulate this behavior without having to create an
577
+ actual file, in a way that supports a range of active Python versions.
578
+ (There seems to be some variety in the way different version of Python handle
579
+ ``encoding=None``, not all of them use ``locale.getpreferredencoding(False)``
580
+ or ``locale.getencoding()``).
581
+ """
582
+ with io.BytesIO() as buffer:
583
+ wrapper = io.TextIOWrapper(buffer, encoding=py312.PTH_ENCODING)
584
+ # TODO: Python 3.13 replace the whole function with `bytes(content, "utf-8")`
585
+ wrapper.write(content)
586
+ wrapper.flush()
587
+ buffer.seek(0)
588
+ return buffer.read()
589
+
590
+
591
+ def _can_symlink_files(base_dir: Path) -> bool:
592
+ with TemporaryDirectory(dir=str(base_dir.resolve())) as tmp:
593
+ path1, path2 = Path(tmp, "file1.txt"), Path(tmp, "file2.txt")
594
+ path1.write_text("file1", encoding="utf-8")
595
+ with suppress(AttributeError, NotImplementedError, OSError):
596
+ os.symlink(path1, path2)
597
+ if path2.is_symlink() and path2.read_text(encoding="utf-8") == "file1":
598
+ return True
599
+
600
+ try:
601
+ os.link(path1, path2) # Ensure hard links can be created
602
+ except Exception as ex:
603
+ msg = (
604
+ "File system does not seem to support either symlinks or hard links. "
605
+ "Strict editable installs require one of them to be supported."
606
+ )
607
+ raise LinksNotSupported(msg) from ex
608
+ return False
609
+
610
+
611
+ def _simple_layout(
612
+ packages: Iterable[str], package_dir: dict[str, str], project_dir: StrPath
613
+ ) -> bool:
614
+ """Return ``True`` if:
615
+ - all packages are contained by the same parent directory, **and**
616
+ - all packages become importable if the parent directory is added to ``sys.path``.
617
+
618
+ >>> _simple_layout(['a'], {"": "src"}, "/tmp/myproj")
619
+ True
620
+ >>> _simple_layout(['a', 'a.b'], {"": "src"}, "/tmp/myproj")
621
+ True
622
+ >>> _simple_layout(['a', 'a.b'], {}, "/tmp/myproj")
623
+ True
624
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"": "src"}, "/tmp/myproj")
625
+ True
626
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "a", "b": "b"}, ".")
627
+ True
628
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a", "b": "_b"}, ".")
629
+ False
630
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a"}, "/tmp/myproj")
631
+ False
632
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a.a1.a2": "_a2"}, ".")
633
+ False
634
+ >>> _simple_layout(['a', 'a.b'], {"": "src", "a.b": "_ab"}, "/tmp/myproj")
635
+ False
636
+ >>> # Special cases, no packages yet:
637
+ >>> _simple_layout([], {"": "src"}, "/tmp/myproj")
638
+ True
639
+ >>> _simple_layout([], {"a": "_a", "": "src"}, "/tmp/myproj")
640
+ False
641
+ """
642
+ layout = {pkg: find_package_path(pkg, package_dir, project_dir) for pkg in packages}
643
+ if not layout:
644
+ return set(package_dir) in ({}, {""})
645
+ parent = os.path.commonpath(starmap(_parent_path, layout.items()))
646
+ return all(
647
+ _path.same_path(Path(parent, *key.split('.')), value)
648
+ for key, value in layout.items()
649
+ )
650
+
651
+
652
+ def _parent_path(pkg, pkg_path):
653
+ """Infer the parent path containing a package, that if added to ``sys.path`` would
654
+ allow importing that package.
655
+ When ``pkg`` is directly mapped into a directory with a different name, return its
656
+ own path.
657
+ >>> _parent_path("a", "src/a")
658
+ 'src'
659
+ >>> _parent_path("b", "src/c")
660
+ 'src/c'
661
+ """
662
+ parent = pkg_path[: -len(pkg)] if pkg_path.endswith(pkg) else pkg_path
663
+ return parent.rstrip("/" + os.sep)
664
+
665
+
666
+ def _find_packages(dist: Distribution) -> Iterator[str]:
667
+ yield from iter(dist.packages or [])
668
+
669
+ py_modules = dist.py_modules or []
670
+ nested_modules = [mod for mod in py_modules if "." in mod]
671
+ if dist.ext_package:
672
+ yield dist.ext_package
673
+ else:
674
+ ext_modules = dist.ext_modules or []
675
+ nested_modules += [x.name for x in ext_modules if "." in x.name]
676
+
677
+ for module in nested_modules:
678
+ package, _, _ = module.rpartition(".")
679
+ yield package
680
+
681
+
682
+ def _find_top_level_modules(dist: Distribution) -> Iterator[str]:
683
+ py_modules = dist.py_modules or []
684
+ yield from (mod for mod in py_modules if "." not in mod)
685
+
686
+ if not dist.ext_package:
687
+ ext_modules = dist.ext_modules or []
688
+ yield from (x.name for x in ext_modules if "." not in x.name)
689
+
690
+
691
+ def _find_package_roots(
692
+ packages: Iterable[str],
693
+ package_dir: Mapping[str, str],
694
+ src_root: StrPath,
695
+ ) -> dict[str, str]:
696
+ pkg_roots: dict[str, str] = {
697
+ pkg: _absolute_root(find_package_path(pkg, package_dir, src_root))
698
+ for pkg in sorted(packages)
699
+ }
700
+
701
+ return _remove_nested(pkg_roots)
702
+
703
+
704
+ def _absolute_root(path: StrPath) -> str:
705
+ """Works for packages and top-level modules"""
706
+ path_ = Path(path)
707
+ parent = path_.parent
708
+
709
+ if path_.exists():
710
+ return str(path_.resolve())
711
+ else:
712
+ return str(parent.resolve() / path_.name)
713
+
714
+
715
+ def _find_virtual_namespaces(pkg_roots: dict[str, str]) -> Iterator[str]:
716
+ """By carefully designing ``package_dir``, it is possible to implement the logical
717
+ structure of PEP 420 in a package without the corresponding directories.
718
+
719
+ Moreover a parent package can be purposefully/accidentally skipped in the discovery
720
+ phase (e.g. ``find_packages(include=["mypkg.*"])``, when ``mypkg.foo`` is included
721
+ by ``mypkg`` itself is not).
722
+ We consider this case to also be a virtual namespace (ignoring the original
723
+ directory) to emulate a non-editable installation.
724
+
725
+ This function will try to find these kinds of namespaces.
726
+ """
727
+ for pkg in pkg_roots:
728
+ if "." not in pkg:
729
+ continue
730
+ parts = pkg.split(".")
731
+ for i in range(len(parts) - 1, 0, -1):
732
+ partial_name = ".".join(parts[:i])
733
+ path = Path(find_package_path(partial_name, pkg_roots, ""))
734
+ if not path.exists() or partial_name not in pkg_roots:
735
+ # partial_name not in pkg_roots ==> purposefully/accidentally skipped
736
+ yield partial_name
737
+
738
+
739
+ def _find_namespaces(
740
+ packages: list[str], pkg_roots: dict[str, str]
741
+ ) -> Iterator[tuple[str, list[str]]]:
742
+ for pkg in packages:
743
+ path = find_package_path(pkg, pkg_roots, "")
744
+ if Path(path).exists() and not Path(path, "__init__.py").exists():
745
+ yield (pkg, [path])
746
+
747
+
748
+ def _remove_nested(pkg_roots: dict[str, str]) -> dict[str, str]:
749
+ output = dict(pkg_roots.copy())
750
+
751
+ for pkg, path in reversed(list(pkg_roots.items())):
752
+ if any(
753
+ pkg != other and _is_nested(pkg, path, other, other_path)
754
+ for other, other_path in pkg_roots.items()
755
+ ):
756
+ output.pop(pkg)
757
+
758
+ return output
759
+
760
+
761
+ def _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool:
762
+ """
763
+ Return ``True`` if ``pkg`` is nested inside ``parent`` both logically and in the
764
+ file system.
765
+ >>> _is_nested("a.b", "path/a/b", "a", "path/a")
766
+ True
767
+ >>> _is_nested("a.b", "path/a/b", "a", "otherpath/a")
768
+ False
769
+ >>> _is_nested("a.b", "path/a/b", "c", "path/c")
770
+ False
771
+ >>> _is_nested("a.a", "path/a/a", "a", "path/a")
772
+ True
773
+ >>> _is_nested("b.a", "path/b/a", "a", "path/a")
774
+ False
775
+ """
776
+ norm_pkg_path = _path.normpath(pkg_path)
777
+ rest = pkg.replace(parent, "", 1).strip(".").split(".")
778
+ return pkg.startswith(parent) and norm_pkg_path == _path.normpath(
779
+ Path(parent_path, *rest)
780
+ )
781
+
782
+
783
+ def _empty_dir(dir_: _P) -> _P:
784
+ """Create a directory ensured to be empty. Existing files may be removed."""
785
+ _shutil.rmtree(dir_, ignore_errors=True)
786
+ os.makedirs(dir_)
787
+ return dir_
788
+
789
+
790
+ class _NamespaceInstaller(namespaces.Installer):
791
+ def __init__(self, distribution, installation_dir, editable_name, src_root) -> None:
792
+ self.distribution = distribution
793
+ self.src_root = src_root
794
+ self.installation_dir = installation_dir
795
+ self.editable_name = editable_name
796
+ self.outputs: list[str] = []
797
+ self.dry_run = False
798
+
799
+ def _get_nspkg_file(self):
800
+ """Installation target."""
801
+ return os.path.join(self.installation_dir, self.editable_name + self.nspkg_ext)
802
+
803
+ def _get_root(self):
804
+ """Where the modules/packages should be loaded from."""
805
+ return repr(str(self.src_root))
806
+
807
+
808
+ _FINDER_TEMPLATE = """\
809
+ from __future__ import annotations
810
+ import sys
811
+ from importlib.machinery import ModuleSpec, PathFinder
812
+ from importlib.machinery import all_suffixes as module_suffixes
813
+ from importlib.util import spec_from_file_location
814
+ from itertools import chain
815
+ from pathlib import Path
816
+
817
+ MAPPING: dict[str, str] = {mapping!r}
818
+ NAMESPACES: dict[str, list[str]] = {namespaces!r}
819
+ PATH_PLACEHOLDER = {name!r} + ".__path_hook__"
820
+
821
+
822
+ class _EditableFinder: # MetaPathFinder
823
+ @classmethod
824
+ def find_spec(cls, fullname: str, path=None, target=None) -> ModuleSpec | None: # type: ignore
825
+ # Top-level packages and modules (we know these exist in the FS)
826
+ if fullname in MAPPING:
827
+ pkg_path = MAPPING[fullname]
828
+ return cls._find_spec(fullname, Path(pkg_path))
829
+
830
+ # Handle immediate children modules (required for namespaces to work)
831
+ # To avoid problems with case sensitivity in the file system we delegate
832
+ # to the importlib.machinery implementation.
833
+ parent, _, child = fullname.rpartition(".")
834
+ if parent and parent in MAPPING:
835
+ return PathFinder.find_spec(fullname, path=[MAPPING[parent]])
836
+
837
+ # Other levels of nesting should be handled automatically by importlib
838
+ # using the parent path.
839
+ return None
840
+
841
+ @classmethod
842
+ def _find_spec(cls, fullname: str, candidate_path: Path) -> ModuleSpec | None:
843
+ init = candidate_path / "__init__.py"
844
+ candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
845
+ for candidate in chain([init], candidates):
846
+ if candidate.exists():
847
+ return spec_from_file_location(fullname, candidate)
848
+ return None
849
+
850
+
851
+ class _EditableNamespaceFinder: # PathEntryFinder
852
+ @classmethod
853
+ def _path_hook(cls, path) -> type[_EditableNamespaceFinder]:
854
+ if path == PATH_PLACEHOLDER:
855
+ return cls
856
+ raise ImportError
857
+
858
+ @classmethod
859
+ def _paths(cls, fullname: str) -> list[str]:
860
+ paths = NAMESPACES[fullname]
861
+ if not paths and fullname in MAPPING:
862
+ paths = [MAPPING[fullname]]
863
+ # Always add placeholder, for 2 reasons:
864
+ # 1. __path__ cannot be empty for the spec to be considered namespace.
865
+ # 2. In the case of nested namespaces, we need to force
866
+ # import machinery to query _EditableNamespaceFinder again.
867
+ return [*paths, PATH_PLACEHOLDER]
868
+
869
+ @classmethod
870
+ def find_spec(cls, fullname: str, target=None) -> ModuleSpec | None: # type: ignore
871
+ if fullname in NAMESPACES:
872
+ spec = ModuleSpec(fullname, None, is_package=True)
873
+ spec.submodule_search_locations = cls._paths(fullname)
874
+ return spec
875
+ return None
876
+
877
+ @classmethod
878
+ def find_module(cls, _fullname) -> None:
879
+ return None
880
+
881
+
882
+ def install():
883
+ if not any(finder == _EditableFinder for finder in sys.meta_path):
884
+ sys.meta_path.append(_EditableFinder)
885
+
886
+ if not NAMESPACES:
887
+ return
888
+
889
+ if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks):
890
+ # PathEntryFinder is needed to create NamespaceSpec without private APIS
891
+ sys.path_hooks.append(_EditableNamespaceFinder._path_hook)
892
+ if PATH_PLACEHOLDER not in sys.path:
893
+ sys.path.append(PATH_PLACEHOLDER) # Used just to trigger the path hook
894
+ """
895
+
896
+
897
+ def _finder_template(
898
+ name: str, mapping: Mapping[str, str], namespaces: dict[str, list[str]]
899
+ ) -> str:
900
+ """Create a string containing the code for the``MetaPathFinder`` and
901
+ ``PathEntryFinder``.
902
+ """
903
+ mapping = dict(sorted(mapping.items(), key=lambda p: p[0]))
904
+ return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces)
905
+
906
+
907
+ class LinksNotSupported(errors.FileError):
908
+ """File system does not seem to support either symlinks or hard links."""
python_embeded/Lib/site-packages/setuptools/command/egg_info.py ADDED
@@ -0,0 +1,718 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """setuptools.command.egg_info
2
+
3
+ Create a distribution's .egg-info directory and contents"""
4
+
5
+ import functools
6
+ import os
7
+ import re
8
+ import sys
9
+ import time
10
+ from collections.abc import Callable
11
+
12
+ import packaging
13
+ import packaging.requirements
14
+ import packaging.version
15
+
16
+ import setuptools.unicode_utils as unicode_utils
17
+ from setuptools import Command
18
+ from setuptools.command import bdist_egg
19
+ from setuptools.command.sdist import sdist, walk_revctrl
20
+ from setuptools.command.setopt import edit_config
21
+ from setuptools.glob import glob
22
+
23
+ from .. import _entry_points, _normalization
24
+ from .._importlib import metadata
25
+ from ..warnings import SetuptoolsDeprecationWarning
26
+ from . import _requirestxt
27
+
28
+ import distutils.errors
29
+ import distutils.filelist
30
+ from distutils import log
31
+ from distutils.errors import DistutilsInternalError
32
+ from distutils.filelist import FileList as _FileList
33
+ from distutils.util import convert_path
34
+
35
+ PY_MAJOR = f'{sys.version_info.major}.{sys.version_info.minor}'
36
+
37
+
38
+ def translate_pattern(glob): # noqa: C901 # is too complex (14) # FIXME
39
+ """
40
+ Translate a file path glob like '*.txt' in to a regular expression.
41
+ This differs from fnmatch.translate which allows wildcards to match
42
+ directory separators. It also knows about '**/' which matches any number of
43
+ directories.
44
+ """
45
+ pat = ''
46
+
47
+ # This will split on '/' within [character classes]. This is deliberate.
48
+ chunks = glob.split(os.path.sep)
49
+
50
+ sep = re.escape(os.sep)
51
+ valid_char = f'[^{sep}]'
52
+
53
+ for c, chunk in enumerate(chunks):
54
+ last_chunk = c == len(chunks) - 1
55
+
56
+ # Chunks that are a literal ** are globstars. They match anything.
57
+ if chunk == '**':
58
+ if last_chunk:
59
+ # Match anything if this is the last component
60
+ pat += '.*'
61
+ else:
62
+ # Match '(name/)*'
63
+ pat += f'(?:{valid_char}+{sep})*'
64
+ continue # Break here as the whole path component has been handled
65
+
66
+ # Find any special characters in the remainder
67
+ i = 0
68
+ chunk_len = len(chunk)
69
+ while i < chunk_len:
70
+ char = chunk[i]
71
+ if char == '*':
72
+ # Match any number of name characters
73
+ pat += valid_char + '*'
74
+ elif char == '?':
75
+ # Match a name character
76
+ pat += valid_char
77
+ elif char == '[':
78
+ # Character class
79
+ inner_i = i + 1
80
+ # Skip initial !/] chars
81
+ if inner_i < chunk_len and chunk[inner_i] == '!':
82
+ inner_i = inner_i + 1
83
+ if inner_i < chunk_len and chunk[inner_i] == ']':
84
+ inner_i = inner_i + 1
85
+
86
+ # Loop till the closing ] is found
87
+ while inner_i < chunk_len and chunk[inner_i] != ']':
88
+ inner_i = inner_i + 1
89
+
90
+ if inner_i >= chunk_len:
91
+ # Got to the end of the string without finding a closing ]
92
+ # Do not treat this as a matching group, but as a literal [
93
+ pat += re.escape(char)
94
+ else:
95
+ # Grab the insides of the [brackets]
96
+ inner = chunk[i + 1 : inner_i]
97
+ char_class = ''
98
+
99
+ # Class negation
100
+ if inner[0] == '!':
101
+ char_class = '^'
102
+ inner = inner[1:]
103
+
104
+ char_class += re.escape(inner)
105
+ pat += f'[{char_class}]'
106
+
107
+ # Skip to the end ]
108
+ i = inner_i
109
+ else:
110
+ pat += re.escape(char)
111
+ i += 1
112
+
113
+ # Join each chunk with the dir separator
114
+ if not last_chunk:
115
+ pat += sep
116
+
117
+ pat += r'\Z'
118
+ return re.compile(pat, flags=re.MULTILINE | re.DOTALL)
119
+
120
+
121
+ class InfoCommon:
122
+ tag_build = None
123
+ tag_date = None
124
+
125
+ @property
126
+ def name(self):
127
+ return _normalization.safe_name(self.distribution.get_name())
128
+
129
+ def tagged_version(self):
130
+ tagged = self._maybe_tag(self.distribution.get_version())
131
+ return _normalization.safe_version(tagged)
132
+
133
+ def _maybe_tag(self, version):
134
+ """
135
+ egg_info may be called more than once for a distribution,
136
+ in which case the version string already contains all tags.
137
+ """
138
+ return (
139
+ version
140
+ if self.vtags and self._already_tagged(version)
141
+ else version + self.vtags
142
+ )
143
+
144
+ def _already_tagged(self, version: str) -> bool:
145
+ # Depending on their format, tags may change with version normalization.
146
+ # So in addition the regular tags, we have to search for the normalized ones.
147
+ return version.endswith(self.vtags) or version.endswith(self._safe_tags())
148
+
149
+ def _safe_tags(self) -> str:
150
+ # To implement this we can rely on `safe_version` pretending to be version 0
151
+ # followed by tags. Then we simply discard the starting 0 (fake version number)
152
+ try:
153
+ return _normalization.safe_version(f"0{self.vtags}")[1:]
154
+ except packaging.version.InvalidVersion:
155
+ return _normalization.safe_name(self.vtags.replace(' ', '.'))
156
+
157
+ def tags(self) -> str:
158
+ version = ''
159
+ if self.tag_build:
160
+ version += self.tag_build
161
+ if self.tag_date:
162
+ version += time.strftime("%Y%m%d")
163
+ return version
164
+
165
+ vtags = property(tags)
166
+
167
+
168
+ class egg_info(InfoCommon, Command):
169
+ description = "create a distribution's .egg-info directory"
170
+
171
+ user_options = [
172
+ (
173
+ 'egg-base=',
174
+ 'e',
175
+ "directory containing .egg-info directories"
176
+ " [default: top of the source tree]",
177
+ ),
178
+ ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
179
+ ('tag-build=', 'b', "Specify explicit tag to add to version number"),
180
+ ('no-date', 'D', "Don't include date stamp [default]"),
181
+ ]
182
+
183
+ boolean_options = ['tag-date']
184
+ negative_opt = {
185
+ 'no-date': 'tag-date',
186
+ }
187
+
188
+ def initialize_options(self):
189
+ self.egg_base = None
190
+ self.egg_name = None
191
+ self.egg_info = None
192
+ self.egg_version = None
193
+ self.ignore_egg_info_in_manifest = False
194
+
195
+ ####################################
196
+ # allow the 'tag_svn_revision' to be detected and
197
+ # set, supporting sdists built on older Setuptools.
198
+ @property
199
+ def tag_svn_revision(self) -> None:
200
+ pass
201
+
202
+ @tag_svn_revision.setter
203
+ def tag_svn_revision(self, value):
204
+ pass
205
+
206
+ ####################################
207
+
208
+ def save_version_info(self, filename) -> None:
209
+ """
210
+ Materialize the value of date into the
211
+ build tag. Install build keys in a deterministic order
212
+ to avoid arbitrary reordering on subsequent builds.
213
+ """
214
+ # follow the order these keys would have been added
215
+ # when PYTHONHASHSEED=0
216
+ egg_info = dict(tag_build=self.tags(), tag_date=0)
217
+ edit_config(filename, dict(egg_info=egg_info))
218
+
219
+ def finalize_options(self) -> None:
220
+ # Note: we need to capture the current value returned
221
+ # by `self.tagged_version()`, so we can later update
222
+ # `self.distribution.metadata.version` without
223
+ # repercussions.
224
+ self.egg_name = self.name
225
+ self.egg_version = self.tagged_version()
226
+ parsed_version = packaging.version.Version(self.egg_version)
227
+
228
+ try:
229
+ is_version = isinstance(parsed_version, packaging.version.Version)
230
+ spec = "%s==%s" if is_version else "%s===%s"
231
+ packaging.requirements.Requirement(spec % (self.egg_name, self.egg_version))
232
+ except ValueError as e:
233
+ raise distutils.errors.DistutilsOptionError(
234
+ f"Invalid distribution name or version syntax: {self.egg_name}-{self.egg_version}"
235
+ ) from e
236
+
237
+ if self.egg_base is None:
238
+ dirs = self.distribution.package_dir
239
+ self.egg_base = (dirs or {}).get('', os.curdir)
240
+
241
+ self.ensure_dirname('egg_base')
242
+ self.egg_info = _normalization.filename_component(self.egg_name) + '.egg-info'
243
+ if self.egg_base != os.curdir:
244
+ self.egg_info = os.path.join(self.egg_base, self.egg_info)
245
+
246
+ # Set package version for the benefit of dumber commands
247
+ # (e.g. sdist, bdist_wininst, etc.)
248
+ #
249
+ self.distribution.metadata.version = self.egg_version
250
+
251
+ def _get_egg_basename(self, py_version=PY_MAJOR, platform=None):
252
+ """Compute filename of the output egg. Private API."""
253
+ return _egg_basename(self.egg_name, self.egg_version, py_version, platform)
254
+
255
+ def write_or_delete_file(self, what, filename, data, force: bool = False) -> None:
256
+ """Write `data` to `filename` or delete if empty
257
+
258
+ If `data` is non-empty, this routine is the same as ``write_file()``.
259
+ If `data` is empty but not ``None``, this is the same as calling
260
+ ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
261
+ unless `filename` exists, in which case a warning is issued about the
262
+ orphaned file (if `force` is false), or deleted (if `force` is true).
263
+ """
264
+ if data:
265
+ self.write_file(what, filename, data)
266
+ elif os.path.exists(filename):
267
+ if data is None and not force:
268
+ log.warn("%s not set in setup(), but %s exists", what, filename)
269
+ return
270
+ else:
271
+ self.delete_file(filename)
272
+
273
+ def write_file(self, what, filename, data) -> None:
274
+ """Write `data` to `filename` (if not a dry run) after announcing it
275
+
276
+ `what` is used in a log message to identify what is being written
277
+ to the file.
278
+ """
279
+ log.info("writing %s to %s", what, filename)
280
+ data = data.encode("utf-8")
281
+ if not self.dry_run:
282
+ f = open(filename, 'wb')
283
+ f.write(data)
284
+ f.close()
285
+
286
+ def delete_file(self, filename) -> None:
287
+ """Delete `filename` (if not a dry run) after announcing it"""
288
+ log.info("deleting %s", filename)
289
+ if not self.dry_run:
290
+ os.unlink(filename)
291
+
292
+ def run(self) -> None:
293
+ # Pre-load to avoid iterating over entry-points while an empty .egg-info
294
+ # exists in sys.path. See pypa/pyproject-hooks#206
295
+ writers = list(metadata.entry_points(group='egg_info.writers'))
296
+
297
+ self.mkpath(self.egg_info)
298
+ try:
299
+ os.utime(self.egg_info, None)
300
+ except OSError as e:
301
+ msg = f"Cannot update time stamp of directory '{self.egg_info}'"
302
+ raise distutils.errors.DistutilsFileError(msg) from e
303
+ for ep in writers:
304
+ writer = ep.load()
305
+ writer(self, ep.name, os.path.join(self.egg_info, ep.name))
306
+
307
+ # Get rid of native_libs.txt if it was put there by older bdist_egg
308
+ nl = os.path.join(self.egg_info, "native_libs.txt")
309
+ if os.path.exists(nl):
310
+ self.delete_file(nl)
311
+
312
+ self.find_sources()
313
+
314
+ def find_sources(self) -> None:
315
+ """Generate SOURCES.txt manifest file"""
316
+ manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
317
+ mm = manifest_maker(self.distribution)
318
+ mm.ignore_egg_info_dir = self.ignore_egg_info_in_manifest
319
+ mm.manifest = manifest_filename
320
+ mm.run()
321
+ self.filelist = mm.filelist
322
+
323
+
324
+ class FileList(_FileList):
325
+ # Implementations of the various MANIFEST.in commands
326
+
327
+ def __init__(
328
+ self, warn=None, debug_print=None, ignore_egg_info_dir: bool = False
329
+ ) -> None:
330
+ super().__init__(warn, debug_print)
331
+ self.ignore_egg_info_dir = ignore_egg_info_dir
332
+
333
+ def process_template_line(self, line) -> None:
334
+ # Parse the line: split it up, make sure the right number of words
335
+ # is there, and return the relevant words. 'action' is always
336
+ # defined: it's the first word of the line. Which of the other
337
+ # three are defined depends on the action; it'll be either
338
+ # patterns, (dir and patterns), or (dir_pattern).
339
+ (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
340
+
341
+ action_map: dict[str, Callable] = {
342
+ 'include': self.include,
343
+ 'exclude': self.exclude,
344
+ 'global-include': self.global_include,
345
+ 'global-exclude': self.global_exclude,
346
+ 'recursive-include': functools.partial(
347
+ self.recursive_include,
348
+ dir,
349
+ ),
350
+ 'recursive-exclude': functools.partial(
351
+ self.recursive_exclude,
352
+ dir,
353
+ ),
354
+ 'graft': self.graft,
355
+ 'prune': self.prune,
356
+ }
357
+ log_map = {
358
+ 'include': "warning: no files found matching '%s'",
359
+ 'exclude': ("warning: no previously-included files found matching '%s'"),
360
+ 'global-include': (
361
+ "warning: no files found matching '%s' anywhere in distribution"
362
+ ),
363
+ 'global-exclude': (
364
+ "warning: no previously-included files matching "
365
+ "'%s' found anywhere in distribution"
366
+ ),
367
+ 'recursive-include': (
368
+ "warning: no files found matching '%s' under directory '%s'"
369
+ ),
370
+ 'recursive-exclude': (
371
+ "warning: no previously-included files matching "
372
+ "'%s' found under directory '%s'"
373
+ ),
374
+ 'graft': "warning: no directories found matching '%s'",
375
+ 'prune': "no previously-included directories found matching '%s'",
376
+ }
377
+
378
+ try:
379
+ process_action = action_map[action]
380
+ except KeyError:
381
+ msg = f"Invalid MANIFEST.in: unknown action {action!r} in {line!r}"
382
+ raise DistutilsInternalError(msg) from None
383
+
384
+ # OK, now we know that the action is valid and we have the
385
+ # right number of words on the line for that action -- so we
386
+ # can proceed with minimal error-checking.
387
+
388
+ action_is_recursive = action.startswith('recursive-')
389
+ if action in {'graft', 'prune'}:
390
+ patterns = [dir_pattern]
391
+ extra_log_args = (dir,) if action_is_recursive else ()
392
+ log_tmpl = log_map[action]
393
+
394
+ self.debug_print(
395
+ ' '.join(
396
+ [action] + ([dir] if action_is_recursive else []) + patterns,
397
+ )
398
+ )
399
+ for pattern in patterns:
400
+ if not process_action(pattern):
401
+ log.warn(log_tmpl, pattern, *extra_log_args)
402
+
403
+ def _remove_files(self, predicate):
404
+ """
405
+ Remove all files from the file list that match the predicate.
406
+ Return True if any matching files were removed
407
+ """
408
+ found = False
409
+ for i in range(len(self.files) - 1, -1, -1):
410
+ if predicate(self.files[i]):
411
+ self.debug_print(" removing " + self.files[i])
412
+ del self.files[i]
413
+ found = True
414
+ return found
415
+
416
+ def include(self, pattern):
417
+ """Include files that match 'pattern'."""
418
+ found = [f for f in glob(pattern) if not os.path.isdir(f)]
419
+ self.extend(found)
420
+ return bool(found)
421
+
422
+ def exclude(self, pattern):
423
+ """Exclude files that match 'pattern'."""
424
+ match = translate_pattern(pattern)
425
+ return self._remove_files(match.match)
426
+
427
+ def recursive_include(self, dir, pattern):
428
+ """
429
+ Include all files anywhere in 'dir/' that match the pattern.
430
+ """
431
+ full_pattern = os.path.join(dir, '**', pattern)
432
+ found = [f for f in glob(full_pattern, recursive=True) if not os.path.isdir(f)]
433
+ self.extend(found)
434
+ return bool(found)
435
+
436
+ def recursive_exclude(self, dir, pattern):
437
+ """
438
+ Exclude any file anywhere in 'dir/' that match the pattern.
439
+ """
440
+ match = translate_pattern(os.path.join(dir, '**', pattern))
441
+ return self._remove_files(match.match)
442
+
443
+ def graft(self, dir):
444
+ """Include all files from 'dir/'."""
445
+ found = [
446
+ item
447
+ for match_dir in glob(dir)
448
+ for item in distutils.filelist.findall(match_dir)
449
+ ]
450
+ self.extend(found)
451
+ return bool(found)
452
+
453
+ def prune(self, dir):
454
+ """Filter out files from 'dir/'."""
455
+ match = translate_pattern(os.path.join(dir, '**'))
456
+ return self._remove_files(match.match)
457
+
458
+ def global_include(self, pattern):
459
+ """
460
+ Include all files anywhere in the current directory that match the
461
+ pattern. This is very inefficient on large file trees.
462
+ """
463
+ if self.allfiles is None:
464
+ self.findall()
465
+ match = translate_pattern(os.path.join('**', pattern))
466
+ found = [f for f in self.allfiles if match.match(f)]
467
+ self.extend(found)
468
+ return bool(found)
469
+
470
+ def global_exclude(self, pattern):
471
+ """
472
+ Exclude all files anywhere that match the pattern.
473
+ """
474
+ match = translate_pattern(os.path.join('**', pattern))
475
+ return self._remove_files(match.match)
476
+
477
+ def append(self, item) -> None:
478
+ if item.endswith('\r'): # Fix older sdists built on Windows
479
+ item = item[:-1]
480
+ path = convert_path(item)
481
+
482
+ if self._safe_path(path):
483
+ self.files.append(path)
484
+
485
+ def extend(self, paths) -> None:
486
+ self.files.extend(filter(self._safe_path, paths))
487
+
488
+ def _repair(self):
489
+ """
490
+ Replace self.files with only safe paths
491
+
492
+ Because some owners of FileList manipulate the underlying
493
+ ``files`` attribute directly, this method must be called to
494
+ repair those paths.
495
+ """
496
+ self.files = list(filter(self._safe_path, self.files))
497
+
498
+ def _safe_path(self, path):
499
+ enc_warn = "'%s' not %s encodable -- skipping"
500
+
501
+ # To avoid accidental trans-codings errors, first to unicode
502
+ u_path = unicode_utils.filesys_decode(path)
503
+ if u_path is None:
504
+ log.warn(f"'{path}' in unexpected encoding -- skipping")
505
+ return False
506
+
507
+ # Must ensure utf-8 encodability
508
+ utf8_path = unicode_utils.try_encode(u_path, "utf-8")
509
+ if utf8_path is None:
510
+ log.warn(enc_warn, path, 'utf-8')
511
+ return False
512
+
513
+ try:
514
+ # ignore egg-info paths
515
+ is_egg_info = ".egg-info" in u_path or b".egg-info" in utf8_path
516
+ if self.ignore_egg_info_dir and is_egg_info:
517
+ return False
518
+ # accept is either way checks out
519
+ if os.path.exists(u_path) or os.path.exists(utf8_path):
520
+ return True
521
+ # this will catch any encode errors decoding u_path
522
+ except UnicodeEncodeError:
523
+ log.warn(enc_warn, path, sys.getfilesystemencoding())
524
+
525
+
526
+ class manifest_maker(sdist):
527
+ template = "MANIFEST.in"
528
+
529
+ def initialize_options(self) -> None:
530
+ self.use_defaults = True
531
+ self.prune = True
532
+ self.manifest_only = True
533
+ self.force_manifest = True
534
+ self.ignore_egg_info_dir = False
535
+
536
+ def finalize_options(self) -> None:
537
+ pass
538
+
539
+ def run(self) -> None:
540
+ self.filelist = FileList(ignore_egg_info_dir=self.ignore_egg_info_dir)
541
+ if not os.path.exists(self.manifest):
542
+ self.write_manifest() # it must exist so it'll get in the list
543
+ self.add_defaults()
544
+ if os.path.exists(self.template):
545
+ self.read_template()
546
+ self.add_license_files()
547
+ self._add_referenced_files()
548
+ self.prune_file_list()
549
+ self.filelist.sort()
550
+ self.filelist.remove_duplicates()
551
+ self.write_manifest()
552
+
553
+ def _manifest_normalize(self, path):
554
+ path = unicode_utils.filesys_decode(path)
555
+ return path.replace(os.sep, '/')
556
+
557
+ def write_manifest(self) -> None:
558
+ """
559
+ Write the file list in 'self.filelist' to the manifest file
560
+ named by 'self.manifest'.
561
+ """
562
+ self.filelist._repair()
563
+
564
+ # Now _repairs should encodability, but not unicode
565
+ files = [self._manifest_normalize(f) for f in self.filelist.files]
566
+ msg = f"writing manifest file '{self.manifest}'"
567
+ self.execute(write_file, (self.manifest, files), msg)
568
+
569
+ def warn(self, msg) -> None:
570
+ if not self._should_suppress_warning(msg):
571
+ sdist.warn(self, msg)
572
+
573
+ @staticmethod
574
+ def _should_suppress_warning(msg):
575
+ """
576
+ suppress missing-file warnings from sdist
577
+ """
578
+ return re.match(r"standard file .*not found", msg)
579
+
580
+ def add_defaults(self) -> None:
581
+ sdist.add_defaults(self)
582
+ self.filelist.append(self.template)
583
+ self.filelist.append(self.manifest)
584
+ rcfiles = list(walk_revctrl())
585
+ if rcfiles:
586
+ self.filelist.extend(rcfiles)
587
+ elif os.path.exists(self.manifest):
588
+ self.read_manifest()
589
+
590
+ if os.path.exists("setup.py"):
591
+ # setup.py should be included by default, even if it's not
592
+ # the script called to create the sdist
593
+ self.filelist.append("setup.py")
594
+
595
+ ei_cmd = self.get_finalized_command('egg_info')
596
+ self.filelist.graft(ei_cmd.egg_info)
597
+
598
+ def add_license_files(self) -> None:
599
+ license_files = self.distribution.metadata.license_files or []
600
+ for lf in license_files:
601
+ log.info("adding license file '%s'", lf)
602
+ self.filelist.extend(license_files)
603
+
604
+ def _add_referenced_files(self):
605
+ """Add files referenced by the config (e.g. `file:` directive) to filelist"""
606
+ referenced = getattr(self.distribution, '_referenced_files', [])
607
+ # ^-- fallback if dist comes from distutils or is a custom class
608
+ for rf in referenced:
609
+ log.debug("adding file referenced by config '%s'", rf)
610
+ self.filelist.extend(referenced)
611
+
612
+ def _safe_data_files(self, build_py):
613
+ """
614
+ The parent class implementation of this method
615
+ (``sdist``) will try to include data files, which
616
+ might cause recursion problems when
617
+ ``include_package_data=True``.
618
+
619
+ Therefore, avoid triggering any attempt of
620
+ analyzing/building the manifest again.
621
+ """
622
+ if hasattr(build_py, 'get_data_files_without_manifest'):
623
+ return build_py.get_data_files_without_manifest()
624
+
625
+ SetuptoolsDeprecationWarning.emit(
626
+ "`build_py` command does not inherit from setuptools' `build_py`.",
627
+ """
628
+ Custom 'build_py' does not implement 'get_data_files_without_manifest'.
629
+ Please extend command classes from setuptools instead of distutils.
630
+ """,
631
+ see_url="https://peps.python.org/pep-0632/",
632
+ # due_date not defined yet, old projects might still do it?
633
+ )
634
+ return build_py.get_data_files()
635
+
636
+
637
+ def write_file(filename, contents) -> None:
638
+ """Create a file with the specified name and write 'contents' (a
639
+ sequence of strings without line terminators) to it.
640
+ """
641
+ contents = "\n".join(contents)
642
+
643
+ # assuming the contents has been vetted for utf-8 encoding
644
+ contents = contents.encode("utf-8")
645
+
646
+ with open(filename, "wb") as f: # always write POSIX-style manifest
647
+ f.write(contents)
648
+
649
+
650
+ def write_pkg_info(cmd, basename, filename) -> None:
651
+ log.info("writing %s", filename)
652
+ if not cmd.dry_run:
653
+ metadata = cmd.distribution.metadata
654
+ metadata.version, oldver = cmd.egg_version, metadata.version
655
+ metadata.name, oldname = cmd.egg_name, metadata.name
656
+
657
+ try:
658
+ metadata.write_pkg_info(cmd.egg_info)
659
+ finally:
660
+ metadata.name, metadata.version = oldname, oldver
661
+
662
+ safe = getattr(cmd.distribution, 'zip_safe', None)
663
+
664
+ bdist_egg.write_safety_flag(cmd.egg_info, safe)
665
+
666
+
667
+ def warn_depends_obsolete(cmd, basename, filename) -> None:
668
+ """
669
+ Unused: left to avoid errors when updating (from source) from <= 67.8.
670
+ Old installations have a .dist-info directory with the entry-point
671
+ ``depends.txt = setuptools.command.egg_info:warn_depends_obsolete``.
672
+ This may trigger errors when running the first egg_info in build_meta.
673
+ TODO: Remove this function in a version sufficiently > 68.
674
+ """
675
+
676
+
677
+ # Export API used in entry_points
678
+ write_requirements = _requirestxt.write_requirements
679
+ write_setup_requirements = _requirestxt.write_setup_requirements
680
+
681
+
682
+ def write_toplevel_names(cmd, basename, filename) -> None:
683
+ pkgs = dict.fromkeys([
684
+ k.split('.', 1)[0] for k in cmd.distribution.iter_distribution_names()
685
+ ])
686
+ cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
687
+
688
+
689
+ def overwrite_arg(cmd, basename, filename) -> None:
690
+ write_arg(cmd, basename, filename, True)
691
+
692
+
693
+ def write_arg(cmd, basename, filename, force: bool = False) -> None:
694
+ argname = os.path.splitext(basename)[0]
695
+ value = getattr(cmd.distribution, argname, None)
696
+ if value is not None:
697
+ value = '\n'.join(value) + '\n'
698
+ cmd.write_or_delete_file(argname, filename, value, force)
699
+
700
+
701
+ def write_entries(cmd, basename, filename) -> None:
702
+ eps = _entry_points.load(cmd.distribution.entry_points)
703
+ defn = _entry_points.render(eps)
704
+ cmd.write_or_delete_file('entry points', filename, defn, True)
705
+
706
+
707
+ def _egg_basename(egg_name, egg_version, py_version=None, platform=None):
708
+ """Compute filename of the output egg. Private API."""
709
+ name = _normalization.filename_component(egg_name)
710
+ version = _normalization.filename_component(egg_version)
711
+ egg = f"{name}-{version}-py{py_version or PY_MAJOR}"
712
+ if platform:
713
+ egg += f"-{platform}"
714
+ return egg
715
+
716
+
717
+ class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):
718
+ """Deprecated behavior warning for EggInfo, bypassing suppression."""
python_embeded/Lib/site-packages/setuptools/command/install.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import platform
5
+ from collections.abc import Callable
6
+ from typing import TYPE_CHECKING, Any, ClassVar
7
+
8
+ from ..dist import Distribution
9
+ from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
10
+
11
+ import distutils.command.install as orig
12
+ from distutils.errors import DistutilsArgError
13
+
14
+ if TYPE_CHECKING:
15
+ # This is only used for a type-cast, don't import at runtime or it'll cause deprecation warnings
16
+ from .easy_install import easy_install as easy_install_cls
17
+ else:
18
+ easy_install_cls = None
19
+
20
+
21
+ def __getattr__(name: str): # pragma: no cover
22
+ if name == "_install":
23
+ SetuptoolsDeprecationWarning.emit(
24
+ "`setuptools.command._install` was an internal implementation detail "
25
+ "that was left in for numpy<1.9 support.",
26
+ due_date=(2025, 5, 2), # Originally added on 2024-11-01
27
+ )
28
+ return orig.install
29
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
30
+
31
+
32
+ class install(orig.install):
33
+ """Use easy_install to install the package, w/dependencies"""
34
+
35
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
36
+
37
+ user_options = orig.install.user_options + [
38
+ ('old-and-unmanageable', None, "Try not to use this!"),
39
+ (
40
+ 'single-version-externally-managed',
41
+ None,
42
+ "used by system package builders to create 'flat' eggs",
43
+ ),
44
+ ]
45
+ boolean_options = orig.install.boolean_options + [
46
+ 'old-and-unmanageable',
47
+ 'single-version-externally-managed',
48
+ ]
49
+ # Type the same as distutils.command.install.install.sub_commands
50
+ # Must keep the second tuple item potentially None due to invariance
51
+ new_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] = [
52
+ ('install_egg_info', lambda self: True),
53
+ ('install_scripts', lambda self: True),
54
+ ]
55
+ _nc = dict(new_commands)
56
+
57
+ def initialize_options(self):
58
+ SetuptoolsDeprecationWarning.emit(
59
+ "setup.py install is deprecated.",
60
+ """
61
+ Please avoid running ``setup.py`` directly.
62
+ Instead, use pypa/build, pypa/installer or other
63
+ standards-based tools.
64
+ """,
65
+ see_url="https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html",
66
+ due_date=(2025, 10, 31),
67
+ )
68
+
69
+ super().initialize_options()
70
+ self.old_and_unmanageable = None
71
+ self.single_version_externally_managed = None
72
+
73
+ def finalize_options(self) -> None:
74
+ super().finalize_options()
75
+ if self.root:
76
+ self.single_version_externally_managed = True
77
+ elif self.single_version_externally_managed:
78
+ if not self.root and not self.record:
79
+ raise DistutilsArgError(
80
+ "You must specify --record or --root when building system packages"
81
+ )
82
+
83
+ def handle_extra_path(self):
84
+ if self.root or self.single_version_externally_managed:
85
+ # explicit backward-compatibility mode, allow extra_path to work
86
+ return orig.install.handle_extra_path(self)
87
+
88
+ # Ignore extra_path when installing an egg (or being run by another
89
+ # command without --root or --single-version-externally-managed
90
+ self.path_file = None
91
+ self.extra_dirs = ''
92
+ return None
93
+
94
+ @staticmethod
95
+ def _called_from_setup(run_frame):
96
+ """
97
+ Attempt to detect whether run() was called from setup() or by another
98
+ command. If called by setup(), the parent caller will be the
99
+ 'run_command' method in 'distutils.dist', and *its* caller will be
100
+ the 'run_commands' method. If called any other way, the
101
+ immediate caller *might* be 'run_command', but it won't have been
102
+ called by 'run_commands'. Return True in that case or if a call stack
103
+ is unavailable. Return False otherwise.
104
+ """
105
+ if run_frame is None:
106
+ msg = "Call stack not available. bdist_* commands may fail."
107
+ SetuptoolsWarning.emit(msg)
108
+ if platform.python_implementation() == 'IronPython':
109
+ msg = "For best results, pass -X:Frames to enable call stack."
110
+ SetuptoolsWarning.emit(msg)
111
+ return True
112
+
113
+ frames = inspect.getouterframes(run_frame)
114
+ for frame in frames[2:4]:
115
+ (caller,) = frame[:1]
116
+ info = inspect.getframeinfo(caller)
117
+ caller_module = caller.f_globals.get('__name__', '')
118
+
119
+ if caller_module == "setuptools.dist" and info.function == "run_command":
120
+ # Starting from v61.0.0 setuptools overwrites dist.run_command
121
+ continue
122
+
123
+ return caller_module == 'distutils.dist' and info.function == 'run_commands'
124
+
125
+ return False
126
+
127
+
128
+ # XXX Python 3.1 doesn't see _nc if this is inside the class
129
+ install.sub_commands = [
130
+ cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc
131
+ ] + install.new_commands
python_embeded/Lib/site-packages/setuptools/command/install_egg_info.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from setuptools import Command, namespaces
4
+ from setuptools.archive_util import unpack_archive
5
+
6
+ from .._path import ensure_directory
7
+
8
+ from distutils import dir_util, log
9
+
10
+
11
+ class install_egg_info(namespaces.Installer, Command):
12
+ """Install an .egg-info directory for the package"""
13
+
14
+ description = "Install an .egg-info directory for the package"
15
+
16
+ user_options = [
17
+ ('install-dir=', 'd', "directory to install to"),
18
+ ]
19
+
20
+ def initialize_options(self):
21
+ self.install_dir = None
22
+
23
+ def finalize_options(self) -> None:
24
+ self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
25
+ ei_cmd = self.get_finalized_command("egg_info")
26
+ basename = f"{ei_cmd._get_egg_basename()}.egg-info"
27
+ self.source = ei_cmd.egg_info
28
+ self.target = os.path.join(self.install_dir, basename)
29
+ self.outputs: list[str] = []
30
+
31
+ def run(self) -> None:
32
+ self.run_command('egg_info')
33
+ if os.path.isdir(self.target) and not os.path.islink(self.target):
34
+ dir_util.remove_tree(self.target, dry_run=self.dry_run)
35
+ elif os.path.exists(self.target):
36
+ self.execute(os.unlink, (self.target,), "Removing " + self.target)
37
+ if not self.dry_run:
38
+ ensure_directory(self.target)
39
+ self.execute(self.copytree, (), f"Copying {self.source} to {self.target}")
40
+ self.install_namespaces()
41
+
42
+ def get_outputs(self):
43
+ return self.outputs
44
+
45
+ def copytree(self) -> None:
46
+ # Copy the .egg-info tree to site-packages
47
+ def skimmer(src, dst):
48
+ # filter out source-control directories; note that 'src' is always
49
+ # a '/'-separated path, regardless of platform. 'dst' is a
50
+ # platform-specific path.
51
+ for skip in '.svn/', 'CVS/':
52
+ if src.startswith(skip) or '/' + skip in src:
53
+ return None
54
+ self.outputs.append(dst)
55
+ log.debug("Copying %s to %s", src, dst)
56
+ return dst
57
+
58
+ unpack_archive(self.source, self.target, skimmer)
python_embeded/Lib/site-packages/setuptools/command/install_lib.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from itertools import product, starmap
6
+
7
+ from .._path import StrPath
8
+ from ..dist import Distribution
9
+
10
+ import distutils.command.install_lib as orig
11
+
12
+
13
+ class install_lib(orig.install_lib):
14
+ """Don't add compiled flags to filenames of non-Python files"""
15
+
16
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
17
+
18
+ def run(self) -> None:
19
+ self.build()
20
+ outfiles = self.install()
21
+ if outfiles is not None:
22
+ # always compile, in case we have any extension stubs to deal with
23
+ self.byte_compile(outfiles)
24
+
25
+ def get_exclusions(self):
26
+ """
27
+ Return a collections.Sized collections.Container of paths to be
28
+ excluded for single_version_externally_managed installations.
29
+ """
30
+ all_packages = (
31
+ pkg
32
+ for ns_pkg in self._get_SVEM_NSPs()
33
+ for pkg in self._all_packages(ns_pkg)
34
+ )
35
+
36
+ excl_specs = product(all_packages, self._gen_exclusion_paths())
37
+ return set(starmap(self._exclude_pkg_path, excl_specs))
38
+
39
+ def _exclude_pkg_path(self, pkg, exclusion_path):
40
+ """
41
+ Given a package name and exclusion path within that package,
42
+ compute the full exclusion path.
43
+ """
44
+ parts = pkg.split('.') + [exclusion_path]
45
+ return os.path.join(self.install_dir, *parts)
46
+
47
+ @staticmethod
48
+ def _all_packages(pkg_name):
49
+ """
50
+ >>> list(install_lib._all_packages('foo.bar.baz'))
51
+ ['foo.bar.baz', 'foo.bar', 'foo']
52
+ """
53
+ while pkg_name:
54
+ yield pkg_name
55
+ pkg_name, _sep, _child = pkg_name.rpartition('.')
56
+
57
+ def _get_SVEM_NSPs(self):
58
+ """
59
+ Get namespace packages (list) but only for
60
+ single_version_externally_managed installations and empty otherwise.
61
+ """
62
+ # TODO: is it necessary to short-circuit here? i.e. what's the cost
63
+ # if get_finalized_command is called even when namespace_packages is
64
+ # False?
65
+ if not self.distribution.namespace_packages:
66
+ return []
67
+
68
+ install_cmd = self.get_finalized_command('install')
69
+ svem = install_cmd.single_version_externally_managed
70
+
71
+ return self.distribution.namespace_packages if svem else []
72
+
73
+ @staticmethod
74
+ def _gen_exclusion_paths():
75
+ """
76
+ Generate file paths to be excluded for namespace packages (bytecode
77
+ cache files).
78
+ """
79
+ # always exclude the package module itself
80
+ yield '__init__.py'
81
+
82
+ yield '__init__.pyc'
83
+ yield '__init__.pyo'
84
+
85
+ if not hasattr(sys, 'implementation'):
86
+ return
87
+
88
+ base = os.path.join('__pycache__', '__init__.' + sys.implementation.cache_tag)
89
+ yield base + '.pyc'
90
+ yield base + '.pyo'
91
+ yield base + '.opt-1.pyc'
92
+ yield base + '.opt-2.pyc'
93
+
94
+ def copy_tree(
95
+ self,
96
+ infile: StrPath,
97
+ outfile: str,
98
+ # override: Using actual booleans
99
+ preserve_mode: bool = True, # type: ignore[override]
100
+ preserve_times: bool = True, # type: ignore[override]
101
+ preserve_symlinks: bool = False, # type: ignore[override]
102
+ level: object = 1,
103
+ ) -> list[str]:
104
+ assert preserve_mode
105
+ assert preserve_times
106
+ assert not preserve_symlinks
107
+ exclude = self.get_exclusions()
108
+
109
+ if not exclude:
110
+ return orig.install_lib.copy_tree(self, infile, outfile)
111
+
112
+ # Exclude namespace package __init__.py* files from the output
113
+
114
+ from setuptools.archive_util import unpack_directory
115
+
116
+ from distutils import log
117
+
118
+ outfiles: list[str] = []
119
+
120
+ def pf(src: str, dst: str):
121
+ if dst in exclude:
122
+ log.warn("Skipping installation of %s (namespace package)", dst)
123
+ return False
124
+
125
+ log.info("copying %s -> %s", src, os.path.dirname(dst))
126
+ outfiles.append(dst)
127
+ return dst
128
+
129
+ unpack_directory(infile, outfile, pf)
130
+ return outfiles
131
+
132
+ def get_outputs(self):
133
+ outputs = orig.install_lib.get_outputs(self)
134
+ exclude = self.get_exclusions()
135
+ if exclude:
136
+ return [f for f in outputs if f not in exclude]
137
+ return outputs
python_embeded/Lib/site-packages/setuptools/command/install_scripts.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+
6
+ from .._path import ensure_directory
7
+ from ..dist import Distribution
8
+
9
+ import distutils.command.install_scripts as orig
10
+ from distutils import log
11
+
12
+
13
+ class install_scripts(orig.install_scripts):
14
+ """Do normal script install, plus any egg_info wrapper scripts"""
15
+
16
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
17
+
18
+ def initialize_options(self) -> None:
19
+ orig.install_scripts.initialize_options(self)
20
+ self.no_ep = False
21
+
22
+ def run(self) -> None:
23
+ self.run_command("egg_info")
24
+ if self.distribution.scripts:
25
+ orig.install_scripts.run(self) # run first to set up self.outfiles
26
+ else:
27
+ self.outfiles: list[str] = []
28
+ if self.no_ep:
29
+ # don't install entry point scripts into .egg file!
30
+ return
31
+ self._install_ep_scripts()
32
+
33
+ def _install_ep_scripts(self):
34
+ # Delay import side-effects
35
+ from .. import _scripts
36
+ from .._importlib import metadata
37
+
38
+ ei_cmd = self.get_finalized_command("egg_info")
39
+ dist = metadata.Distribution.at(path=ei_cmd.egg_info)
40
+ bs_cmd = self.get_finalized_command('build_scripts')
41
+ exec_param = getattr(bs_cmd, 'executable', None)
42
+ writer = _scripts.ScriptWriter
43
+ if exec_param == sys.executable:
44
+ # In case the path to the Python executable contains a space, wrap
45
+ # it so it's not split up.
46
+ exec_param = [exec_param]
47
+ # resolve the writer to the environment
48
+ writer = writer.best()
49
+ cmd = writer.command_spec_class.best().from_param(exec_param)
50
+ for args in writer.get_args(dist, cmd.as_header()):
51
+ self.write_script(*args)
52
+
53
+ def write_script(self, script_name, contents, mode: str = "t", *ignored) -> None:
54
+ """Write an executable file to the scripts directory"""
55
+ from .._shutil import attempt_chmod_verbose as chmod, current_umask
56
+
57
+ log.info("Installing %s script to %s", script_name, self.install_dir)
58
+ target = os.path.join(self.install_dir, script_name)
59
+ self.outfiles.append(target)
60
+
61
+ encoding = None if "b" in mode else "utf-8"
62
+ mask = current_umask()
63
+ if not self.dry_run:
64
+ ensure_directory(target)
65
+ with open(target, "w" + mode, encoding=encoding) as f:
66
+ f.write(contents)
67
+ chmod(target, 0o777 - mask)
python_embeded/Lib/site-packages/setuptools/command/launcher manifest.xml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
3
+ <assemblyIdentity version="1.0.0.0"
4
+ processorArchitecture="X86"
5
+ name="%(name)s"
6
+ type="win32"/>
7
+ <!-- Identify the application security requirements. -->
8
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
9
+ <security>
10
+ <requestedPrivileges>
11
+ <requestedExecutionLevel level="asInvoker" uiAccess="false"/>
12
+ </requestedPrivileges>
13
+ </security>
14
+ </trustInfo>
15
+ </assembly>
python_embeded/Lib/site-packages/setuptools/command/rotate.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import ClassVar
5
+
6
+ from .. import Command, _shutil
7
+
8
+ from distutils import log
9
+ from distutils.errors import DistutilsOptionError
10
+ from distutils.util import convert_path
11
+
12
+
13
+ class rotate(Command):
14
+ """Delete older distributions"""
15
+
16
+ description = "delete older distributions, keeping N newest files"
17
+ user_options = [
18
+ ('match=', 'm', "patterns to match (required)"),
19
+ ('dist-dir=', 'd', "directory where the distributions are"),
20
+ ('keep=', 'k', "number of matching distributions to keep"),
21
+ ]
22
+
23
+ boolean_options: ClassVar[list[str]] = []
24
+
25
+ def initialize_options(self):
26
+ self.match = None
27
+ self.dist_dir = None
28
+ self.keep = None
29
+
30
+ def finalize_options(self) -> None:
31
+ if self.match is None:
32
+ raise DistutilsOptionError(
33
+ "Must specify one or more (comma-separated) match patterns "
34
+ "(e.g. '.zip' or '.egg')"
35
+ )
36
+ if self.keep is None:
37
+ raise DistutilsOptionError("Must specify number of files to keep")
38
+ try:
39
+ self.keep = int(self.keep)
40
+ except ValueError as e:
41
+ raise DistutilsOptionError("--keep must be an integer") from e
42
+ if isinstance(self.match, str):
43
+ self.match = [convert_path(p.strip()) for p in self.match.split(',')]
44
+ self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
45
+
46
+ def run(self) -> None:
47
+ self.run_command("egg_info")
48
+ from glob import glob
49
+
50
+ for pattern in self.match:
51
+ pattern = self.distribution.get_name() + '*' + pattern
52
+ files = glob(os.path.join(self.dist_dir, pattern))
53
+ files = [(os.path.getmtime(f), f) for f in files]
54
+ files.sort()
55
+ files.reverse()
56
+
57
+ log.info("%d file(s) matching %s", len(files), pattern)
58
+ files = files[self.keep :]
59
+ for t, f in files:
60
+ log.info("Deleting %s", f)
61
+ if not self.dry_run:
62
+ if os.path.isdir(f):
63
+ _shutil.rmtree(f)
64
+ else:
65
+ os.unlink(f)
python_embeded/Lib/site-packages/setuptools/command/saveopts.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools.command.setopt import edit_config, option_base
2
+
3
+
4
+ class saveopts(option_base):
5
+ """Save command-line options to a file"""
6
+
7
+ description = "save supplied options to setup.cfg or other config file"
8
+
9
+ def run(self) -> None:
10
+ dist = self.distribution
11
+ settings: dict[str, dict[str, str]] = {}
12
+
13
+ for cmd in dist.command_options:
14
+ if cmd == 'saveopts':
15
+ continue # don't save our own options!
16
+
17
+ for opt, (src, val) in dist.get_option_dict(cmd).items():
18
+ if src == "command line":
19
+ settings.setdefault(cmd, {})[opt] = val
20
+
21
+ edit_config(self.filename, settings, self.dry_run)
python_embeded/Lib/site-packages/setuptools/command/sdist.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import os
5
+ import re
6
+ from itertools import chain
7
+ from typing import ClassVar
8
+
9
+ from .._importlib import metadata
10
+ from ..dist import Distribution
11
+ from .build import _ORIGINAL_SUBCOMMANDS
12
+
13
+ import distutils.command.sdist as orig
14
+ from distutils import log
15
+
16
+ _default_revctrl = list
17
+
18
+
19
+ def walk_revctrl(dirname=''):
20
+ """Find all files under revision control"""
21
+ for ep in metadata.entry_points(group='setuptools.file_finders'):
22
+ yield from ep.load()(dirname)
23
+
24
+
25
+ class sdist(orig.sdist):
26
+ """Smart sdist that finds anything supported by revision control"""
27
+
28
+ user_options = [
29
+ ('formats=', None, "formats for source distribution (comma-separated list)"),
30
+ (
31
+ 'keep-temp',
32
+ 'k',
33
+ "keep the distribution tree around after creating archive file(s)",
34
+ ),
35
+ (
36
+ 'dist-dir=',
37
+ 'd',
38
+ "directory to put the source distribution archive(s) in [default: dist]",
39
+ ),
40
+ (
41
+ 'owner=',
42
+ 'u',
43
+ "Owner name used when creating a tar file [default: current user]",
44
+ ),
45
+ (
46
+ 'group=',
47
+ 'g',
48
+ "Group name used when creating a tar file [default: current group]",
49
+ ),
50
+ ]
51
+
52
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
53
+ negative_opt: ClassVar[dict[str, str]] = {}
54
+
55
+ README_EXTENSIONS = ['', '.rst', '.txt', '.md']
56
+ READMES = tuple(f'README{ext}' for ext in README_EXTENSIONS)
57
+
58
+ def run(self) -> None:
59
+ self.run_command('egg_info')
60
+ ei_cmd = self.get_finalized_command('egg_info')
61
+ self.filelist = ei_cmd.filelist
62
+ self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
63
+ self.check_readme()
64
+
65
+ # Run sub commands
66
+ for cmd_name in self.get_sub_commands():
67
+ self.run_command(cmd_name)
68
+
69
+ self.make_distribution()
70
+
71
+ dist_files = getattr(self.distribution, 'dist_files', [])
72
+ for file in self.archive_files:
73
+ data = ('sdist', '', file)
74
+ if data not in dist_files:
75
+ dist_files.append(data)
76
+
77
+ def initialize_options(self) -> None:
78
+ orig.sdist.initialize_options(self)
79
+
80
+ def make_distribution(self) -> None:
81
+ """
82
+ Workaround for #516
83
+ """
84
+ with self._remove_os_link():
85
+ orig.sdist.make_distribution(self)
86
+
87
+ @staticmethod
88
+ @contextlib.contextmanager
89
+ def _remove_os_link():
90
+ """
91
+ In a context, remove and restore os.link if it exists
92
+ """
93
+
94
+ class NoValue:
95
+ pass
96
+
97
+ orig_val = getattr(os, 'link', NoValue)
98
+ try:
99
+ del os.link
100
+ except Exception:
101
+ pass
102
+ try:
103
+ yield
104
+ finally:
105
+ if orig_val is not NoValue:
106
+ os.link = orig_val
107
+
108
+ def add_defaults(self) -> None:
109
+ super().add_defaults()
110
+ self._add_defaults_build_sub_commands()
111
+
112
+ def _add_defaults_optional(self):
113
+ super()._add_defaults_optional()
114
+ if os.path.isfile('pyproject.toml'):
115
+ self.filelist.append('pyproject.toml')
116
+
117
+ def _add_defaults_python(self):
118
+ """getting python files"""
119
+ if self.distribution.has_pure_modules():
120
+ build_py = self.get_finalized_command('build_py')
121
+ self.filelist.extend(build_py.get_source_files())
122
+ self._add_data_files(self._safe_data_files(build_py))
123
+
124
+ def _add_defaults_build_sub_commands(self):
125
+ build = self.get_finalized_command("build")
126
+ missing_cmds = set(build.get_sub_commands()) - _ORIGINAL_SUBCOMMANDS
127
+ # ^-- the original built-in sub-commands are already handled by default.
128
+ cmds = (self.get_finalized_command(c) for c in missing_cmds)
129
+ files = (c.get_source_files() for c in cmds if hasattr(c, "get_source_files"))
130
+ self.filelist.extend(chain.from_iterable(files))
131
+
132
+ def _safe_data_files(self, build_py):
133
+ """
134
+ Since the ``sdist`` class is also used to compute the MANIFEST
135
+ (via :obj:`setuptools.command.egg_info.manifest_maker`),
136
+ there might be recursion problems when trying to obtain the list of
137
+ data_files and ``include_package_data=True`` (which in turn depends on
138
+ the files included in the MANIFEST).
139
+
140
+ To avoid that, ``manifest_maker`` should be able to overwrite this
141
+ method and avoid recursive attempts to build/analyze the MANIFEST.
142
+ """
143
+ return build_py.data_files
144
+
145
+ def _add_data_files(self, data_files):
146
+ """
147
+ Add data files as found in build_py.data_files.
148
+ """
149
+ self.filelist.extend(
150
+ os.path.join(src_dir, name)
151
+ for _, src_dir, _, filenames in data_files
152
+ for name in filenames
153
+ )
154
+
155
+ def _add_defaults_data_files(self):
156
+ try:
157
+ super()._add_defaults_data_files()
158
+ except TypeError:
159
+ log.warn("data_files contains unexpected objects")
160
+
161
+ def prune_file_list(self) -> None:
162
+ super().prune_file_list()
163
+ # Prevent accidental inclusion of test-related cache dirs at the project root
164
+ sep = re.escape(os.sep)
165
+ self.filelist.exclude_pattern(r"^(\.tox|\.nox|\.venv)" + sep, is_regex=True)
166
+
167
+ def check_readme(self) -> None:
168
+ for f in self.READMES:
169
+ if os.path.exists(f):
170
+ return
171
+ else:
172
+ self.warn(
173
+ "standard file not found: should have one of " + ', '.join(self.READMES)
174
+ )
175
+
176
+ def make_release_tree(self, base_dir, files) -> None:
177
+ orig.sdist.make_release_tree(self, base_dir, files)
178
+
179
+ # Save any egg_info command line options used to create this sdist
180
+ dest = os.path.join(base_dir, 'setup.cfg')
181
+ if hasattr(os, 'link') and os.path.exists(dest):
182
+ # unlink and re-copy, since it might be hard-linked, and
183
+ # we don't want to change the source version
184
+ os.unlink(dest)
185
+ self.copy_file('setup.cfg', dest)
186
+
187
+ self.get_finalized_command('egg_info').save_version_info(dest)
188
+
189
+ def _manifest_is_not_generated(self):
190
+ # check for special comment used in 2.7.1 and higher
191
+ if not os.path.isfile(self.manifest):
192
+ return False
193
+
194
+ with open(self.manifest, 'rb') as fp:
195
+ first_line = fp.readline()
196
+ return first_line != b'# file GENERATED by distutils, do NOT edit\n'
197
+
198
+ def read_manifest(self):
199
+ """Read the manifest file (named by 'self.manifest') and use it to
200
+ fill in 'self.filelist', the list of files to include in the source
201
+ distribution.
202
+ """
203
+ log.info("reading manifest file '%s'", self.manifest)
204
+ manifest = open(self.manifest, 'rb')
205
+ for bytes_line in manifest:
206
+ # The manifest must contain UTF-8. See #303.
207
+ try:
208
+ line = bytes_line.decode('UTF-8')
209
+ except UnicodeDecodeError:
210
+ log.warn(f"{line!r} not UTF-8 decodable -- skipping")
211
+ continue
212
+ # ignore comments and blank lines
213
+ line = line.strip()
214
+ if line.startswith('#') or not line:
215
+ continue
216
+ self.filelist.append(line)
217
+ manifest.close()
python_embeded/Lib/site-packages/setuptools/command/setopt.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import configparser
2
+ import os
3
+
4
+ from .. import Command
5
+ from ..unicode_utils import _cfg_read_utf8_with_fallback
6
+
7
+ import distutils
8
+ from distutils import log
9
+ from distutils.errors import DistutilsOptionError
10
+ from distutils.util import convert_path
11
+
12
+ __all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
13
+
14
+
15
+ def config_file(kind="local"):
16
+ """Get the filename of the distutils, local, global, or per-user config
17
+
18
+ `kind` must be one of "local", "global", or "user"
19
+ """
20
+ if kind == 'local':
21
+ return 'setup.cfg'
22
+ if kind == 'global':
23
+ return os.path.join(os.path.dirname(distutils.__file__), 'distutils.cfg')
24
+ if kind == 'user':
25
+ dot = os.name == 'posix' and '.' or ''
26
+ return os.path.expanduser(convert_path(f"~/{dot}pydistutils.cfg"))
27
+ raise ValueError("config_file() type must be 'local', 'global', or 'user'", kind)
28
+
29
+
30
+ def edit_config(filename, settings, dry_run=False):
31
+ """Edit a configuration file to include `settings`
32
+
33
+ `settings` is a dictionary of dictionaries or ``None`` values, keyed by
34
+ command/section name. A ``None`` value means to delete the entire section,
35
+ while a dictionary lists settings to be changed or deleted in that section.
36
+ A setting of ``None`` means to delete that setting.
37
+ """
38
+ log.debug("Reading configuration from %s", filename)
39
+ opts = configparser.RawConfigParser()
40
+ opts.optionxform = lambda optionstr: optionstr # type: ignore[method-assign] # overriding method
41
+ _cfg_read_utf8_with_fallback(opts, filename)
42
+
43
+ for section, options in settings.items():
44
+ if options is None:
45
+ log.info("Deleting section [%s] from %s", section, filename)
46
+ opts.remove_section(section)
47
+ else:
48
+ if not opts.has_section(section):
49
+ log.debug("Adding new section [%s] to %s", section, filename)
50
+ opts.add_section(section)
51
+ for option, value in options.items():
52
+ if value is None:
53
+ log.debug("Deleting %s.%s from %s", section, option, filename)
54
+ opts.remove_option(section, option)
55
+ if not opts.options(section):
56
+ log.info(
57
+ "Deleting empty [%s] section from %s", section, filename
58
+ )
59
+ opts.remove_section(section)
60
+ else:
61
+ log.debug(
62
+ "Setting %s.%s to %r in %s", section, option, value, filename
63
+ )
64
+ opts.set(section, option, value)
65
+
66
+ log.info("Writing %s", filename)
67
+ if not dry_run:
68
+ with open(filename, 'w', encoding="utf-8") as f:
69
+ opts.write(f)
70
+
71
+
72
+ class option_base(Command):
73
+ """Abstract base class for commands that mess with config files"""
74
+
75
+ user_options = [
76
+ ('global-config', 'g', "save options to the site-wide distutils.cfg file"),
77
+ ('user-config', 'u', "save options to the current user's pydistutils.cfg file"),
78
+ ('filename=', 'f', "configuration file to use (default=setup.cfg)"),
79
+ ]
80
+
81
+ boolean_options = [
82
+ 'global-config',
83
+ 'user-config',
84
+ ]
85
+
86
+ def initialize_options(self):
87
+ self.global_config = None
88
+ self.user_config = None
89
+ self.filename = None
90
+
91
+ def finalize_options(self):
92
+ filenames = []
93
+ if self.global_config:
94
+ filenames.append(config_file('global'))
95
+ if self.user_config:
96
+ filenames.append(config_file('user'))
97
+ if self.filename is not None:
98
+ filenames.append(self.filename)
99
+ if not filenames:
100
+ filenames.append(config_file('local'))
101
+ if len(filenames) > 1:
102
+ raise DistutilsOptionError(
103
+ "Must specify only one configuration file option", filenames
104
+ )
105
+ (self.filename,) = filenames
106
+
107
+
108
+ class setopt(option_base):
109
+ """Save command-line options to a file"""
110
+
111
+ description = "set an option in setup.cfg or another config file"
112
+
113
+ user_options = [
114
+ ('command=', 'c', 'command to set an option for'),
115
+ ('option=', 'o', 'option to set'),
116
+ ('set-value=', 's', 'value of the option'),
117
+ ('remove', 'r', 'remove (unset) the value'),
118
+ ] + option_base.user_options
119
+
120
+ boolean_options = option_base.boolean_options + ['remove']
121
+
122
+ def initialize_options(self):
123
+ option_base.initialize_options(self)
124
+ self.command = None
125
+ self.option = None
126
+ self.set_value = None
127
+ self.remove = None
128
+
129
+ def finalize_options(self) -> None:
130
+ option_base.finalize_options(self)
131
+ if self.command is None or self.option is None:
132
+ raise DistutilsOptionError("Must specify --command *and* --option")
133
+ if self.set_value is None and not self.remove:
134
+ raise DistutilsOptionError("Must specify --set-value or --remove")
135
+
136
+ def run(self) -> None:
137
+ edit_config(
138
+ self.filename,
139
+ {self.command: {self.option.replace('-', '_'): self.set_value}},
140
+ self.dry_run,
141
+ )
python_embeded/Lib/site-packages/setuptools/command/test.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from setuptools import Command
4
+ from setuptools.warnings import SetuptoolsDeprecationWarning
5
+
6
+
7
+ # Would restrict to Literal["test"], but mypy doesn't support it: https://github.com/python/mypy/issues/8203
8
+ def __getattr__(name: str) -> type[_test]:
9
+ if name == 'test':
10
+ SetuptoolsDeprecationWarning.emit(
11
+ "The test command is disabled and references to it are deprecated.",
12
+ "Please remove any references to `setuptools.command.test` in all "
13
+ "supported versions of the affected package.",
14
+ due_date=(2024, 11, 15),
15
+ stacklevel=2,
16
+ )
17
+ return _test
18
+ raise AttributeError(name)
19
+
20
+
21
+ class _test(Command):
22
+ """
23
+ Stub to warn when test command is referenced or used.
24
+ """
25
+
26
+ description = "stub for old test command (do not use)"
27
+
28
+ user_options = [
29
+ ('test-module=', 'm', "Run 'test_suite' in specified module"),
30
+ (
31
+ 'test-suite=',
32
+ 's',
33
+ "Run single test, case or suite (e.g. 'module.test_suite')",
34
+ ),
35
+ ('test-runner=', 'r', "Test runner to use"),
36
+ ]
37
+
38
+ def initialize_options(self):
39
+ pass
40
+
41
+ def finalize_options(self):
42
+ pass
43
+
44
+ def run(self):
45
+ raise RuntimeError("Support for the test command was removed in Setuptools 72")
python_embeded/Lib/site-packages/setuptools/compat/__init__.py ADDED
File without changes
python_embeded/Lib/site-packages/setuptools/compat/py310.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ __all__ = ['tomllib']
4
+
5
+
6
+ if sys.version_info >= (3, 11):
7
+ import tomllib
8
+ else: # pragma: no cover
9
+ import tomli as tomllib
10
+
11
+
12
+ if sys.version_info >= (3, 11):
13
+
14
+ def add_note(ex, note):
15
+ ex.add_note(note)
16
+
17
+ else: # pragma: no cover
18
+
19
+ def add_note(ex, note):
20
+ vars(ex).setdefault('__notes__', []).append(note)
python_embeded/Lib/site-packages/setuptools/compat/py311.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ import sys
5
+ from typing import TYPE_CHECKING, Any, Callable
6
+
7
+ if TYPE_CHECKING:
8
+ from _typeshed import ExcInfo, StrOrBytesPath
9
+ from typing_extensions import TypeAlias
10
+
11
+ # Same as shutil._OnExcCallback from typeshed
12
+ _OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object]
13
+
14
+
15
+ def shutil_rmtree(
16
+ path: StrOrBytesPath,
17
+ ignore_errors: bool = False,
18
+ onexc: _OnExcCallback | None = None,
19
+ ) -> None:
20
+ if sys.version_info >= (3, 12):
21
+ return shutil.rmtree(path, ignore_errors, onexc=onexc)
22
+
23
+ def _handler(fn: Callable[..., Any], path: str, excinfo: ExcInfo) -> None:
24
+ if onexc:
25
+ onexc(fn, path, excinfo[1])
26
+
27
+ return shutil.rmtree(path, ignore_errors, onerror=_handler)
python_embeded/Lib/site-packages/setuptools/compat/py312.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ if sys.version_info >= (3, 12, 4):
6
+ # Python 3.13 should support `.pth` files encoded in UTF-8
7
+ # See discussion in https://github.com/python/cpython/issues/77102
8
+ PTH_ENCODING: str | None = "utf-8"
9
+ else:
10
+ from .py39 import LOCALE_ENCODING
11
+
12
+ # PTH_ENCODING = "locale"
13
+ PTH_ENCODING = LOCALE_ENCODING
python_embeded/Lib/site-packages/setuptools/compat/py39.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ # Explicitly use the ``"locale"`` encoding in versions that support it,
4
+ # otherwise just rely on the implicit handling of ``encoding=None``.
5
+ # Since all platforms that support ``EncodingWarning`` also support
6
+ # ``encoding="locale"``, this can be used to suppress the warning.
7
+ # However, please try to use UTF-8 when possible
8
+ # (.pth files are the notorious exception: python/cpython#77102, pypa/setuptools#3937).
9
+ LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None
python_embeded/Lib/site-packages/setuptools/config/NOTICE ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ The following files include code from opensource projects
2
+ (either as direct copies or modified versions):
3
+
4
+ - `setuptools.schema.json`, `distutils.schema.json`:
5
+ - project: `validate-pyproject` - licensed under MPL-2.0
6
+ (https://github.com/abravalheri/validate-pyproject):
7
+
8
+ This Source Code Form is subject to the terms of the Mozilla Public
9
+ License, v. 2.0. If a copy of the MPL was not distributed with this file,
10
+ You can obtain one at https://mozilla.org/MPL/2.0/.
python_embeded/Lib/site-packages/setuptools/config/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """For backward compatibility, expose main functions from
2
+ ``setuptools.config.setupcfg``
3
+ """
4
+
5
+ from functools import wraps
6
+ from typing import Callable, TypeVar, cast
7
+
8
+ from ..warnings import SetuptoolsDeprecationWarning
9
+ from . import setupcfg
10
+
11
+ Fn = TypeVar("Fn", bound=Callable)
12
+
13
+ __all__ = ('parse_configuration', 'read_configuration')
14
+
15
+
16
+ def _deprecation_notice(fn: Fn) -> Fn:
17
+ @wraps(fn)
18
+ def _wrapper(*args, **kwargs):
19
+ SetuptoolsDeprecationWarning.emit(
20
+ "Deprecated API usage.",
21
+ f"""
22
+ As setuptools moves its configuration towards `pyproject.toml`,
23
+ `{__name__}.{fn.__name__}` became deprecated.
24
+
25
+ For the time being, you can use the `{setupcfg.__name__}` module
26
+ to access a backward compatible API, but this module is provisional
27
+ and might be removed in the future.
28
+
29
+ To read project metadata, consider using
30
+ ``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
31
+ For simple scenarios, you can also try parsing the file directly
32
+ with the help of ``configparser``.
33
+ """,
34
+ # due_date not defined yet, because the community still heavily relies on it
35
+ # Warning introduced in 24 Mar 2022
36
+ )
37
+ return fn(*args, **kwargs)
38
+
39
+ return cast(Fn, _wrapper)
40
+
41
+
42
+ read_configuration = _deprecation_notice(setupcfg.read_configuration)
43
+ parse_configuration = _deprecation_notice(setupcfg.parse_configuration)
python_embeded/Lib/site-packages/setuptools/config/_apply_pyprojecttoml.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Translation layer between pyproject config and setuptools distribution and
2
+ metadata objects.
3
+
4
+ The distribution and metadata objects are modeled after (an old version of)
5
+ core metadata, therefore configs in the format specified for ``pyproject.toml``
6
+ need to be processed before being applied.
7
+
8
+ **PRIVATE MODULE**: API reserved for setuptools internal usage only.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import os
15
+ from collections.abc import Mapping
16
+ from email.headerregistry import Address
17
+ from functools import partial, reduce
18
+ from inspect import cleandoc
19
+ from itertools import chain
20
+ from types import MappingProxyType
21
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union
22
+
23
+ from .. import _static
24
+ from .._path import StrPath
25
+ from ..errors import InvalidConfigError, RemovedConfigError
26
+ from ..extension import Extension
27
+ from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
28
+
29
+ if TYPE_CHECKING:
30
+ from typing_extensions import TypeAlias
31
+
32
+ from setuptools._importlib import metadata
33
+ from setuptools.dist import Distribution
34
+
35
+ from distutils.dist import _OptionsList # Comes from typeshed
36
+
37
+
38
+ EMPTY: Mapping = MappingProxyType({}) # Immutable dict-like
39
+ _ProjectReadmeValue: TypeAlias = Union[str, dict[str, str]]
40
+ _Correspondence: TypeAlias = Callable[["Distribution", Any, Union[StrPath, None]], None]
41
+ _T = TypeVar("_T")
42
+
43
+ _logger = logging.getLogger(__name__)
44
+
45
+
46
+ def apply(dist: Distribution, config: dict, filename: StrPath) -> Distribution:
47
+ """Apply configuration dict read with :func:`read_configuration`"""
48
+
49
+ if not config:
50
+ return dist # short-circuit unrelated pyproject.toml file
51
+
52
+ root_dir = os.path.dirname(filename) or "."
53
+
54
+ _apply_project_table(dist, config, root_dir)
55
+ _apply_tool_table(dist, config, filename)
56
+
57
+ current_directory = os.getcwd()
58
+ os.chdir(root_dir)
59
+ try:
60
+ dist._finalize_requires()
61
+ dist._finalize_license_expression()
62
+ dist._finalize_license_files()
63
+ finally:
64
+ os.chdir(current_directory)
65
+
66
+ return dist
67
+
68
+
69
+ def _apply_project_table(dist: Distribution, config: dict, root_dir: StrPath):
70
+ orig_config = config.get("project", {})
71
+ if not orig_config:
72
+ return # short-circuit
73
+
74
+ project_table = {k: _static.attempt_conversion(v) for k, v in orig_config.items()}
75
+ _handle_missing_dynamic(dist, project_table)
76
+ _unify_entry_points(project_table)
77
+
78
+ for field, value in project_table.items():
79
+ norm_key = json_compatible_key(field)
80
+ corresp = PYPROJECT_CORRESPONDENCE.get(norm_key, norm_key)
81
+ if callable(corresp):
82
+ corresp(dist, value, root_dir)
83
+ else:
84
+ _set_config(dist, corresp, value)
85
+
86
+
87
+ def _apply_tool_table(dist: Distribution, config: dict, filename: StrPath):
88
+ tool_table = config.get("tool", {}).get("setuptools", {})
89
+ if not tool_table:
90
+ return # short-circuit
91
+
92
+ if "license-files" in tool_table:
93
+ if "license-files" in config.get("project", {}):
94
+ # https://github.com/pypa/setuptools/pull/4837#discussion_r2004983349
95
+ raise InvalidConfigError(
96
+ "'project.license-files' is defined already. "
97
+ "Remove 'tool.setuptools.license-files'."
98
+ )
99
+
100
+ pypa_guides = "guides/writing-pyproject-toml/#license-files"
101
+ SetuptoolsDeprecationWarning.emit(
102
+ "'tool.setuptools.license-files' is deprecated in favor of "
103
+ "'project.license-files' (available on setuptools>=77.0.0).",
104
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
105
+ due_date=(2026, 2, 18), # Warning introduced on 2025-02-18
106
+ )
107
+
108
+ for field, value in tool_table.items():
109
+ norm_key = json_compatible_key(field)
110
+
111
+ if norm_key in TOOL_TABLE_REMOVALS:
112
+ suggestion = cleandoc(TOOL_TABLE_REMOVALS[norm_key])
113
+ msg = f"""
114
+ The parameter `tool.setuptools.{field}` was long deprecated
115
+ and has been removed from `pyproject.toml`.
116
+ """
117
+ raise RemovedConfigError("\n".join([cleandoc(msg), suggestion]))
118
+
119
+ norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)
120
+ corresp = TOOL_TABLE_CORRESPONDENCE.get(norm_key, norm_key)
121
+ if callable(corresp):
122
+ corresp(dist, value)
123
+ else:
124
+ _set_config(dist, corresp, value)
125
+
126
+ _copy_command_options(config, dist, filename)
127
+
128
+
129
+ def _handle_missing_dynamic(dist: Distribution, project_table: dict):
130
+ """Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``"""
131
+ dynamic = set(project_table.get("dynamic", []))
132
+ for field, getter in _PREVIOUSLY_DEFINED.items():
133
+ if not (field in project_table or field in dynamic):
134
+ value = getter(dist)
135
+ if value:
136
+ _MissingDynamic.emit(field=field, value=value)
137
+ project_table[field] = _RESET_PREVIOUSLY_DEFINED.get(field)
138
+
139
+
140
+ def json_compatible_key(key: str) -> str:
141
+ """As defined in :pep:`566#json-compatible-metadata`"""
142
+ return key.lower().replace("-", "_")
143
+
144
+
145
+ def _set_config(dist: Distribution, field: str, value: Any):
146
+ val = _PREPROCESS.get(field, _noop)(dist, value)
147
+ setter = getattr(dist.metadata, f"set_{field}", None)
148
+ if setter:
149
+ setter(val)
150
+ elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES:
151
+ setattr(dist.metadata, field, val)
152
+ else:
153
+ setattr(dist, field, val)
154
+
155
+
156
+ _CONTENT_TYPES = {
157
+ ".md": "text/markdown",
158
+ ".rst": "text/x-rst",
159
+ ".txt": "text/plain",
160
+ }
161
+
162
+
163
+ def _guess_content_type(file: str) -> str | None:
164
+ _, ext = os.path.splitext(file.lower())
165
+ if not ext:
166
+ return None
167
+
168
+ if ext in _CONTENT_TYPES:
169
+ return _static.Str(_CONTENT_TYPES[ext])
170
+
171
+ valid = ", ".join(f"{k} ({v})" for k, v in _CONTENT_TYPES.items())
172
+ msg = f"only the following file extensions are recognized: {valid}."
173
+ raise ValueError(f"Undefined content type for {file}, {msg}")
174
+
175
+
176
+ def _long_description(
177
+ dist: Distribution, val: _ProjectReadmeValue, root_dir: StrPath | None
178
+ ):
179
+ from setuptools.config import expand
180
+
181
+ file: str | tuple[()]
182
+ if isinstance(val, str):
183
+ file = val
184
+ text = expand.read_files(file, root_dir)
185
+ ctype = _guess_content_type(file)
186
+ else:
187
+ file = val.get("file") or ()
188
+ text = val.get("text") or expand.read_files(file, root_dir)
189
+ ctype = val["content-type"]
190
+
191
+ # XXX: Is it completely safe to assume static?
192
+ _set_config(dist, "long_description", _static.Str(text))
193
+
194
+ if ctype:
195
+ _set_config(dist, "long_description_content_type", _static.Str(ctype))
196
+
197
+ if file:
198
+ dist._referenced_files.add(file)
199
+
200
+
201
+ def _license(dist: Distribution, val: str | dict, root_dir: StrPath | None):
202
+ from setuptools.config import expand
203
+
204
+ if isinstance(val, str):
205
+ if getattr(dist.metadata, "license", None):
206
+ SetuptoolsWarning.emit("`license` overwritten by `pyproject.toml`")
207
+ dist.metadata.license = None
208
+ _set_config(dist, "license_expression", _static.Str(val))
209
+ else:
210
+ pypa_guides = "guides/writing-pyproject-toml/#license"
211
+ SetuptoolsDeprecationWarning.emit(
212
+ "`project.license` as a TOML table is deprecated",
213
+ "Please use a simple string containing a SPDX expression for "
214
+ "`project.license`. You can also use `project.license-files`. "
215
+ "(Both options available on setuptools>=77.0.0).",
216
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
217
+ due_date=(2026, 2, 18), # Introduced on 2025-02-18
218
+ )
219
+ if "file" in val:
220
+ # XXX: Is it completely safe to assume static?
221
+ value = expand.read_files([val["file"]], root_dir)
222
+ _set_config(dist, "license", _static.Str(value))
223
+ dist._referenced_files.add(val["file"])
224
+ else:
225
+ _set_config(dist, "license", _static.Str(val["text"]))
226
+
227
+
228
+ def _people(dist: Distribution, val: list[dict], _root_dir: StrPath | None, kind: str):
229
+ field = []
230
+ email_field = []
231
+ for person in val:
232
+ if "name" not in person:
233
+ email_field.append(person["email"])
234
+ elif "email" not in person:
235
+ field.append(person["name"])
236
+ else:
237
+ addr = Address(display_name=person["name"], addr_spec=person["email"])
238
+ email_field.append(str(addr))
239
+
240
+ if field:
241
+ _set_config(dist, kind, _static.Str(", ".join(field)))
242
+ if email_field:
243
+ _set_config(dist, f"{kind}_email", _static.Str(", ".join(email_field)))
244
+
245
+
246
+ def _project_urls(dist: Distribution, val: dict, _root_dir: StrPath | None):
247
+ _set_config(dist, "project_urls", val)
248
+
249
+
250
+ def _python_requires(dist: Distribution, val: str, _root_dir: StrPath | None):
251
+ _set_config(dist, "python_requires", _static.SpecifierSet(val))
252
+
253
+
254
+ def _dependencies(dist: Distribution, val: list, _root_dir: StrPath | None):
255
+ if getattr(dist, "install_requires", []):
256
+ msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)"
257
+ SetuptoolsWarning.emit(msg)
258
+ dist.install_requires = val
259
+
260
+
261
+ def _optional_dependencies(dist: Distribution, val: dict, _root_dir: StrPath | None):
262
+ if getattr(dist, "extras_require", None):
263
+ msg = "`extras_require` overwritten in `pyproject.toml` (optional-dependencies)"
264
+ SetuptoolsWarning.emit(msg)
265
+ dist.extras_require = val
266
+
267
+
268
+ def _ext_modules(dist: Distribution, val: list[dict]) -> list[Extension]:
269
+ existing = dist.ext_modules or []
270
+ args = ({k.replace("-", "_"): v for k, v in x.items()} for x in val)
271
+ new = [Extension(**kw) for kw in args]
272
+ return [*existing, *new]
273
+
274
+
275
+ def _noop(_dist: Distribution, val: _T) -> _T:
276
+ return val
277
+
278
+
279
+ def _identity(val: _T) -> _T:
280
+ return val
281
+
282
+
283
+ def _unify_entry_points(project_table: dict):
284
+ project = project_table
285
+ given = project.pop("entry-points", project.pop("entry_points", {}))
286
+ entry_points = dict(given) # Avoid problems with static
287
+ renaming = {"scripts": "console_scripts", "gui_scripts": "gui_scripts"}
288
+ for key, value in list(project.items()): # eager to allow modifications
289
+ norm_key = json_compatible_key(key)
290
+ if norm_key in renaming:
291
+ # Don't skip even if value is empty (reason: reset missing `dynamic`)
292
+ entry_points[renaming[norm_key]] = project.pop(key)
293
+
294
+ if entry_points:
295
+ project["entry-points"] = {
296
+ name: [f"{k} = {v}" for k, v in group.items()]
297
+ for name, group in entry_points.items()
298
+ if group # now we can skip empty groups
299
+ }
300
+ # Sometimes this will set `project["entry-points"] = {}`, and that is
301
+ # intentional (for resetting configurations that are missing `dynamic`).
302
+
303
+
304
+ def _copy_command_options(pyproject: dict, dist: Distribution, filename: StrPath):
305
+ tool_table = pyproject.get("tool", {})
306
+ cmdclass = tool_table.get("setuptools", {}).get("cmdclass", {})
307
+ valid_options = _valid_command_options(cmdclass)
308
+
309
+ cmd_opts = dist.command_options
310
+ for cmd, config in pyproject.get("tool", {}).get("distutils", {}).items():
311
+ cmd = json_compatible_key(cmd)
312
+ valid = valid_options.get(cmd, set())
313
+ cmd_opts.setdefault(cmd, {})
314
+ for key, value in config.items():
315
+ key = json_compatible_key(key)
316
+ cmd_opts[cmd][key] = (str(filename), value)
317
+ if key not in valid:
318
+ # To avoid removing options that are specified dynamically we
319
+ # just log a warn...
320
+ _logger.warning(f"Command option {cmd}.{key} is not defined")
321
+
322
+
323
+ def _valid_command_options(cmdclass: Mapping = EMPTY) -> dict[str, set[str]]:
324
+ from setuptools.dist import Distribution
325
+
326
+ from .._importlib import metadata
327
+
328
+ valid_options = {"global": _normalise_cmd_options(Distribution.global_options)}
329
+
330
+ unloaded_entry_points = metadata.entry_points(group='distutils.commands')
331
+ loaded_entry_points = (_load_ep(ep) for ep in unloaded_entry_points)
332
+ entry_points = (ep for ep in loaded_entry_points if ep)
333
+ for cmd, cmd_class in chain(entry_points, cmdclass.items()):
334
+ opts = valid_options.get(cmd, set())
335
+ opts = opts | _normalise_cmd_options(getattr(cmd_class, "user_options", []))
336
+ valid_options[cmd] = opts
337
+
338
+ return valid_options
339
+
340
+
341
+ def _load_ep(ep: metadata.EntryPoint) -> tuple[str, type] | None:
342
+ if ep.value.startswith("wheel.bdist_wheel"):
343
+ # Ignore deprecated entrypoint from wheel and avoid warning pypa/wheel#631
344
+ # TODO: remove check when `bdist_wheel` has been fully removed from pypa/wheel
345
+ return None
346
+
347
+ # Ignore all the errors
348
+ try:
349
+ return (ep.name, ep.load())
350
+ except Exception as ex:
351
+ msg = f"{ex.__class__.__name__} while trying to load entry-point {ep.name}"
352
+ _logger.warning(f"{msg}: {ex}")
353
+ return None
354
+
355
+
356
+ def _normalise_cmd_option_key(name: str) -> str:
357
+ return json_compatible_key(name).strip("_=")
358
+
359
+
360
+ def _normalise_cmd_options(desc: _OptionsList) -> set[str]:
361
+ return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc}
362
+
363
+
364
+ def _get_previous_entrypoints(dist: Distribution) -> dict[str, list]:
365
+ ignore = ("console_scripts", "gui_scripts")
366
+ value = getattr(dist, "entry_points", None) or {}
367
+ return {k: v for k, v in value.items() if k not in ignore}
368
+
369
+
370
+ def _get_previous_scripts(dist: Distribution) -> list | None:
371
+ value = getattr(dist, "entry_points", None) or {}
372
+ return value.get("console_scripts")
373
+
374
+
375
+ def _get_previous_gui_scripts(dist: Distribution) -> list | None:
376
+ value = getattr(dist, "entry_points", None) or {}
377
+ return value.get("gui_scripts")
378
+
379
+
380
+ def _set_static_list_metadata(attr: str, dist: Distribution, val: list) -> None:
381
+ """Apply distutils metadata validation but preserve "static" behaviour"""
382
+ meta = dist.metadata
383
+ setter, getter = getattr(meta, f"set_{attr}"), getattr(meta, f"get_{attr}")
384
+ setter(val)
385
+ setattr(meta, attr, _static.List(getter()))
386
+
387
+
388
+ def _attrgetter(attr):
389
+ """
390
+ Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found
391
+ >>> from types import SimpleNamespace
392
+ >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
393
+ >>> _attrgetter("a")(obj)
394
+ 42
395
+ >>> _attrgetter("b.c")(obj)
396
+ 13
397
+ >>> _attrgetter("d")(obj) is None
398
+ True
399
+ """
400
+ return partial(reduce, lambda acc, x: getattr(acc, x, None), attr.split("."))
401
+
402
+
403
+ def _some_attrgetter(*items):
404
+ """
405
+ Return the first "truth-y" attribute or None
406
+ >>> from types import SimpleNamespace
407
+ >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
408
+ >>> _some_attrgetter("d", "a", "b.c")(obj)
409
+ 42
410
+ >>> _some_attrgetter("d", "e", "b.c", "a")(obj)
411
+ 13
412
+ >>> _some_attrgetter("d", "e", "f")(obj) is None
413
+ True
414
+ """
415
+
416
+ def _acessor(obj):
417
+ values = (_attrgetter(i)(obj) for i in items)
418
+ return next((i for i in values if i is not None), None)
419
+
420
+ return _acessor
421
+
422
+
423
+ PYPROJECT_CORRESPONDENCE: dict[str, _Correspondence] = {
424
+ "readme": _long_description,
425
+ "license": _license,
426
+ "authors": partial(_people, kind="author"),
427
+ "maintainers": partial(_people, kind="maintainer"),
428
+ "urls": _project_urls,
429
+ "dependencies": _dependencies,
430
+ "optional_dependencies": _optional_dependencies,
431
+ "requires_python": _python_requires,
432
+ }
433
+
434
+ TOOL_TABLE_RENAMES = {"script_files": "scripts"}
435
+ TOOL_TABLE_REMOVALS = {
436
+ "namespace_packages": """
437
+ Please migrate to implicit native namespaces instead.
438
+ See https://packaging.python.org/en/latest/guides/packaging-namespace-packages/.
439
+ """,
440
+ }
441
+ TOOL_TABLE_CORRESPONDENCE = {
442
+ # Fields with corresponding core metadata need to be marked as static:
443
+ "obsoletes": partial(_set_static_list_metadata, "obsoletes"),
444
+ "provides": partial(_set_static_list_metadata, "provides"),
445
+ "platforms": partial(_set_static_list_metadata, "platforms"),
446
+ }
447
+
448
+ SETUPTOOLS_PATCHES = {
449
+ "long_description_content_type",
450
+ "project_urls",
451
+ "provides_extras",
452
+ "license_file",
453
+ "license_files",
454
+ "license_expression",
455
+ }
456
+
457
+ _PREPROCESS = {
458
+ "ext_modules": _ext_modules,
459
+ }
460
+
461
+ _PREVIOUSLY_DEFINED = {
462
+ "name": _attrgetter("metadata.name"),
463
+ "version": _attrgetter("metadata.version"),
464
+ "description": _attrgetter("metadata.description"),
465
+ "readme": _attrgetter("metadata.long_description"),
466
+ "requires-python": _some_attrgetter("python_requires", "metadata.python_requires"),
467
+ "license": _some_attrgetter("metadata.license_expression", "metadata.license"),
468
+ # XXX: `license-file` is currently not considered in the context of `dynamic`.
469
+ # See TestPresetField.test_license_files_exempt_from_dynamic
470
+ "authors": _some_attrgetter("metadata.author", "metadata.author_email"),
471
+ "maintainers": _some_attrgetter("metadata.maintainer", "metadata.maintainer_email"),
472
+ "keywords": _attrgetter("metadata.keywords"),
473
+ "classifiers": _attrgetter("metadata.classifiers"),
474
+ "urls": _attrgetter("metadata.project_urls"),
475
+ "entry-points": _get_previous_entrypoints,
476
+ "scripts": _get_previous_scripts,
477
+ "gui-scripts": _get_previous_gui_scripts,
478
+ "dependencies": _attrgetter("install_requires"),
479
+ "optional-dependencies": _attrgetter("extras_require"),
480
+ }
481
+
482
+
483
+ _RESET_PREVIOUSLY_DEFINED: dict = {
484
+ # Fix improper setting: given in `setup.py`, but not listed in `dynamic`
485
+ # Use "immutable" data structures to avoid in-place modification.
486
+ # dict: pyproject name => value to which reset
487
+ "license": "",
488
+ # XXX: `license-file` is currently not considered in the context of `dynamic`.
489
+ # See TestPresetField.test_license_files_exempt_from_dynamic
490
+ "authors": _static.EMPTY_LIST,
491
+ "maintainers": _static.EMPTY_LIST,
492
+ "keywords": _static.EMPTY_LIST,
493
+ "classifiers": _static.EMPTY_LIST,
494
+ "urls": _static.EMPTY_DICT,
495
+ "entry-points": _static.EMPTY_DICT,
496
+ "scripts": _static.EMPTY_DICT,
497
+ "gui-scripts": _static.EMPTY_DICT,
498
+ "dependencies": _static.EMPTY_LIST,
499
+ "optional-dependencies": _static.EMPTY_DICT,
500
+ }
501
+
502
+
503
+ class _MissingDynamic(SetuptoolsWarning):
504
+ _SUMMARY = "`{field}` defined outside of `pyproject.toml` is ignored."
505
+
506
+ _DETAILS = """
507
+ The following seems to be defined outside of `pyproject.toml`:
508
+
509
+ `{field} = {value!r}`
510
+
511
+ According to the spec (see the link below), however, setuptools CANNOT
512
+ consider this value unless `{field}` is listed as `dynamic`.
513
+
514
+ https://packaging.python.org/en/latest/specifications/pyproject-toml/#declaring-project-metadata-the-project-table
515
+
516
+ To prevent this problem, you can list `{field}` under `dynamic` or alternatively
517
+ remove the `[project]` table from your file and rely entirely on other means of
518
+ configuration.
519
+ """
520
+ # TODO: Consider removing this check in the future?
521
+ # There is a trade-off here between improving "debug-ability" and the cost
522
+ # of running/testing/maintaining these unnecessary checks...
523
+
524
+ @classmethod
525
+ def details(cls, field: str, value: Any) -> str:
526
+ return cls._DETAILS.format(field=field, value=value)
python_embeded/Lib/site-packages/setuptools/config/distutils.schema.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+
4
+ "$id": "https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html",
5
+ "title": "``tool.distutils`` table",
6
+ "$$description": [
7
+ "**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``",
8
+ "subtables to configure arguments for ``distutils`` commands.",
9
+ "Originally, ``distutils`` allowed developers to configure arguments for",
10
+ "``setup.py`` commands via `distutils configuration files",
11
+ "<https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html>`_.",
12
+ "See also `the old Python docs <https://docs.python.org/3.11/install/>_`."
13
+ ],
14
+
15
+ "type": "object",
16
+ "properties": {
17
+ "global": {
18
+ "type": "object",
19
+ "description": "Global options applied to all ``distutils`` commands"
20
+ }
21
+ },
22
+ "patternProperties": {
23
+ ".+": {"type": "object"}
24
+ },
25
+ "$comment": "TODO: Is there a practical way of making this schema more specific?"
26
+ }
python_embeded/Lib/site-packages/setuptools/config/expand.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility functions to expand configuration directives or special values
2
+ (such glob patterns).
3
+
4
+ We can split the process of interpreting configuration files into 2 steps:
5
+
6
+ 1. The parsing the file contents from strings to value objects
7
+ that can be understand by Python (for example a string with a comma
8
+ separated list of keywords into an actual Python list of strings).
9
+
10
+ 2. The expansion (or post-processing) of these values according to the
11
+ semantics ``setuptools`` assign to them (for example a configuration field
12
+ with the ``file:`` directive should be expanded from a list of file paths to
13
+ a single string with the contents of those files concatenated)
14
+
15
+ This module focus on the second step, and therefore allow sharing the expansion
16
+ functions among several configuration file formats.
17
+
18
+ **PRIVATE MODULE**: API reserved for setuptools internal usage only.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import ast
24
+ import importlib
25
+ import os
26
+ import pathlib
27
+ import sys
28
+ from collections.abc import Iterable, Iterator, Mapping
29
+ from configparser import ConfigParser
30
+ from glob import iglob
31
+ from importlib.machinery import ModuleSpec, all_suffixes
32
+ from itertools import chain
33
+ from pathlib import Path
34
+ from types import ModuleType, TracebackType
35
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar
36
+
37
+ from .. import _static
38
+ from .._path import StrPath, same_path as _same_path
39
+ from ..discovery import find_package_path
40
+ from ..warnings import SetuptoolsWarning
41
+
42
+ from distutils.errors import DistutilsOptionError
43
+
44
+ if TYPE_CHECKING:
45
+ from typing_extensions import Self
46
+
47
+ from setuptools.dist import Distribution
48
+
49
+ _K = TypeVar("_K")
50
+ _V_co = TypeVar("_V_co", covariant=True)
51
+
52
+
53
+ class StaticModule:
54
+ """Proxy to a module object that avoids executing arbitrary code."""
55
+
56
+ def __init__(self, name: str, spec: ModuleSpec) -> None:
57
+ module = ast.parse(pathlib.Path(spec.origin).read_bytes()) # type: ignore[arg-type] # Let it raise an error on None
58
+ vars(self).update(locals())
59
+ del self.self
60
+
61
+ def _find_assignments(self) -> Iterator[tuple[ast.AST, ast.AST]]:
62
+ for statement in self.module.body:
63
+ if isinstance(statement, ast.Assign):
64
+ yield from ((target, statement.value) for target in statement.targets)
65
+ elif isinstance(statement, ast.AnnAssign) and statement.value:
66
+ yield (statement.target, statement.value)
67
+
68
+ def __getattr__(self, attr: str):
69
+ """Attempt to load an attribute "statically", via :func:`ast.literal_eval`."""
70
+ try:
71
+ return next(
72
+ ast.literal_eval(value)
73
+ for target, value in self._find_assignments()
74
+ if isinstance(target, ast.Name) and target.id == attr
75
+ )
76
+ except Exception as e:
77
+ raise AttributeError(f"{self.name} has no attribute {attr}") from e
78
+
79
+
80
+ def glob_relative(
81
+ patterns: Iterable[str], root_dir: StrPath | None = None
82
+ ) -> list[str]:
83
+ """Expand the list of glob patterns, but preserving relative paths.
84
+
85
+ :param list[str] patterns: List of glob patterns
86
+ :param str root_dir: Path to which globs should be relative
87
+ (current directory by default)
88
+ :rtype: list
89
+ """
90
+ glob_characters = {'*', '?', '[', ']', '{', '}'}
91
+ expanded_values = []
92
+ root_dir = root_dir or os.getcwd()
93
+ for value in patterns:
94
+ # Has globby characters?
95
+ if any(char in value for char in glob_characters):
96
+ # then expand the glob pattern while keeping paths *relative*:
97
+ glob_path = os.path.abspath(os.path.join(root_dir, value))
98
+ expanded_values.extend(
99
+ sorted(
100
+ os.path.relpath(path, root_dir).replace(os.sep, "/")
101
+ for path in iglob(glob_path, recursive=True)
102
+ )
103
+ )
104
+
105
+ else:
106
+ # take the value as-is
107
+ path = os.path.relpath(value, root_dir).replace(os.sep, "/")
108
+ expanded_values.append(path)
109
+
110
+ return expanded_values
111
+
112
+
113
+ def read_files(
114
+ filepaths: StrPath | Iterable[StrPath], root_dir: StrPath | None = None
115
+ ) -> str:
116
+ """Return the content of the files concatenated using ``\n`` as str
117
+
118
+ This function is sandboxed and won't reach anything outside ``root_dir``
119
+
120
+ (By default ``root_dir`` is the current directory).
121
+ """
122
+ from more_itertools import always_iterable
123
+
124
+ root_dir = os.path.abspath(root_dir or os.getcwd())
125
+ _filepaths = (os.path.join(root_dir, path) for path in always_iterable(filepaths))
126
+ return '\n'.join(
127
+ _read_file(path)
128
+ for path in _filter_existing_files(_filepaths)
129
+ if _assert_local(path, root_dir)
130
+ )
131
+
132
+
133
+ def _filter_existing_files(filepaths: Iterable[StrPath]) -> Iterator[StrPath]:
134
+ for path in filepaths:
135
+ if os.path.isfile(path):
136
+ yield path
137
+ else:
138
+ SetuptoolsWarning.emit(f"File {path!r} cannot be found")
139
+
140
+
141
+ def _read_file(filepath: bytes | StrPath) -> str:
142
+ with open(filepath, encoding='utf-8') as f:
143
+ return f.read()
144
+
145
+
146
+ def _assert_local(filepath: StrPath, root_dir: str):
147
+ if Path(os.path.abspath(root_dir)) not in Path(os.path.abspath(filepath)).parents:
148
+ msg = f"Cannot access {filepath!r} (or anything outside {root_dir!r})"
149
+ raise DistutilsOptionError(msg)
150
+
151
+ return True
152
+
153
+
154
+ def read_attr(
155
+ attr_desc: str,
156
+ package_dir: Mapping[str, str] | None = None,
157
+ root_dir: StrPath | None = None,
158
+ ) -> Any:
159
+ """Reads the value of an attribute from a module.
160
+
161
+ This function will try to read the attributed statically first
162
+ (via :func:`ast.literal_eval`), and only evaluate the module if it fails.
163
+
164
+ Examples:
165
+ read_attr("package.attr")
166
+ read_attr("package.module.attr")
167
+
168
+ :param str attr_desc: Dot-separated string describing how to reach the
169
+ attribute (see examples above)
170
+ :param dict[str, str] package_dir: Mapping of package names to their
171
+ location in disk (represented by paths relative to ``root_dir``).
172
+ :param str root_dir: Path to directory containing all the packages in
173
+ ``package_dir`` (current directory by default).
174
+ :rtype: str
175
+ """
176
+ root_dir = root_dir or os.getcwd()
177
+ attrs_path = attr_desc.strip().split('.')
178
+ attr_name = attrs_path.pop()
179
+ module_name = '.'.join(attrs_path)
180
+ module_name = module_name or '__init__'
181
+ path = _find_module(module_name, package_dir, root_dir)
182
+ spec = _find_spec(module_name, path)
183
+
184
+ try:
185
+ value = getattr(StaticModule(module_name, spec), attr_name)
186
+ # XXX: Is marking as static contents coming from modules too optimistic?
187
+ return _static.attempt_conversion(value)
188
+ except Exception:
189
+ # fallback to evaluate module
190
+ module = _load_spec(spec, module_name)
191
+ return getattr(module, attr_name)
192
+
193
+
194
+ def _find_spec(module_name: str, module_path: StrPath | None) -> ModuleSpec:
195
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
196
+ spec = spec or importlib.util.find_spec(module_name)
197
+
198
+ if spec is None:
199
+ raise ModuleNotFoundError(module_name)
200
+
201
+ return spec
202
+
203
+
204
+ def _load_spec(spec: ModuleSpec, module_name: str) -> ModuleType:
205
+ name = getattr(spec, "__name__", module_name)
206
+ if name in sys.modules:
207
+ return sys.modules[name]
208
+ module = importlib.util.module_from_spec(spec)
209
+ sys.modules[name] = module # cache (it also ensures `==` works on loaded items)
210
+ assert spec.loader is not None
211
+ spec.loader.exec_module(module)
212
+ return module
213
+
214
+
215
+ def _find_module(
216
+ module_name: str, package_dir: Mapping[str, str] | None, root_dir: StrPath
217
+ ) -> str | None:
218
+ """Find the path to the module named ``module_name``,
219
+ considering the ``package_dir`` in the build configuration and ``root_dir``.
220
+
221
+ >>> tmp = getfixture('tmpdir')
222
+ >>> _ = tmp.ensure("a/b/c.py")
223
+ >>> _ = tmp.ensure("a/b/d/__init__.py")
224
+ >>> r = lambda x: x.replace(str(tmp), "tmp").replace(os.sep, "/")
225
+ >>> r(_find_module("a.b.c", None, tmp))
226
+ 'tmp/a/b/c.py'
227
+ >>> r(_find_module("f.g.h", {"": "1", "f": "2", "f.g": "3", "f.g.h": "a/b/d"}, tmp))
228
+ 'tmp/a/b/d/__init__.py'
229
+ """
230
+ path_start = find_package_path(module_name, package_dir or {}, root_dir)
231
+ candidates = chain.from_iterable(
232
+ (f"{path_start}{ext}", os.path.join(path_start, f"__init__{ext}"))
233
+ for ext in all_suffixes()
234
+ )
235
+ return next((x for x in candidates if os.path.isfile(x)), None)
236
+
237
+
238
+ def resolve_class(
239
+ qualified_class_name: str,
240
+ package_dir: Mapping[str, str] | None = None,
241
+ root_dir: StrPath | None = None,
242
+ ) -> Callable:
243
+ """Given a qualified class name, return the associated class object"""
244
+ root_dir = root_dir or os.getcwd()
245
+ idx = qualified_class_name.rfind('.')
246
+ class_name = qualified_class_name[idx + 1 :]
247
+ pkg_name = qualified_class_name[:idx]
248
+
249
+ path = _find_module(pkg_name, package_dir, root_dir)
250
+ module = _load_spec(_find_spec(pkg_name, path), pkg_name)
251
+ return getattr(module, class_name)
252
+
253
+
254
+ def cmdclass(
255
+ values: dict[str, str],
256
+ package_dir: Mapping[str, str] | None = None,
257
+ root_dir: StrPath | None = None,
258
+ ) -> dict[str, Callable]:
259
+ """Given a dictionary mapping command names to strings for qualified class
260
+ names, apply :func:`resolve_class` to the dict values.
261
+ """
262
+ return {k: resolve_class(v, package_dir, root_dir) for k, v in values.items()}
263
+
264
+
265
+ def find_packages(
266
+ *,
267
+ namespaces=True,
268
+ fill_package_dir: dict[str, str] | None = None,
269
+ root_dir: StrPath | None = None,
270
+ **kwargs,
271
+ ) -> list[str]:
272
+ """Works similarly to :func:`setuptools.find_packages`, but with all
273
+ arguments given as keyword arguments. Moreover, ``where`` can be given
274
+ as a list (the results will be simply concatenated).
275
+
276
+ When the additional keyword argument ``namespaces`` is ``True``, it will
277
+ behave like :func:`setuptools.find_namespace_packages`` (i.e. include
278
+ implicit namespaces as per :pep:`420`).
279
+
280
+ The ``where`` argument will be considered relative to ``root_dir`` (or the current
281
+ working directory when ``root_dir`` is not given).
282
+
283
+ If the ``fill_package_dir`` argument is passed, this function will consider it as a
284
+ similar data structure to the ``package_dir`` configuration parameter add fill-in
285
+ any missing package location.
286
+
287
+ :rtype: list
288
+ """
289
+ from more_itertools import always_iterable, unique_everseen
290
+
291
+ from setuptools.discovery import construct_package_dir
292
+
293
+ # check "not namespaces" first due to python/mypy#6232
294
+ if not namespaces:
295
+ from setuptools.discovery import PackageFinder
296
+ else:
297
+ from setuptools.discovery import PEP420PackageFinder as PackageFinder
298
+
299
+ root_dir = root_dir or os.curdir
300
+ where = kwargs.pop('where', ['.'])
301
+ packages: list[str] = []
302
+ fill_package_dir = {} if fill_package_dir is None else fill_package_dir
303
+ search = list(unique_everseen(always_iterable(where)))
304
+
305
+ if len(search) == 1 and all(not _same_path(search[0], x) for x in (".", root_dir)):
306
+ fill_package_dir.setdefault("", search[0])
307
+
308
+ for path in search:
309
+ package_path = _nest_path(root_dir, path)
310
+ pkgs = PackageFinder.find(package_path, **kwargs)
311
+ packages.extend(pkgs)
312
+ if pkgs and not (
313
+ fill_package_dir.get("") == path or os.path.samefile(package_path, root_dir)
314
+ ):
315
+ fill_package_dir.update(construct_package_dir(pkgs, path))
316
+
317
+ return packages
318
+
319
+
320
+ def _nest_path(parent: StrPath, path: StrPath) -> str:
321
+ path = parent if path in {".", ""} else os.path.join(parent, path)
322
+ return os.path.normpath(path)
323
+
324
+
325
+ def version(value: Callable | Iterable[str | int] | str) -> str:
326
+ """When getting the version directly from an attribute,
327
+ it should be normalised to string.
328
+ """
329
+ _value = value() if callable(value) else value
330
+
331
+ if isinstance(_value, str):
332
+ return _value
333
+ if hasattr(_value, '__iter__'):
334
+ return '.'.join(map(str, _value))
335
+ return f'{_value}'
336
+
337
+
338
+ def canonic_package_data(package_data: dict) -> dict:
339
+ if "*" in package_data:
340
+ package_data[""] = package_data.pop("*")
341
+ return package_data
342
+
343
+
344
+ def canonic_data_files(
345
+ data_files: list | dict, root_dir: StrPath | None = None
346
+ ) -> list[tuple[str, list[str]]]:
347
+ """For compatibility with ``setup.py``, ``data_files`` should be a list
348
+ of pairs instead of a dict.
349
+
350
+ This function also expands glob patterns.
351
+ """
352
+ if isinstance(data_files, list):
353
+ return data_files
354
+
355
+ return [
356
+ (dest, glob_relative(patterns, root_dir))
357
+ for dest, patterns in data_files.items()
358
+ ]
359
+
360
+
361
+ def entry_points(
362
+ text: str, text_source: str = "entry-points"
363
+ ) -> dict[str, dict[str, str]]:
364
+ """Given the contents of entry-points file,
365
+ process it into a 2-level dictionary (``dict[str, dict[str, str]]``).
366
+ The first level keys are entry-point groups, the second level keys are
367
+ entry-point names, and the second level values are references to objects
368
+ (that correspond to the entry-point value).
369
+ """
370
+ # Using undocumented behaviour, see python/typeshed#12700
371
+ parser = ConfigParser(default_section=None, delimiters=("=",)) # type: ignore[call-overload]
372
+ parser.optionxform = str # case sensitive
373
+ parser.read_string(text, text_source)
374
+ groups = {k: dict(v.items()) for k, v in parser.items()}
375
+ groups.pop(parser.default_section, None)
376
+ return groups
377
+
378
+
379
+ class EnsurePackagesDiscovered:
380
+ """Some expand functions require all the packages to already be discovered before
381
+ they run, e.g. :func:`read_attr`, :func:`resolve_class`, :func:`cmdclass`.
382
+
383
+ Therefore in some cases we will need to run autodiscovery during the evaluation of
384
+ the configuration. However, it is better to postpone calling package discovery as
385
+ much as possible, because some parameters can influence it (e.g. ``package_dir``),
386
+ and those might not have been processed yet.
387
+ """
388
+
389
+ def __init__(self, distribution: Distribution) -> None:
390
+ self._dist = distribution
391
+ self._called = False
392
+
393
+ def __call__(self):
394
+ """Trigger the automatic package discovery, if it is still necessary."""
395
+ if not self._called:
396
+ self._called = True
397
+ self._dist.set_defaults(name=False) # Skip name, we can still be parsing
398
+
399
+ def __enter__(self) -> Self:
400
+ return self
401
+
402
+ def __exit__(
403
+ self,
404
+ exc_type: type[BaseException] | None,
405
+ exc_value: BaseException | None,
406
+ traceback: TracebackType | None,
407
+ ):
408
+ if self._called:
409
+ self._dist.set_defaults.analyse_name() # Now we can set a default name
410
+
411
+ def _get_package_dir(self) -> Mapping[str, str]:
412
+ self()
413
+ pkg_dir = self._dist.package_dir
414
+ return {} if pkg_dir is None else pkg_dir
415
+
416
+ @property
417
+ def package_dir(self) -> Mapping[str, str]:
418
+ """Proxy to ``package_dir`` that may trigger auto-discovery when used."""
419
+ return LazyMappingProxy(self._get_package_dir)
420
+
421
+
422
+ class LazyMappingProxy(Mapping[_K, _V_co]):
423
+ """Mapping proxy that delays resolving the target object, until really needed.
424
+
425
+ >>> def obtain_mapping():
426
+ ... print("Running expensive function!")
427
+ ... return {"key": "value", "other key": "other value"}
428
+ >>> mapping = LazyMappingProxy(obtain_mapping)
429
+ >>> mapping["key"]
430
+ Running expensive function!
431
+ 'value'
432
+ >>> mapping["other key"]
433
+ 'other value'
434
+ """
435
+
436
+ def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V_co]]) -> None:
437
+ self._obtain = obtain_mapping_value
438
+ self._value: Mapping[_K, _V_co] | None = None
439
+
440
+ def _target(self) -> Mapping[_K, _V_co]:
441
+ if self._value is None:
442
+ self._value = self._obtain()
443
+ return self._value
444
+
445
+ def __getitem__(self, key: _K) -> _V_co:
446
+ return self._target()[key]
447
+
448
+ def __len__(self) -> int:
449
+ return len(self._target())
450
+
451
+ def __iter__(self) -> Iterator[_K]:
452
+ return iter(self._target())
python_embeded/Lib/site-packages/setuptools/config/pyprojecttoml.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Load setuptools configuration from ``pyproject.toml`` files.
3
+
4
+ **PRIVATE MODULE**: API reserved for setuptools internal usage only.
5
+
6
+ To read project metadata, consider using
7
+ ``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
8
+ For simple scenarios, you can also try parsing the file directly
9
+ with the help of ``tomllib`` or ``tomli``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import os
16
+ from collections.abc import Mapping
17
+ from contextlib import contextmanager
18
+ from functools import partial
19
+ from types import TracebackType
20
+ from typing import TYPE_CHECKING, Any, Callable
21
+
22
+ from .._path import StrPath
23
+ from ..errors import FileError, InvalidConfigError
24
+ from ..warnings import SetuptoolsWarning
25
+ from . import expand as _expand
26
+ from ._apply_pyprojecttoml import _PREVIOUSLY_DEFINED, _MissingDynamic, apply as _apply
27
+
28
+ if TYPE_CHECKING:
29
+ from typing_extensions import Self
30
+
31
+ from setuptools.dist import Distribution
32
+
33
+ _logger = logging.getLogger(__name__)
34
+
35
+
36
+ def load_file(filepath: StrPath) -> dict:
37
+ from ..compat.py310 import tomllib
38
+
39
+ with open(filepath, "rb") as file:
40
+ return tomllib.load(file)
41
+
42
+
43
+ def validate(config: dict, filepath: StrPath) -> bool:
44
+ from . import _validate_pyproject as validator
45
+
46
+ trove_classifier = validator.FORMAT_FUNCTIONS.get("trove-classifier")
47
+ if hasattr(trove_classifier, "_disable_download"):
48
+ # Improve reproducibility by default. See abravalheri/validate-pyproject#31
49
+ trove_classifier._disable_download() # type: ignore[union-attr]
50
+
51
+ try:
52
+ return validator.validate(config)
53
+ except validator.ValidationError as ex:
54
+ summary = f"configuration error: {ex.summary}"
55
+ if ex.name.strip("`") != "project":
56
+ # Probably it is just a field missing/misnamed, not worthy the verbosity...
57
+ _logger.debug(summary)
58
+ _logger.debug(ex.details)
59
+
60
+ error = f"invalid pyproject.toml config: {ex.name}."
61
+ raise ValueError(f"{error}\n{summary}") from None
62
+
63
+
64
+ def apply_configuration(
65
+ dist: Distribution,
66
+ filepath: StrPath,
67
+ ignore_option_errors: bool = False,
68
+ ) -> Distribution:
69
+ """Apply the configuration from a ``pyproject.toml`` file into an existing
70
+ distribution object.
71
+ """
72
+ config = read_configuration(filepath, True, ignore_option_errors, dist)
73
+ return _apply(dist, config, filepath)
74
+
75
+
76
+ def read_configuration(
77
+ filepath: StrPath,
78
+ expand: bool = True,
79
+ ignore_option_errors: bool = False,
80
+ dist: Distribution | None = None,
81
+ ) -> dict[str, Any]:
82
+ """Read given configuration file and returns options from it as a dict.
83
+
84
+ :param str|unicode filepath: Path to configuration file in the ``pyproject.toml``
85
+ format.
86
+
87
+ :param bool expand: Whether to expand directives and other computed values
88
+ (i.e. post-process the given configuration)
89
+
90
+ :param bool ignore_option_errors: Whether to silently ignore
91
+ options, values of which could not be resolved (e.g. due to exceptions
92
+ in directives such as file:, attr:, etc.).
93
+ If False exceptions are propagated as expected.
94
+
95
+ :param Distribution|None: Distribution object to which the configuration refers.
96
+ If not given a dummy object will be created and discarded after the
97
+ configuration is read. This is used for auto-discovery of packages and in the
98
+ case a dynamic configuration (e.g. ``attr`` or ``cmdclass``) is expanded.
99
+ When ``expand=False`` this object is simply ignored.
100
+
101
+ :rtype: dict
102
+ """
103
+ filepath = os.path.abspath(filepath)
104
+
105
+ if not os.path.isfile(filepath):
106
+ raise FileError(f"Configuration file {filepath!r} does not exist.")
107
+
108
+ asdict = load_file(filepath) or {}
109
+ project_table = asdict.get("project", {})
110
+ tool_table = asdict.get("tool", {})
111
+ setuptools_table = tool_table.get("setuptools", {})
112
+ if not asdict or not (project_table or setuptools_table):
113
+ return {} # User is not using pyproject to configure setuptools
114
+
115
+ if "setuptools" in asdict.get("tools", {}):
116
+ # let the user know they probably have a typo in their metadata
117
+ _ToolsTypoInMetadata.emit()
118
+
119
+ if "distutils" in tool_table:
120
+ _ExperimentalConfiguration.emit(subject="[tool.distutils]")
121
+
122
+ # There is an overall sense in the community that making include_package_data=True
123
+ # the default would be an improvement.
124
+ # `ini2toml` backfills include_package_data=False when nothing is explicitly given,
125
+ # therefore setting a default here is backwards compatible.
126
+ if dist and dist.include_package_data is not None:
127
+ setuptools_table.setdefault("include-package-data", dist.include_package_data)
128
+ else:
129
+ setuptools_table.setdefault("include-package-data", True)
130
+ # Persist changes:
131
+ asdict["tool"] = tool_table
132
+ tool_table["setuptools"] = setuptools_table
133
+
134
+ if "ext-modules" in setuptools_table:
135
+ _ExperimentalConfiguration.emit(subject="[tool.setuptools.ext-modules]")
136
+
137
+ with _ignore_errors(ignore_option_errors):
138
+ # Don't complain about unrelated errors (e.g. tools not using the "tool" table)
139
+ subset = {"project": project_table, "tool": {"setuptools": setuptools_table}}
140
+ validate(subset, filepath)
141
+
142
+ if expand:
143
+ root_dir = os.path.dirname(filepath)
144
+ return expand_configuration(asdict, root_dir, ignore_option_errors, dist)
145
+
146
+ return asdict
147
+
148
+
149
+ def expand_configuration(
150
+ config: dict,
151
+ root_dir: StrPath | None = None,
152
+ ignore_option_errors: bool = False,
153
+ dist: Distribution | None = None,
154
+ ) -> dict:
155
+ """Given a configuration with unresolved fields (e.g. dynamic, cmdclass, ...)
156
+ find their final values.
157
+
158
+ :param dict config: Dict containing the configuration for the distribution
159
+ :param str root_dir: Top-level directory for the distribution/project
160
+ (the same directory where ``pyproject.toml`` is place)
161
+ :param bool ignore_option_errors: see :func:`read_configuration`
162
+ :param Distribution|None: Distribution object to which the configuration refers.
163
+ If not given a dummy object will be created and discarded after the
164
+ configuration is read. Used in the case a dynamic configuration
165
+ (e.g. ``attr`` or ``cmdclass``).
166
+
167
+ :rtype: dict
168
+ """
169
+ return _ConfigExpander(config, root_dir, ignore_option_errors, dist).expand()
170
+
171
+
172
+ class _ConfigExpander:
173
+ def __init__(
174
+ self,
175
+ config: dict,
176
+ root_dir: StrPath | None = None,
177
+ ignore_option_errors: bool = False,
178
+ dist: Distribution | None = None,
179
+ ) -> None:
180
+ self.config = config
181
+ self.root_dir = root_dir or os.getcwd()
182
+ self.project_cfg = config.get("project", {})
183
+ self.dynamic = self.project_cfg.get("dynamic", [])
184
+ self.setuptools_cfg = config.get("tool", {}).get("setuptools", {})
185
+ self.dynamic_cfg = self.setuptools_cfg.get("dynamic", {})
186
+ self.ignore_option_errors = ignore_option_errors
187
+ self._dist = dist
188
+ self._referenced_files = set[str]()
189
+
190
+ def _ensure_dist(self) -> Distribution:
191
+ from setuptools.dist import Distribution
192
+
193
+ attrs = {"src_root": self.root_dir, "name": self.project_cfg.get("name", None)}
194
+ return self._dist or Distribution(attrs)
195
+
196
+ def _process_field(self, container: dict, field: str, fn: Callable):
197
+ if field in container:
198
+ with _ignore_errors(self.ignore_option_errors):
199
+ container[field] = fn(container[field])
200
+
201
+ def _canonic_package_data(self, field="package-data"):
202
+ package_data = self.setuptools_cfg.get(field, {})
203
+ return _expand.canonic_package_data(package_data)
204
+
205
+ def expand(self):
206
+ self._expand_packages()
207
+ self._canonic_package_data()
208
+ self._canonic_package_data("exclude-package-data")
209
+
210
+ # A distribution object is required for discovering the correct package_dir
211
+ dist = self._ensure_dist()
212
+ ctx = _EnsurePackagesDiscovered(dist, self.project_cfg, self.setuptools_cfg)
213
+ with ctx as ensure_discovered:
214
+ package_dir = ensure_discovered.package_dir
215
+ self._expand_data_files()
216
+ self._expand_cmdclass(package_dir)
217
+ self._expand_all_dynamic(dist, package_dir)
218
+
219
+ dist._referenced_files.update(self._referenced_files)
220
+ return self.config
221
+
222
+ def _expand_packages(self):
223
+ packages = self.setuptools_cfg.get("packages")
224
+ if packages is None or isinstance(packages, (list, tuple)):
225
+ return
226
+
227
+ find = packages.get("find")
228
+ if isinstance(find, dict):
229
+ find["root_dir"] = self.root_dir
230
+ find["fill_package_dir"] = self.setuptools_cfg.setdefault("package-dir", {})
231
+ with _ignore_errors(self.ignore_option_errors):
232
+ self.setuptools_cfg["packages"] = _expand.find_packages(**find)
233
+
234
+ def _expand_data_files(self):
235
+ data_files = partial(_expand.canonic_data_files, root_dir=self.root_dir)
236
+ self._process_field(self.setuptools_cfg, "data-files", data_files)
237
+
238
+ def _expand_cmdclass(self, package_dir: Mapping[str, str]):
239
+ root_dir = self.root_dir
240
+ cmdclass = partial(_expand.cmdclass, package_dir=package_dir, root_dir=root_dir)
241
+ self._process_field(self.setuptools_cfg, "cmdclass", cmdclass)
242
+
243
+ def _expand_all_dynamic(self, dist: Distribution, package_dir: Mapping[str, str]):
244
+ special = ( # need special handling
245
+ "version",
246
+ "readme",
247
+ "entry-points",
248
+ "scripts",
249
+ "gui-scripts",
250
+ "classifiers",
251
+ "dependencies",
252
+ "optional-dependencies",
253
+ )
254
+ # `_obtain` functions are assumed to raise appropriate exceptions/warnings.
255
+ obtained_dynamic = {
256
+ field: self._obtain(dist, field, package_dir)
257
+ for field in self.dynamic
258
+ if field not in special
259
+ }
260
+ obtained_dynamic.update(
261
+ self._obtain_entry_points(dist, package_dir) or {},
262
+ version=self._obtain_version(dist, package_dir),
263
+ readme=self._obtain_readme(dist),
264
+ classifiers=self._obtain_classifiers(dist),
265
+ dependencies=self._obtain_dependencies(dist),
266
+ optional_dependencies=self._obtain_optional_dependencies(dist),
267
+ )
268
+ # `None` indicates there is nothing in `tool.setuptools.dynamic` but the value
269
+ # might have already been set by setup.py/extensions, so avoid overwriting.
270
+ updates = {k: v for k, v in obtained_dynamic.items() if v is not None}
271
+ self.project_cfg.update(updates)
272
+
273
+ def _ensure_previously_set(self, dist: Distribution, field: str):
274
+ previous = _PREVIOUSLY_DEFINED[field](dist)
275
+ if previous is None and not self.ignore_option_errors:
276
+ msg = (
277
+ f"No configuration found for dynamic {field!r}.\n"
278
+ "Some dynamic fields need to be specified via `tool.setuptools.dynamic`"
279
+ "\nothers must be specified via the equivalent attribute in `setup.py`."
280
+ )
281
+ raise InvalidConfigError(msg)
282
+
283
+ def _expand_directive(
284
+ self, specifier: str, directive, package_dir: Mapping[str, str]
285
+ ):
286
+ from more_itertools import always_iterable
287
+
288
+ with _ignore_errors(self.ignore_option_errors):
289
+ root_dir = self.root_dir
290
+ if "file" in directive:
291
+ self._referenced_files.update(always_iterable(directive["file"]))
292
+ return _expand.read_files(directive["file"], root_dir)
293
+ if "attr" in directive:
294
+ return _expand.read_attr(directive["attr"], package_dir, root_dir)
295
+ raise ValueError(f"invalid `{specifier}`: {directive!r}")
296
+ return None
297
+
298
+ def _obtain(self, dist: Distribution, field: str, package_dir: Mapping[str, str]):
299
+ if field in self.dynamic_cfg:
300
+ return self._expand_directive(
301
+ f"tool.setuptools.dynamic.{field}",
302
+ self.dynamic_cfg[field],
303
+ package_dir,
304
+ )
305
+ self._ensure_previously_set(dist, field)
306
+ return None
307
+
308
+ def _obtain_version(self, dist: Distribution, package_dir: Mapping[str, str]):
309
+ # Since plugins can set version, let's silently skip if it cannot be obtained
310
+ if "version" in self.dynamic and "version" in self.dynamic_cfg:
311
+ return _expand.version(
312
+ # We already do an early check for the presence of "version"
313
+ self._obtain(dist, "version", package_dir) # pyright: ignore[reportArgumentType]
314
+ )
315
+ return None
316
+
317
+ def _obtain_readme(self, dist: Distribution) -> dict[str, str] | None:
318
+ if "readme" not in self.dynamic:
319
+ return None
320
+
321
+ dynamic_cfg = self.dynamic_cfg
322
+ if "readme" in dynamic_cfg:
323
+ return {
324
+ # We already do an early check for the presence of "readme"
325
+ "text": self._obtain(dist, "readme", {}),
326
+ "content-type": dynamic_cfg["readme"].get("content-type", "text/x-rst"),
327
+ } # pyright: ignore[reportReturnType]
328
+
329
+ self._ensure_previously_set(dist, "readme")
330
+ return None
331
+
332
+ def _obtain_entry_points(
333
+ self, dist: Distribution, package_dir: Mapping[str, str]
334
+ ) -> dict[str, dict[str, Any]] | None:
335
+ fields = ("entry-points", "scripts", "gui-scripts")
336
+ if not any(field in self.dynamic for field in fields):
337
+ return None
338
+
339
+ text = self._obtain(dist, "entry-points", package_dir)
340
+ if text is None:
341
+ return None
342
+
343
+ groups = _expand.entry_points(text)
344
+ # Any is str | dict[str, str], but causes variance issues
345
+ expanded: dict[str, dict[str, Any]] = {"entry-points": groups}
346
+
347
+ def _set_scripts(field: str, group: str):
348
+ if group in groups:
349
+ value = groups.pop(group)
350
+ if field not in self.dynamic:
351
+ raise InvalidConfigError(_MissingDynamic.details(field, value))
352
+ expanded[field] = value
353
+
354
+ _set_scripts("scripts", "console_scripts")
355
+ _set_scripts("gui-scripts", "gui_scripts")
356
+
357
+ return expanded
358
+
359
+ def _obtain_classifiers(self, dist: Distribution):
360
+ if "classifiers" in self.dynamic:
361
+ value = self._obtain(dist, "classifiers", {})
362
+ if value:
363
+ return value.splitlines()
364
+ return None
365
+
366
+ def _obtain_dependencies(self, dist: Distribution):
367
+ if "dependencies" in self.dynamic:
368
+ value = self._obtain(dist, "dependencies", {})
369
+ if value:
370
+ return _parse_requirements_list(value)
371
+ return None
372
+
373
+ def _obtain_optional_dependencies(self, dist: Distribution):
374
+ if "optional-dependencies" not in self.dynamic:
375
+ return None
376
+ if "optional-dependencies" in self.dynamic_cfg:
377
+ optional_dependencies_map = self.dynamic_cfg["optional-dependencies"]
378
+ assert isinstance(optional_dependencies_map, dict)
379
+ return {
380
+ group: _parse_requirements_list(
381
+ self._expand_directive(
382
+ f"tool.setuptools.dynamic.optional-dependencies.{group}",
383
+ directive,
384
+ {},
385
+ )
386
+ )
387
+ for group, directive in optional_dependencies_map.items()
388
+ }
389
+ self._ensure_previously_set(dist, "optional-dependencies")
390
+ return None
391
+
392
+
393
+ def _parse_requirements_list(value):
394
+ return [
395
+ line
396
+ for line in value.splitlines()
397
+ if line.strip() and not line.strip().startswith("#")
398
+ ]
399
+
400
+
401
+ @contextmanager
402
+ def _ignore_errors(ignore_option_errors: bool):
403
+ if not ignore_option_errors:
404
+ yield
405
+ return
406
+
407
+ try:
408
+ yield
409
+ except Exception as ex:
410
+ _logger.debug(f"ignored error: {ex.__class__.__name__} - {ex}")
411
+
412
+
413
+ class _EnsurePackagesDiscovered(_expand.EnsurePackagesDiscovered):
414
+ def __init__(
415
+ self, distribution: Distribution, project_cfg: dict, setuptools_cfg: dict
416
+ ) -> None:
417
+ super().__init__(distribution)
418
+ self._project_cfg = project_cfg
419
+ self._setuptools_cfg = setuptools_cfg
420
+
421
+ def __enter__(self) -> Self:
422
+ """When entering the context, the values of ``packages``, ``py_modules`` and
423
+ ``package_dir`` that are missing in ``dist`` are copied from ``setuptools_cfg``.
424
+ """
425
+ dist, cfg = self._dist, self._setuptools_cfg
426
+ package_dir: dict[str, str] = cfg.setdefault("package-dir", {})
427
+ package_dir.update(dist.package_dir or {})
428
+ dist.package_dir = package_dir # needs to be the same object
429
+
430
+ dist.set_defaults._ignore_ext_modules() # pyproject.toml-specific behaviour
431
+
432
+ # Set `name`, `py_modules` and `packages` in dist to short-circuit
433
+ # auto-discovery, but avoid overwriting empty lists purposefully set by users.
434
+ if dist.metadata.name is None:
435
+ dist.metadata.name = self._project_cfg.get("name")
436
+ if dist.py_modules is None:
437
+ dist.py_modules = cfg.get("py-modules")
438
+ if dist.packages is None:
439
+ dist.packages = cfg.get("packages")
440
+
441
+ return super().__enter__()
442
+
443
+ def __exit__(
444
+ self,
445
+ exc_type: type[BaseException] | None,
446
+ exc_value: BaseException | None,
447
+ traceback: TracebackType | None,
448
+ ) -> None:
449
+ """When exiting the context, if values of ``packages``, ``py_modules`` and
450
+ ``package_dir`` are missing in ``setuptools_cfg``, copy from ``dist``.
451
+ """
452
+ # If anything was discovered set them back, so they count in the final config.
453
+ self._setuptools_cfg.setdefault("packages", self._dist.packages)
454
+ self._setuptools_cfg.setdefault("py-modules", self._dist.py_modules)
455
+ return super().__exit__(exc_type, exc_value, traceback)
456
+
457
+
458
+ class _ExperimentalConfiguration(SetuptoolsWarning):
459
+ _SUMMARY = (
460
+ "`{subject}` in `pyproject.toml` is still *experimental* "
461
+ "and likely to change in future releases."
462
+ )
463
+
464
+
465
+ class _ToolsTypoInMetadata(SetuptoolsWarning):
466
+ _SUMMARY = (
467
+ "Ignoring [tools.setuptools] in pyproject.toml, did you mean [tool.setuptools]?"
468
+ )
python_embeded/Lib/site-packages/setuptools/config/setupcfg.py ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Load setuptools configuration from ``setup.cfg`` files.
3
+
4
+ **API will be made private in the future**
5
+
6
+ To read project metadata, consider using
7
+ ``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
8
+ For simple scenarios, you can also try parsing the file directly
9
+ with the help of ``configparser``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import functools
16
+ import os
17
+ from collections import defaultdict
18
+ from collections.abc import Iterable, Iterator
19
+ from functools import partial, wraps
20
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, TypeVar, cast
21
+
22
+ from packaging.markers import default_environment as marker_env
23
+ from packaging.requirements import InvalidRequirement, Requirement
24
+ from packaging.version import InvalidVersion, Version
25
+
26
+ from .. import _static
27
+ from .._path import StrPath
28
+ from ..errors import FileError, OptionError
29
+ from ..warnings import SetuptoolsDeprecationWarning
30
+ from . import expand
31
+
32
+ if TYPE_CHECKING:
33
+ from typing_extensions import TypeAlias
34
+
35
+ from setuptools.dist import Distribution
36
+
37
+ from distutils.dist import DistributionMetadata
38
+
39
+ SingleCommandOptions: TypeAlias = dict[str, tuple[str, Any]]
40
+ """Dict that associate the name of the options of a particular command to a
41
+ tuple. The first element of the tuple indicates the origin of the option value
42
+ (e.g. the name of the configuration file where it was read from),
43
+ while the second element of the tuple is the option value itself
44
+ """
45
+ AllCommandOptions: TypeAlias = dict[str, SingleCommandOptions]
46
+ """cmd name => its options"""
47
+ Target = TypeVar("Target", "Distribution", "DistributionMetadata")
48
+
49
+
50
+ def read_configuration(
51
+ filepath: StrPath, find_others: bool = False, ignore_option_errors: bool = False
52
+ ) -> dict:
53
+ """Read given configuration file and returns options from it as a dict.
54
+
55
+ :param str|unicode filepath: Path to configuration file
56
+ to get options from.
57
+
58
+ :param bool find_others: Whether to search for other configuration files
59
+ which could be on in various places.
60
+
61
+ :param bool ignore_option_errors: Whether to silently ignore
62
+ options, values of which could not be resolved (e.g. due to exceptions
63
+ in directives such as file:, attr:, etc.).
64
+ If False exceptions are propagated as expected.
65
+
66
+ :rtype: dict
67
+ """
68
+ from setuptools.dist import Distribution
69
+
70
+ dist = Distribution()
71
+ filenames = dist.find_config_files() if find_others else []
72
+ handlers = _apply(dist, filepath, filenames, ignore_option_errors)
73
+ return configuration_to_dict(handlers)
74
+
75
+
76
+ def apply_configuration(dist: Distribution, filepath: StrPath) -> Distribution:
77
+ """Apply the configuration from a ``setup.cfg`` file into an existing
78
+ distribution object.
79
+ """
80
+ _apply(dist, filepath)
81
+ dist._finalize_requires()
82
+ return dist
83
+
84
+
85
+ def _apply(
86
+ dist: Distribution,
87
+ filepath: StrPath,
88
+ other_files: Iterable[StrPath] = (),
89
+ ignore_option_errors: bool = False,
90
+ ) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]:
91
+ """Read configuration from ``filepath`` and applies to the ``dist`` object."""
92
+ from setuptools.dist import _Distribution
93
+
94
+ filepath = os.path.abspath(filepath)
95
+
96
+ if not os.path.isfile(filepath):
97
+ raise FileError(f'Configuration file {filepath} does not exist.')
98
+
99
+ current_directory = os.getcwd()
100
+ os.chdir(os.path.dirname(filepath))
101
+ filenames = [*other_files, filepath]
102
+
103
+ try:
104
+ # TODO: Temporary cast until mypy 1.12 is released with upstream fixes from typeshed
105
+ _Distribution.parse_config_files(dist, filenames=cast(list[str], filenames))
106
+ handlers = parse_configuration(
107
+ dist, dist.command_options, ignore_option_errors=ignore_option_errors
108
+ )
109
+ dist._finalize_license_files()
110
+ finally:
111
+ os.chdir(current_directory)
112
+
113
+ return handlers
114
+
115
+
116
+ def _get_option(target_obj: Distribution | DistributionMetadata, key: str):
117
+ """
118
+ Given a target object and option key, get that option from
119
+ the target object, either through a get_{key} method or
120
+ from an attribute directly.
121
+ """
122
+ getter_name = f'get_{key}'
123
+ by_attribute = functools.partial(getattr, target_obj, key)
124
+ getter = getattr(target_obj, getter_name, by_attribute)
125
+ return getter()
126
+
127
+
128
+ def configuration_to_dict(
129
+ handlers: Iterable[
130
+ ConfigHandler[Distribution] | ConfigHandler[DistributionMetadata]
131
+ ],
132
+ ) -> dict:
133
+ """Returns configuration data gathered by given handlers as a dict.
134
+
135
+ :param Iterable[ConfigHandler] handlers: Handlers list,
136
+ usually from parse_configuration()
137
+
138
+ :rtype: dict
139
+ """
140
+ config_dict: dict = defaultdict(dict)
141
+
142
+ for handler in handlers:
143
+ for option in handler.set_options:
144
+ value = _get_option(handler.target_obj, option)
145
+ config_dict[handler.section_prefix][option] = value
146
+
147
+ return config_dict
148
+
149
+
150
+ def parse_configuration(
151
+ distribution: Distribution,
152
+ command_options: AllCommandOptions,
153
+ ignore_option_errors: bool = False,
154
+ ) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]:
155
+ """Performs additional parsing of configuration options
156
+ for a distribution.
157
+
158
+ Returns a list of used option handlers.
159
+
160
+ :param Distribution distribution:
161
+ :param dict command_options:
162
+ :param bool ignore_option_errors: Whether to silently ignore
163
+ options, values of which could not be resolved (e.g. due to exceptions
164
+ in directives such as file:, attr:, etc.).
165
+ If False exceptions are propagated as expected.
166
+ :rtype: list
167
+ """
168
+ with expand.EnsurePackagesDiscovered(distribution) as ensure_discovered:
169
+ options = ConfigOptionsHandler(
170
+ distribution,
171
+ command_options,
172
+ ignore_option_errors,
173
+ ensure_discovered,
174
+ )
175
+
176
+ options.parse()
177
+ if not distribution.package_dir:
178
+ distribution.package_dir = options.package_dir # Filled by `find_packages`
179
+
180
+ meta = ConfigMetadataHandler(
181
+ distribution.metadata,
182
+ command_options,
183
+ ignore_option_errors,
184
+ ensure_discovered,
185
+ distribution.package_dir,
186
+ distribution.src_root,
187
+ )
188
+ meta.parse()
189
+ distribution._referenced_files.update(
190
+ options._referenced_files, meta._referenced_files
191
+ )
192
+
193
+ return meta, options
194
+
195
+
196
+ def _warn_accidental_env_marker_misconfig(label: str, orig_value: str, parsed: list):
197
+ """Because users sometimes misinterpret this configuration:
198
+
199
+ [options.extras_require]
200
+ foo = bar;python_version<"4"
201
+
202
+ It looks like one requirement with an environment marker
203
+ but because there is no newline, it's parsed as two requirements
204
+ with a semicolon as separator.
205
+
206
+ Therefore, if:
207
+ * input string does not contain a newline AND
208
+ * parsed result contains two requirements AND
209
+ * parsing of the two parts from the result ("<first>;<second>")
210
+ leads in a valid Requirement with a valid marker
211
+ a UserWarning is shown to inform the user about the possible problem.
212
+ """
213
+ if "\n" in orig_value or len(parsed) != 2:
214
+ return
215
+
216
+ markers = marker_env().keys()
217
+
218
+ try:
219
+ req = Requirement(parsed[1])
220
+ if req.name in markers:
221
+ _AmbiguousMarker.emit(field=label, req=parsed[1])
222
+ except InvalidRequirement as ex:
223
+ if any(parsed[1].startswith(marker) for marker in markers):
224
+ msg = _AmbiguousMarker.message(field=label, req=parsed[1])
225
+ raise InvalidRequirement(msg) from ex
226
+
227
+
228
+ class ConfigHandler(Generic[Target]):
229
+ """Handles metadata supplied in configuration files."""
230
+
231
+ section_prefix: str
232
+ """Prefix for config sections handled by this handler.
233
+ Must be provided by class heirs.
234
+
235
+ """
236
+
237
+ aliases: ClassVar[dict[str, str]] = {}
238
+ """Options aliases.
239
+ For compatibility with various packages. E.g.: d2to1 and pbr.
240
+ Note: `-` in keys is replaced with `_` by config parser.
241
+
242
+ """
243
+
244
+ def __init__(
245
+ self,
246
+ target_obj: Target,
247
+ options: AllCommandOptions,
248
+ ignore_option_errors,
249
+ ensure_discovered: expand.EnsurePackagesDiscovered,
250
+ ) -> None:
251
+ self.ignore_option_errors = ignore_option_errors
252
+ self.target_obj: Target = target_obj
253
+ self.sections = dict(self._section_options(options))
254
+ self.set_options: list[str] = []
255
+ self.ensure_discovered = ensure_discovered
256
+ self._referenced_files = set[str]()
257
+ """After parsing configurations, this property will enumerate
258
+ all files referenced by the "file:" directive. Private API for setuptools only.
259
+ """
260
+
261
+ @classmethod
262
+ def _section_options(
263
+ cls, options: AllCommandOptions
264
+ ) -> Iterator[tuple[str, SingleCommandOptions]]:
265
+ for full_name, value in options.items():
266
+ pre, _sep, name = full_name.partition(cls.section_prefix)
267
+ if pre:
268
+ continue
269
+ yield name.lstrip('.'), value
270
+
271
+ @property
272
+ def parsers(self):
273
+ """Metadata item name to parser function mapping."""
274
+ raise NotImplementedError(
275
+ f'{self.__class__.__name__} must provide .parsers property'
276
+ )
277
+
278
+ def __setitem__(self, option_name, value) -> None:
279
+ target_obj = self.target_obj
280
+
281
+ # Translate alias into real name.
282
+ option_name = self.aliases.get(option_name, option_name)
283
+
284
+ try:
285
+ current_value = getattr(target_obj, option_name)
286
+ except AttributeError as e:
287
+ raise KeyError(option_name) from e
288
+
289
+ if current_value:
290
+ # Already inhabited. Skipping.
291
+ return
292
+
293
+ try:
294
+ parsed = self.parsers.get(option_name, lambda x: x)(value)
295
+ except (Exception,) * self.ignore_option_errors:
296
+ return
297
+
298
+ simple_setter = functools.partial(target_obj.__setattr__, option_name)
299
+ setter = getattr(target_obj, f"set_{option_name}", simple_setter)
300
+ setter(parsed)
301
+
302
+ self.set_options.append(option_name)
303
+
304
+ @classmethod
305
+ def _parse_list(cls, value, separator=','):
306
+ """Represents value as a list.
307
+
308
+ Value is split either by separator (defaults to comma) or by lines.
309
+
310
+ :param value:
311
+ :param separator: List items separator character.
312
+ :rtype: list
313
+ """
314
+ if isinstance(value, list): # _get_parser_compound case
315
+ return value
316
+
317
+ if '\n' in value:
318
+ value = value.splitlines()
319
+ else:
320
+ value = value.split(separator)
321
+
322
+ return [chunk.strip() for chunk in value if chunk.strip()]
323
+
324
+ @classmethod
325
+ def _parse_dict(cls, value):
326
+ """Represents value as a dict.
327
+
328
+ :param value:
329
+ :rtype: dict
330
+ """
331
+ separator = '='
332
+ result = {}
333
+ for line in cls._parse_list(value):
334
+ key, sep, val = line.partition(separator)
335
+ if sep != separator:
336
+ raise OptionError(f"Unable to parse option value to dict: {value}")
337
+ result[key.strip()] = val.strip()
338
+
339
+ return result
340
+
341
+ @classmethod
342
+ def _parse_bool(cls, value):
343
+ """Represents value as boolean.
344
+
345
+ :param value:
346
+ :rtype: bool
347
+ """
348
+ value = value.lower()
349
+ return value in ('1', 'true', 'yes')
350
+
351
+ @classmethod
352
+ def _exclude_files_parser(cls, key):
353
+ """Returns a parser function to make sure field inputs
354
+ are not files.
355
+
356
+ Parses a value after getting the key so error messages are
357
+ more informative.
358
+
359
+ :param key:
360
+ :rtype: callable
361
+ """
362
+
363
+ def parser(value):
364
+ exclude_directive = 'file:'
365
+ if value.startswith(exclude_directive):
366
+ raise ValueError(
367
+ f'Only strings are accepted for the {key} field, '
368
+ 'files are not accepted'
369
+ )
370
+ return _static.Str(value)
371
+
372
+ return parser
373
+
374
+ def _parse_file(self, value, root_dir: StrPath | None):
375
+ """Represents value as a string, allowing including text
376
+ from nearest files using `file:` directive.
377
+
378
+ Directive is sandboxed and won't reach anything outside
379
+ directory with setup.py.
380
+
381
+ Examples:
382
+ file: README.rst, CHANGELOG.md, src/file.txt
383
+
384
+ :param str value:
385
+ :rtype: str
386
+ """
387
+ include_directive = 'file:'
388
+
389
+ if not isinstance(value, str):
390
+ return value
391
+
392
+ if not value.startswith(include_directive):
393
+ return _static.Str(value)
394
+
395
+ spec = value[len(include_directive) :]
396
+ filepaths = [path.strip() for path in spec.split(',')]
397
+ self._referenced_files.update(filepaths)
398
+ # XXX: Is marking as static contents coming from files too optimistic?
399
+ return _static.Str(expand.read_files(filepaths, root_dir))
400
+
401
+ def _parse_attr(self, value, package_dir, root_dir: StrPath):
402
+ """Represents value as a module attribute.
403
+
404
+ Examples:
405
+ attr: package.attr
406
+ attr: package.module.attr
407
+
408
+ :param str value:
409
+ :rtype: str
410
+ """
411
+ attr_directive = 'attr:'
412
+ if not value.startswith(attr_directive):
413
+ return _static.Str(value)
414
+
415
+ attr_desc = value.replace(attr_directive, '')
416
+
417
+ # Make sure package_dir is populated correctly, so `attr:` directives can work
418
+ package_dir.update(self.ensure_discovered.package_dir)
419
+ return expand.read_attr(attr_desc, package_dir, root_dir)
420
+
421
+ @classmethod
422
+ def _get_parser_compound(cls, *parse_methods):
423
+ """Returns parser function to represents value as a list.
424
+
425
+ Parses a value applying given methods one after another.
426
+
427
+ :param parse_methods:
428
+ :rtype: callable
429
+ """
430
+
431
+ def parse(value):
432
+ parsed = value
433
+
434
+ for method in parse_methods:
435
+ parsed = method(parsed)
436
+
437
+ return parsed
438
+
439
+ return parse
440
+
441
+ @classmethod
442
+ def _parse_section_to_dict_with_key(cls, section_options, values_parser):
443
+ """Parses section options into a dictionary.
444
+
445
+ Applies a given parser to each option in a section.
446
+
447
+ :param dict section_options:
448
+ :param callable values_parser: function with 2 args corresponding to key, value
449
+ :rtype: dict
450
+ """
451
+ value = {}
452
+ for key, (_, val) in section_options.items():
453
+ value[key] = values_parser(key, val)
454
+ return value
455
+
456
+ @classmethod
457
+ def _parse_section_to_dict(cls, section_options, values_parser=None):
458
+ """Parses section options into a dictionary.
459
+
460
+ Optionally applies a given parser to each value.
461
+
462
+ :param dict section_options:
463
+ :param callable values_parser: function with 1 arg corresponding to option value
464
+ :rtype: dict
465
+ """
466
+ parser = (lambda _, v: values_parser(v)) if values_parser else (lambda _, v: v)
467
+ return cls._parse_section_to_dict_with_key(section_options, parser)
468
+
469
+ def parse_section(self, section_options) -> None:
470
+ """Parses configuration file section.
471
+
472
+ :param dict section_options:
473
+ """
474
+ for name, (_, value) in section_options.items():
475
+ with contextlib.suppress(KeyError):
476
+ # Keep silent for a new option may appear anytime.
477
+ self[name] = value
478
+
479
+ def parse(self) -> None:
480
+ """Parses configuration file items from one
481
+ or more related sections.
482
+
483
+ """
484
+ for section_name, section_options in self.sections.items():
485
+ method_postfix = ''
486
+ if section_name: # [section.option] variant
487
+ method_postfix = f"_{section_name}"
488
+
489
+ section_parser_method: Callable | None = getattr(
490
+ self,
491
+ # Dots in section names are translated into dunderscores.
492
+ f'parse_section{method_postfix}'.replace('.', '__'),
493
+ None,
494
+ )
495
+
496
+ if section_parser_method is None:
497
+ raise OptionError(
498
+ "Unsupported distribution option section: "
499
+ f"[{self.section_prefix}.{section_name}]"
500
+ )
501
+
502
+ section_parser_method(section_options)
503
+
504
+ def _deprecated_config_handler(self, func, msg, **kw):
505
+ """this function will wrap around parameters that are deprecated
506
+
507
+ :param msg: deprecation message
508
+ :param func: function to be wrapped around
509
+ """
510
+
511
+ @wraps(func)
512
+ def config_handler(*args, **kwargs):
513
+ kw.setdefault("stacklevel", 2)
514
+ _DeprecatedConfig.emit("Deprecated config in `setup.cfg`", msg, **kw)
515
+ return func(*args, **kwargs)
516
+
517
+ return config_handler
518
+
519
+
520
+ class ConfigMetadataHandler(ConfigHandler["DistributionMetadata"]):
521
+ section_prefix = 'metadata'
522
+
523
+ aliases = {
524
+ 'home_page': 'url',
525
+ 'summary': 'description',
526
+ 'classifier': 'classifiers',
527
+ 'platform': 'platforms',
528
+ }
529
+
530
+ strict_mode = False
531
+ """We need to keep it loose, to be partially compatible with
532
+ `pbr` and `d2to1` packages which also uses `metadata` section.
533
+
534
+ """
535
+
536
+ def __init__(
537
+ self,
538
+ target_obj: DistributionMetadata,
539
+ options: AllCommandOptions,
540
+ ignore_option_errors: bool,
541
+ ensure_discovered: expand.EnsurePackagesDiscovered,
542
+ package_dir: dict | None = None,
543
+ root_dir: StrPath | None = os.curdir,
544
+ ) -> None:
545
+ super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
546
+ self.package_dir = package_dir
547
+ self.root_dir = root_dir
548
+
549
+ @property
550
+ def parsers(self):
551
+ """Metadata item name to parser function mapping."""
552
+ parse_list_static = self._get_parser_compound(self._parse_list, _static.List)
553
+ parse_dict_static = self._get_parser_compound(self._parse_dict, _static.Dict)
554
+ parse_file = partial(self._parse_file, root_dir=self.root_dir)
555
+ exclude_files_parser = self._exclude_files_parser
556
+
557
+ return {
558
+ 'author': _static.Str,
559
+ 'author_email': _static.Str,
560
+ 'maintainer': _static.Str,
561
+ 'maintainer_email': _static.Str,
562
+ 'platforms': parse_list_static,
563
+ 'keywords': parse_list_static,
564
+ 'provides': parse_list_static,
565
+ 'obsoletes': parse_list_static,
566
+ 'classifiers': self._get_parser_compound(parse_file, parse_list_static),
567
+ 'license': exclude_files_parser('license'),
568
+ 'license_files': parse_list_static,
569
+ 'description': parse_file,
570
+ 'long_description': parse_file,
571
+ 'long_description_content_type': _static.Str,
572
+ 'version': self._parse_version, # Cannot be marked as dynamic
573
+ 'url': _static.Str,
574
+ 'project_urls': parse_dict_static,
575
+ }
576
+
577
+ def _parse_version(self, value):
578
+ """Parses `version` option value.
579
+
580
+ :param value:
581
+ :rtype: str
582
+
583
+ """
584
+ version = self._parse_file(value, self.root_dir)
585
+
586
+ if version != value:
587
+ version = version.strip()
588
+ # Be strict about versions loaded from file because it's easy to
589
+ # accidentally include newlines and other unintended content
590
+ try:
591
+ Version(version)
592
+ except InvalidVersion as e:
593
+ raise OptionError(
594
+ f'Version loaded from {value} does not '
595
+ f'comply with PEP 440: {version}'
596
+ ) from e
597
+
598
+ return version
599
+
600
+ return expand.version(self._parse_attr(value, self.package_dir, self.root_dir))
601
+
602
+
603
+ class ConfigOptionsHandler(ConfigHandler["Distribution"]):
604
+ section_prefix = 'options'
605
+
606
+ def __init__(
607
+ self,
608
+ target_obj: Distribution,
609
+ options: AllCommandOptions,
610
+ ignore_option_errors: bool,
611
+ ensure_discovered: expand.EnsurePackagesDiscovered,
612
+ ) -> None:
613
+ super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
614
+ self.root_dir = target_obj.src_root
615
+ self.package_dir: dict[str, str] = {} # To be filled by `find_packages`
616
+
617
+ @classmethod
618
+ def _parse_list_semicolon(cls, value):
619
+ return cls._parse_list(value, separator=';')
620
+
621
+ def _parse_file_in_root(self, value):
622
+ return self._parse_file(value, root_dir=self.root_dir)
623
+
624
+ def _parse_requirements_list(self, label: str, value: str):
625
+ # Parse a requirements list, either by reading in a `file:`, or a list.
626
+ parsed = self._parse_list_semicolon(self._parse_file_in_root(value))
627
+ _warn_accidental_env_marker_misconfig(label, value, parsed)
628
+ # Filter it to only include lines that are not comments. `parse_list`
629
+ # will have stripped each line and filtered out empties.
630
+ return _static.List(line for line in parsed if not line.startswith("#"))
631
+ # ^-- Use `_static.List` to mark a non-`Dynamic` Core Metadata
632
+
633
+ @property
634
+ def parsers(self):
635
+ """Metadata item name to parser function mapping."""
636
+ parse_list = self._parse_list
637
+ parse_bool = self._parse_bool
638
+ parse_cmdclass = self._parse_cmdclass
639
+
640
+ return {
641
+ 'zip_safe': parse_bool,
642
+ 'include_package_data': parse_bool,
643
+ 'package_dir': self._parse_dict,
644
+ 'scripts': parse_list,
645
+ 'eager_resources': parse_list,
646
+ 'dependency_links': parse_list,
647
+ 'namespace_packages': self._deprecated_config_handler(
648
+ parse_list,
649
+ "The namespace_packages parameter is deprecated, "
650
+ "consider using implicit namespaces instead (PEP 420).",
651
+ # TODO: define due date, see setuptools.dist:check_nsp.
652
+ ),
653
+ 'install_requires': partial( # Core Metadata
654
+ self._parse_requirements_list, "install_requires"
655
+ ),
656
+ 'setup_requires': self._parse_list_semicolon,
657
+ 'packages': self._parse_packages,
658
+ 'entry_points': self._parse_file_in_root,
659
+ 'py_modules': parse_list,
660
+ 'python_requires': _static.SpecifierSet, # Core Metadata
661
+ 'cmdclass': parse_cmdclass,
662
+ }
663
+
664
+ def _parse_cmdclass(self, value):
665
+ package_dir = self.ensure_discovered.package_dir
666
+ return expand.cmdclass(self._parse_dict(value), package_dir, self.root_dir)
667
+
668
+ def _parse_packages(self, value):
669
+ """Parses `packages` option value.
670
+
671
+ :param value:
672
+ :rtype: list
673
+ """
674
+ find_directives = ['find:', 'find_namespace:']
675
+ trimmed_value = value.strip()
676
+
677
+ if trimmed_value not in find_directives:
678
+ return self._parse_list(value)
679
+
680
+ # Read function arguments from a dedicated section.
681
+ find_kwargs = self.parse_section_packages__find(
682
+ self.sections.get('packages.find', {})
683
+ )
684
+
685
+ find_kwargs.update(
686
+ namespaces=(trimmed_value == find_directives[1]),
687
+ root_dir=self.root_dir,
688
+ fill_package_dir=self.package_dir,
689
+ )
690
+
691
+ return expand.find_packages(**find_kwargs)
692
+
693
+ def parse_section_packages__find(self, section_options):
694
+ """Parses `packages.find` configuration file section.
695
+
696
+ To be used in conjunction with _parse_packages().
697
+
698
+ :param dict section_options:
699
+ """
700
+ section_data = self._parse_section_to_dict(section_options, self._parse_list)
701
+
702
+ valid_keys = ['where', 'include', 'exclude']
703
+ find_kwargs = {k: v for k, v in section_data.items() if k in valid_keys and v}
704
+
705
+ where = find_kwargs.get('where')
706
+ if where is not None:
707
+ find_kwargs['where'] = where[0] # cast list to single val
708
+
709
+ return find_kwargs
710
+
711
+ def parse_section_entry_points(self, section_options) -> None:
712
+ """Parses `entry_points` configuration file section.
713
+
714
+ :param dict section_options:
715
+ """
716
+ parsed = self._parse_section_to_dict(section_options, self._parse_list)
717
+ self['entry_points'] = parsed
718
+
719
+ def _parse_package_data(self, section_options):
720
+ package_data = self._parse_section_to_dict(section_options, self._parse_list)
721
+ return expand.canonic_package_data(package_data)
722
+
723
+ def parse_section_package_data(self, section_options) -> None:
724
+ """Parses `package_data` configuration file section.
725
+
726
+ :param dict section_options:
727
+ """
728
+ self['package_data'] = self._parse_package_data(section_options)
729
+
730
+ def parse_section_exclude_package_data(self, section_options) -> None:
731
+ """Parses `exclude_package_data` configuration file section.
732
+
733
+ :param dict section_options:
734
+ """
735
+ self['exclude_package_data'] = self._parse_package_data(section_options)
736
+
737
+ def parse_section_extras_require(self, section_options) -> None: # Core Metadata
738
+ """Parses `extras_require` configuration file section.
739
+
740
+ :param dict section_options:
741
+ """
742
+ parsed = self._parse_section_to_dict_with_key(
743
+ section_options,
744
+ lambda k, v: self._parse_requirements_list(f"extras_require[{k}]", v),
745
+ )
746
+
747
+ self['extras_require'] = _static.Dict(parsed)
748
+ # ^-- Use `_static.Dict` to mark a non-`Dynamic` Core Metadata
749
+
750
+ def parse_section_data_files(self, section_options) -> None:
751
+ """Parses `data_files` configuration file section.
752
+
753
+ :param dict section_options:
754
+ """
755
+ parsed = self._parse_section_to_dict(section_options, self._parse_list)
756
+ self['data_files'] = expand.canonic_data_files(parsed, self.root_dir)
757
+
758
+
759
+ class _AmbiguousMarker(SetuptoolsDeprecationWarning):
760
+ _SUMMARY = "Ambiguous requirement marker."
761
+ _DETAILS = """
762
+ One of the parsed requirements in `{field}` looks like a valid environment marker:
763
+
764
+ {req!r}
765
+
766
+ Please make sure that the configuration file is correct.
767
+ You can use dangling lines to avoid this problem.
768
+ """
769
+ _SEE_DOCS = "userguide/declarative_config.html#opt-2"
770
+ # TODO: should we include due_date here? Initially introduced in 6 Aug 2022.
771
+ # Does this make sense with latest version of packaging?
772
+
773
+ @classmethod
774
+ def message(cls, **kw):
775
+ docs = f"https://setuptools.pypa.io/en/latest/{cls._SEE_DOCS}"
776
+ return cls._format(cls._SUMMARY, cls._DETAILS, see_url=docs, format_args=kw)
777
+
778
+
779
+ class _DeprecatedConfig(SetuptoolsDeprecationWarning):
780
+ _SEE_DOCS = "userguide/declarative_config.html"
python_embeded/Lib/site-packages/setuptools/config/setuptools.schema.json ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+
4
+ "$id": "https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html",
5
+ "title": "``tool.setuptools`` table",
6
+ "$$description": [
7
+ "``setuptools``-specific configurations that can be set by users that require",
8
+ "customization.",
9
+ "These configurations are completely optional and probably can be skipped when",
10
+ "creating simple packages. They are equivalent to some of the `Keywords",
11
+ "<https://setuptools.pypa.io/en/latest/references/keywords.html>`_",
12
+ "used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.",
13
+ "It considers only ``setuptools`` `parameters",
14
+ "<https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html#setuptools-specific-configuration>`_",
15
+ "that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``",
16
+ "and ``setup_requires`` (incompatible with modern workflows/standards)."
17
+ ],
18
+
19
+ "type": "object",
20
+ "additionalProperties": false,
21
+ "properties": {
22
+ "platforms": {
23
+ "type": "array",
24
+ "items": {"type": "string"}
25
+ },
26
+ "provides": {
27
+ "$$description": [
28
+ "Package and virtual package names contained within this package",
29
+ "**(not supported by pip)**"
30
+ ],
31
+ "type": "array",
32
+ "items": {"type": "string", "format": "pep508-identifier"}
33
+ },
34
+ "obsoletes": {
35
+ "$$description": [
36
+ "Packages which this package renders obsolete",
37
+ "**(not supported by pip)**"
38
+ ],
39
+ "type": "array",
40
+ "items": {"type": "string", "format": "pep508-identifier"}
41
+ },
42
+ "zip-safe": {
43
+ "$$description": [
44
+ "Whether the project can be safely installed and run from a zip file.",
45
+ "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
46
+ "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
47
+ ],
48
+ "type": "boolean"
49
+ },
50
+ "script-files": {
51
+ "$$description": [
52
+ "Legacy way of defining scripts (entry-points are preferred).",
53
+ "Equivalent to the ``script`` keyword in ``setup.py``",
54
+ "(it was renamed to avoid confusion with entry-point based ``project.scripts``",
55
+ "defined in :pep:`621`).",
56
+ "**DISCOURAGED**: generic script wrappers are tricky and may not work properly.",
57
+ "Whenever possible, please use ``project.scripts`` instead."
58
+ ],
59
+ "type": "array",
60
+ "items": {"type": "string"},
61
+ "$comment": "TODO: is this field deprecated/should be removed?"
62
+ },
63
+ "eager-resources": {
64
+ "$$description": [
65
+ "Resources that should be extracted together, if any of them is needed,",
66
+ "or if any C extensions included in the project are imported.",
67
+ "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
68
+ "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
69
+ ],
70
+ "type": "array",
71
+ "items": {"type": "string"}
72
+ },
73
+ "packages": {
74
+ "$$description": [
75
+ "Packages that should be included in the distribution.",
76
+ "It can be given either as a list of package identifiers",
77
+ "or as a ``dict``-like structure with a single key ``find``",
78
+ "which corresponds to a dynamic call to",
79
+ "``setuptools.config.expand.find_packages`` function.",
80
+ "The ``find`` key is associated with a nested ``dict``-like structure that can",
81
+ "contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,",
82
+ "mimicking the keyword arguments of the associated function."
83
+ ],
84
+ "oneOf": [
85
+ {
86
+ "title": "Array of Python package identifiers",
87
+ "type": "array",
88
+ "items": {"$ref": "#/definitions/package-name"}
89
+ },
90
+ {"$ref": "#/definitions/find-directive"}
91
+ ]
92
+ },
93
+ "package-dir": {
94
+ "$$description": [
95
+ ":class:`dict`-like structure mapping from package names to directories where their",
96
+ "code can be found.",
97
+ "The empty string (as key) means that all packages are contained inside",
98
+ "the given directory will be included in the distribution."
99
+ ],
100
+ "type": "object",
101
+ "additionalProperties": false,
102
+ "propertyNames": {
103
+ "anyOf": [{"const": ""}, {"$ref": "#/definitions/package-name"}]
104
+ },
105
+ "patternProperties": {
106
+ "^.*$": {"type": "string" }
107
+ }
108
+ },
109
+ "package-data": {
110
+ "$$description": [
111
+ "Mapping from package names to lists of glob patterns.",
112
+ "Usually this option is not needed when using ``include-package-data = true``",
113
+ "For more information on how to include data files, check ``setuptools`` `docs",
114
+ "<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_."
115
+ ],
116
+ "type": "object",
117
+ "additionalProperties": false,
118
+ "propertyNames": {
119
+ "anyOf": [{"type": "string", "format": "python-module-name"}, {"const": "*"}]
120
+ },
121
+ "patternProperties": {
122
+ "^.*$": {"type": "array", "items": {"type": "string"}}
123
+ }
124
+ },
125
+ "include-package-data": {
126
+ "$$description": [
127
+ "Automatically include any data files inside the package directories",
128
+ "that are specified by ``MANIFEST.in``",
129
+ "For more information on how to include data files, check ``setuptools`` `docs",
130
+ "<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_."
131
+ ],
132
+ "type": "boolean"
133
+ },
134
+ "exclude-package-data": {
135
+ "$$description": [
136
+ "Mapping from package names to lists of glob patterns that should be excluded",
137
+ "For more information on how to include data files, check ``setuptools`` `docs",
138
+ "<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_."
139
+ ],
140
+ "type": "object",
141
+ "additionalProperties": false,
142
+ "propertyNames": {
143
+ "anyOf": [{"type": "string", "format": "python-module-name"}, {"const": "*"}]
144
+ },
145
+ "patternProperties": {
146
+ "^.*$": {"type": "array", "items": {"type": "string"}}
147
+ }
148
+ },
149
+ "namespace-packages": {
150
+ "type": "array",
151
+ "items": {"type": "string", "format": "python-module-name-relaxed"},
152
+ "$comment": "https://setuptools.pypa.io/en/latest/userguide/package_discovery.html",
153
+ "description": "**DEPRECATED**: use implicit namespaces instead (:pep:`420`)."
154
+ },
155
+ "py-modules": {
156
+ "description": "Modules that setuptools will manipulate",
157
+ "type": "array",
158
+ "items": {"type": "string", "format": "python-module-name-relaxed"},
159
+ "$comment": "TODO: clarify the relationship with ``packages``"
160
+ },
161
+ "ext-modules": {
162
+ "description": "Extension modules to be compiled by setuptools",
163
+ "type": "array",
164
+ "items": {"$ref": "#/definitions/ext-module"}
165
+ },
166
+ "data-files": {
167
+ "$$description": [
168
+ "``dict``-like structure where each key represents a directory and",
169
+ "the value is a list of glob patterns that should be installed in them.",
170
+ "**DISCOURAGED**: please notice this might not work as expected with wheels.",
171
+ "Whenever possible, consider using data files inside the package directories",
172
+ "(or create a new namespace package that only contains data files).",
173
+ "See `data files support",
174
+ "<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_."
175
+ ],
176
+ "type": "object",
177
+ "patternProperties": {
178
+ "^.*$": {"type": "array", "items": {"type": "string"}}
179
+ }
180
+ },
181
+ "cmdclass": {
182
+ "$$description": [
183
+ "Mapping of distutils-style command names to ``setuptools.Command`` subclasses",
184
+ "which in turn should be represented by strings with a qualified class name",
185
+ "(i.e., \"dotted\" form with module), e.g.::\n\n",
186
+ " cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\n\n",
187
+ "The command class should be a directly defined at the top-level of the",
188
+ "containing module (no class nesting)."
189
+ ],
190
+ "type": "object",
191
+ "patternProperties": {
192
+ "^.*$": {"type": "string", "format": "python-qualified-identifier"}
193
+ }
194
+ },
195
+ "license-files": {
196
+ "type": "array",
197
+ "items": {"type": "string"},
198
+ "$$description": [
199
+ "**PROVISIONAL**: list of glob patterns for all license files being distributed.",
200
+ "(likely to become standard with :pep:`639`).",
201
+ "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"
202
+ ],
203
+ "$comment": "TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?"
204
+ },
205
+ "dynamic": {
206
+ "type": "object",
207
+ "description": "Instructions for loading :pep:`621`-related metadata dynamically",
208
+ "additionalProperties": false,
209
+ "properties": {
210
+ "version": {
211
+ "$$description": [
212
+ "A version dynamically loaded via either the ``attr:`` or ``file:``",
213
+ "directives. Please make sure the given file or attribute respects :pep:`440`.",
214
+ "Also ensure to set ``project.dynamic`` accordingly."
215
+ ],
216
+ "oneOf": [
217
+ {"$ref": "#/definitions/attr-directive"},
218
+ {"$ref": "#/definitions/file-directive"}
219
+ ]
220
+ },
221
+ "classifiers": {"$ref": "#/definitions/file-directive"},
222
+ "description": {"$ref": "#/definitions/file-directive"},
223
+ "entry-points": {"$ref": "#/definitions/file-directive"},
224
+ "dependencies": {"$ref": "#/definitions/file-directive-for-dependencies"},
225
+ "optional-dependencies": {
226
+ "type": "object",
227
+ "propertyNames": {"type": "string", "format": "pep508-identifier"},
228
+ "additionalProperties": false,
229
+ "patternProperties": {
230
+ ".+": {"$ref": "#/definitions/file-directive-for-dependencies"}
231
+ }
232
+ },
233
+ "readme": {
234
+ "type": "object",
235
+ "anyOf": [
236
+ {"$ref": "#/definitions/file-directive"},
237
+ {
238
+ "type": "object",
239
+ "properties": {
240
+ "content-type": {"type": "string"},
241
+ "file": { "$ref": "#/definitions/file-directive/properties/file" }
242
+ },
243
+ "additionalProperties": false}
244
+ ],
245
+ "required": ["file"]
246
+ }
247
+ }
248
+ }
249
+ },
250
+
251
+ "definitions": {
252
+ "package-name": {
253
+ "$id": "#/definitions/package-name",
254
+ "title": "Valid package name",
255
+ "description": "Valid package name (importable or :pep:`561`).",
256
+ "type": "string",
257
+ "anyOf": [
258
+ {"type": "string", "format": "python-module-name-relaxed"},
259
+ {"type": "string", "format": "pep561-stub-name"}
260
+ ]
261
+ },
262
+ "ext-module": {
263
+ "$id": "#/definitions/ext-module",
264
+ "title": "Extension module",
265
+ "description": "Parameters to construct a :class:`setuptools.Extension` object",
266
+ "type": "object",
267
+ "required": ["name", "sources"],
268
+ "additionalProperties": false,
269
+ "properties": {
270
+ "name": {
271
+ "type": "string",
272
+ "format": "python-module-name-relaxed"
273
+ },
274
+ "sources": {
275
+ "type": "array",
276
+ "items": {"type": "string"}
277
+ },
278
+ "include-dirs":{
279
+ "type": "array",
280
+ "items": {"type": "string"}
281
+ },
282
+ "define-macros": {
283
+ "type": "array",
284
+ "items": {
285
+ "type": "array",
286
+ "items": [
287
+ {"description": "macro name", "type": "string"},
288
+ {"description": "macro value", "oneOf": [{"type": "string"}, {"type": "null"}]}
289
+ ],
290
+ "additionalItems": false
291
+ }
292
+ },
293
+ "undef-macros": {
294
+ "type": "array",
295
+ "items": {"type": "string"}
296
+ },
297
+ "library-dirs": {
298
+ "type": "array",
299
+ "items": {"type": "string"}
300
+ },
301
+ "libraries": {
302
+ "type": "array",
303
+ "items": {"type": "string"}
304
+ },
305
+ "runtime-library-dirs": {
306
+ "type": "array",
307
+ "items": {"type": "string"}
308
+ },
309
+ "extra-objects": {
310
+ "type": "array",
311
+ "items": {"type": "string"}
312
+ },
313
+ "extra-compile-args": {
314
+ "type": "array",
315
+ "items": {"type": "string"}
316
+ },
317
+ "extra-link-args": {
318
+ "type": "array",
319
+ "items": {"type": "string"}
320
+ },
321
+ "export-symbols": {
322
+ "type": "array",
323
+ "items": {"type": "string"}
324
+ },
325
+ "swig-opts": {
326
+ "type": "array",
327
+ "items": {"type": "string"}
328
+ },
329
+ "depends": {
330
+ "type": "array",
331
+ "items": {"type": "string"}
332
+ },
333
+ "language": {"type": "string"},
334
+ "optional": {"type": "boolean"},
335
+ "py-limited-api": {"type": "boolean"}
336
+ }
337
+ },
338
+ "file-directive": {
339
+ "$id": "#/definitions/file-directive",
340
+ "title": "'file:' directive",
341
+ "description":
342
+ "Value is read from a file (or list of files and then concatenated)",
343
+ "type": "object",
344
+ "additionalProperties": false,
345
+ "properties": {
346
+ "file": {
347
+ "oneOf": [
348
+ {"type": "string"},
349
+ {"type": "array", "items": {"type": "string"}}
350
+ ]
351
+ }
352
+ },
353
+ "required": ["file"]
354
+ },
355
+ "file-directive-for-dependencies": {
356
+ "title": "'file:' directive for dependencies",
357
+ "allOf": [
358
+ {
359
+ "$$description": [
360
+ "**BETA**: subset of the ``requirements.txt`` format",
361
+ "without ``pip`` flags and options",
362
+ "(one :pep:`508`-compliant string per line,",
363
+ "lines that are blank or start with ``#`` are excluded).",
364
+ "See `dynamic metadata",
365
+ "<https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html#dynamic-metadata>`_."
366
+ ]
367
+ },
368
+ {"$ref": "#/definitions/file-directive"}
369
+ ]
370
+ },
371
+ "attr-directive": {
372
+ "title": "'attr:' directive",
373
+ "$id": "#/definitions/attr-directive",
374
+ "$$description": [
375
+ "Value is read from a module attribute. Supports callables and iterables;",
376
+ "unsupported types are cast via ``str()``"
377
+ ],
378
+ "type": "object",
379
+ "additionalProperties": false,
380
+ "properties": {
381
+ "attr": {"type": "string", "format": "python-qualified-identifier"}
382
+ },
383
+ "required": ["attr"]
384
+ },
385
+ "find-directive": {
386
+ "$id": "#/definitions/find-directive",
387
+ "title": "'find:' directive",
388
+ "type": "object",
389
+ "additionalProperties": false,
390
+ "properties": {
391
+ "find": {
392
+ "type": "object",
393
+ "$$description": [
394
+ "Dynamic `package discovery",
395
+ "<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_."
396
+ ],
397
+ "additionalProperties": false,
398
+ "properties": {
399
+ "where": {
400
+ "description":
401
+ "Directories to be searched for packages (Unix-style relative path)",
402
+ "type": "array",
403
+ "items": {"type": "string"}
404
+ },
405
+ "exclude": {
406
+ "type": "array",
407
+ "$$description": [
408
+ "Exclude packages that match the values listed in this field.",
409
+ "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
410
+ ],
411
+ "items": {"type": "string"}
412
+ },
413
+ "include": {
414
+ "type": "array",
415
+ "$$description": [
416
+ "Restrict the found packages to just the ones listed in this field.",
417
+ "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
418
+ ],
419
+ "items": {"type": "string"}
420
+ },
421
+ "namespaces": {
422
+ "type": "boolean",
423
+ "$$description": [
424
+ "When ``True``, directories without a ``__init__.py`` file will also",
425
+ "be scanned for :pep:`420`-style implicit namespaces"
426
+ ]
427
+ }
428
+ }
429
+ }
430
+ }
431
+ }
432
+ }
433
+ }
python_embeded/Lib/site-packages/setuptools/tests/contexts.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import io
3
+ import os
4
+ import shutil
5
+ import site
6
+ import sys
7
+ import tempfile
8
+
9
+ from filelock import FileLock
10
+
11
+
12
+ @contextlib.contextmanager
13
+ def tempdir(cd=lambda dir: None, **kwargs):
14
+ temp_dir = tempfile.mkdtemp(**kwargs)
15
+ orig_dir = os.getcwd()
16
+ try:
17
+ cd(temp_dir)
18
+ yield temp_dir
19
+ finally:
20
+ cd(orig_dir)
21
+ shutil.rmtree(temp_dir)
22
+
23
+
24
+ @contextlib.contextmanager
25
+ def environment(**replacements):
26
+ """
27
+ In a context, patch the environment with replacements. Pass None values
28
+ to clear the values.
29
+ """
30
+ saved = dict((key, os.environ[key]) for key in replacements if key in os.environ)
31
+
32
+ # remove values that are null
33
+ remove = (key for (key, value) in replacements.items() if value is None)
34
+ for key in list(remove):
35
+ os.environ.pop(key, None)
36
+ replacements.pop(key)
37
+
38
+ os.environ.update(replacements)
39
+
40
+ try:
41
+ yield saved
42
+ finally:
43
+ for key in replacements:
44
+ os.environ.pop(key, None)
45
+ os.environ.update(saved)
46
+
47
+
48
+ @contextlib.contextmanager
49
+ def quiet():
50
+ """
51
+ Redirect stdout/stderr to StringIO objects to prevent console output from
52
+ distutils commands.
53
+ """
54
+
55
+ old_stdout = sys.stdout
56
+ old_stderr = sys.stderr
57
+ new_stdout = sys.stdout = io.StringIO()
58
+ new_stderr = sys.stderr = io.StringIO()
59
+ try:
60
+ yield new_stdout, new_stderr
61
+ finally:
62
+ new_stdout.seek(0)
63
+ new_stderr.seek(0)
64
+ sys.stdout = old_stdout
65
+ sys.stderr = old_stderr
66
+
67
+
68
+ @contextlib.contextmanager
69
+ def save_user_site_setting():
70
+ saved = site.ENABLE_USER_SITE
71
+ try:
72
+ yield saved
73
+ finally:
74
+ site.ENABLE_USER_SITE = saved
75
+
76
+
77
+ @contextlib.contextmanager
78
+ def suppress_exceptions(*excs):
79
+ try:
80
+ yield
81
+ except excs:
82
+ pass
83
+
84
+
85
+ def multiproc(request):
86
+ """
87
+ Return True if running under xdist and multiple
88
+ workers are used.
89
+ """
90
+ try:
91
+ worker_id = request.getfixturevalue('worker_id')
92
+ except Exception:
93
+ return False
94
+ return worker_id != 'master'
95
+
96
+
97
+ @contextlib.contextmanager
98
+ def session_locked_tmp_dir(request, tmp_path_factory, name):
99
+ """Uses a file lock to guarantee only one worker can access a temp dir"""
100
+ # get the temp directory shared by all workers
101
+ base = tmp_path_factory.getbasetemp()
102
+ shared_dir = base.parent if multiproc(request) else base
103
+
104
+ locked_dir = shared_dir / name
105
+ with FileLock(locked_dir.with_suffix(".lock")):
106
+ # ^-- prevent multiple workers to access the directory at once
107
+ locked_dir.mkdir(exist_ok=True, parents=True)
108
+ yield locked_dir
109
+
110
+
111
+ @contextlib.contextmanager
112
+ def save_paths():
113
+ """Make sure ``sys.path``, ``sys.meta_path`` and ``sys.path_hooks`` are preserved"""
114
+ prev = sys.path[:], sys.meta_path[:], sys.path_hooks[:]
115
+
116
+ try:
117
+ yield
118
+ finally:
119
+ sys.path, sys.meta_path, sys.path_hooks = prev
120
+
121
+
122
+ @contextlib.contextmanager
123
+ def save_sys_modules():
124
+ """Make sure initial ``sys.modules`` is preserved"""
125
+ prev_modules = sys.modules
126
+
127
+ try:
128
+ sys.modules = sys.modules.copy()
129
+ yield
130
+ finally:
131
+ sys.modules = prev_modules
python_embeded/Lib/site-packages/setuptools/tests/environment.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import sys
4
+ import unicodedata
5
+ from subprocess import PIPE as _PIPE, Popen as _Popen
6
+
7
+ import jaraco.envs
8
+
9
+
10
+ class VirtualEnv(jaraco.envs.VirtualEnv):
11
+ name = '.env'
12
+ # Some version of PyPy will import distutils on startup, implicitly
13
+ # importing setuptools, and thus leading to BackendInvalid errors
14
+ # when upgrading Setuptools. Bypass this behavior by avoiding the
15
+ # early availability and need to upgrade.
16
+ create_opts = ['--no-setuptools']
17
+
18
+ def run(self, cmd, *args, **kwargs):
19
+ cmd = [self.exe(cmd[0])] + cmd[1:]
20
+ kwargs = {"cwd": self.root, "encoding": "utf-8", **kwargs} # Allow overriding
21
+ # In some environments (eg. downstream distro packaging), where:
22
+ # - tox isn't used to run tests and
23
+ # - PYTHONPATH is set to point to a specific setuptools codebase and
24
+ # - no custom env is explicitly set by a test
25
+ # PYTHONPATH will leak into the spawned processes.
26
+ # In that case tests look for module in the wrong place (on PYTHONPATH).
27
+ # Unless the test sets its own special env, pass a copy of the existing
28
+ # environment with removed PYTHONPATH to the subprocesses.
29
+ if "env" not in kwargs:
30
+ env = dict(os.environ)
31
+ if "PYTHONPATH" in env:
32
+ del env["PYTHONPATH"]
33
+ kwargs["env"] = env
34
+ return subprocess.check_output(cmd, *args, **kwargs)
35
+
36
+
37
+ def _which_dirs(cmd):
38
+ result = set()
39
+ for path in os.environ.get('PATH', '').split(os.pathsep):
40
+ filename = os.path.join(path, cmd)
41
+ if os.access(filename, os.X_OK):
42
+ result.add(path)
43
+ return result
44
+
45
+
46
+ def run_setup_py(cmd, pypath=None, path=None, data_stream=0, env=None):
47
+ """
48
+ Execution command for tests, separate from those used by the
49
+ code directly to prevent accidental behavior issues
50
+ """
51
+ if env is None:
52
+ env = dict()
53
+ for envname in os.environ:
54
+ env[envname] = os.environ[envname]
55
+
56
+ # override the python path if needed
57
+ if pypath is not None:
58
+ env["PYTHONPATH"] = pypath
59
+
60
+ # override the execution path if needed
61
+ if path is not None:
62
+ env["PATH"] = path
63
+ if not env.get("PATH", ""):
64
+ env["PATH"] = _which_dirs("tar").union(_which_dirs("gzip"))
65
+ env["PATH"] = os.pathsep.join(env["PATH"])
66
+
67
+ cmd = [sys.executable, "setup.py"] + list(cmd)
68
+
69
+ # https://bugs.python.org/issue8557
70
+ shell = sys.platform == 'win32'
71
+
72
+ try:
73
+ proc = _Popen(
74
+ cmd,
75
+ stdout=_PIPE,
76
+ stderr=_PIPE,
77
+ shell=shell,
78
+ env=env,
79
+ encoding="utf-8",
80
+ )
81
+
82
+ if isinstance(data_stream, tuple):
83
+ data_stream = slice(*data_stream)
84
+ data = proc.communicate()[data_stream]
85
+ except OSError:
86
+ return 1, ''
87
+
88
+ # decode the console string if needed
89
+ if hasattr(data, "decode"):
90
+ # use the default encoding
91
+ data = data.decode()
92
+ data = unicodedata.normalize('NFC', data)
93
+
94
+ # communicate calls wait()
95
+ return proc.returncode, data
python_embeded/Lib/site-packages/setuptools/tests/fixtures.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import io
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ import tarfile
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import jaraco.path
11
+ import path
12
+ import pytest
13
+
14
+ from setuptools._normalization import safer_name
15
+
16
+ from . import contexts, environment
17
+ from .textwrap import DALS
18
+
19
+
20
+ @pytest.fixture
21
+ def user_override(monkeypatch):
22
+ """
23
+ Override site.USER_BASE and site.USER_SITE with temporary directories in
24
+ a context.
25
+ """
26
+ with contexts.tempdir() as user_base:
27
+ monkeypatch.setattr('site.USER_BASE', user_base)
28
+ with contexts.tempdir() as user_site:
29
+ monkeypatch.setattr('site.USER_SITE', user_site)
30
+ with contexts.save_user_site_setting():
31
+ yield
32
+
33
+
34
+ @pytest.fixture
35
+ def tmpdir_cwd(tmpdir):
36
+ with tmpdir.as_cwd() as orig:
37
+ yield orig
38
+
39
+
40
+ @pytest.fixture(autouse=True, scope="session")
41
+ def workaround_xdist_376(request):
42
+ """
43
+ Workaround pytest-dev/pytest-xdist#376
44
+
45
+ ``pytest-xdist`` tends to inject '' into ``sys.path``,
46
+ which may break certain isolation expectations.
47
+ Remove the entry so the import
48
+ machinery behaves the same irrespective of xdist.
49
+ """
50
+ if not request.config.pluginmanager.has_plugin('xdist'):
51
+ return
52
+
53
+ with contextlib.suppress(ValueError):
54
+ sys.path.remove('')
55
+
56
+
57
+ @pytest.fixture
58
+ def sample_project(tmp_path):
59
+ """
60
+ Clone the 'sampleproject' and return a path to it.
61
+ """
62
+ cmd = ['git', 'clone', 'https://github.com/pypa/sampleproject']
63
+ try:
64
+ subprocess.check_call(cmd, cwd=str(tmp_path))
65
+ except Exception:
66
+ pytest.skip("Unable to clone sampleproject")
67
+ return tmp_path / 'sampleproject'
68
+
69
+
70
+ @pytest.fixture
71
+ def sample_project_cwd(sample_project):
72
+ with path.Path(sample_project):
73
+ yield
74
+
75
+
76
+ # sdist and wheel artifacts should be stable across a round of tests
77
+ # so we can build them once per session and use the files as "readonly"
78
+
79
+ # In the case of setuptools, building the wheel without sdist may cause
80
+ # it to contain the `build` directory, and therefore create situations with
81
+ # `setuptools/build/lib/build/lib/...`. To avoid that, build both artifacts at once.
82
+
83
+
84
+ def _build_distributions(tmp_path_factory, request):
85
+ with contexts.session_locked_tmp_dir(
86
+ request, tmp_path_factory, "dist_build"
87
+ ) as tmp: # pragma: no cover
88
+ sdist = next(tmp.glob("*.tar.gz"), None)
89
+ wheel = next(tmp.glob("*.whl"), None)
90
+ if sdist and wheel:
91
+ return (sdist, wheel)
92
+
93
+ # Sanity check: should not create recursive setuptools/build/lib/build/lib/...
94
+ assert not Path(request.config.rootdir, "build/lib/build").exists()
95
+
96
+ subprocess.check_output([
97
+ sys.executable,
98
+ "-m",
99
+ "build",
100
+ "--outdir",
101
+ str(tmp),
102
+ str(request.config.rootdir),
103
+ ])
104
+
105
+ # Sanity check: should not create recursive setuptools/build/lib/build/lib/...
106
+ assert not Path(request.config.rootdir, "build/lib/build").exists()
107
+
108
+ return next(tmp.glob("*.tar.gz")), next(tmp.glob("*.whl"))
109
+
110
+
111
+ @pytest.fixture(scope="session")
112
+ def setuptools_sdist(tmp_path_factory, request):
113
+ prebuilt = os.getenv("PRE_BUILT_SETUPTOOLS_SDIST")
114
+ if prebuilt and os.path.exists(prebuilt): # pragma: no cover
115
+ return Path(prebuilt).resolve()
116
+
117
+ sdist, _ = _build_distributions(tmp_path_factory, request)
118
+ return sdist
119
+
120
+
121
+ @pytest.fixture(scope="session")
122
+ def setuptools_wheel(tmp_path_factory, request):
123
+ prebuilt = os.getenv("PRE_BUILT_SETUPTOOLS_WHEEL")
124
+ if prebuilt and os.path.exists(prebuilt): # pragma: no cover
125
+ return Path(prebuilt).resolve()
126
+
127
+ _, wheel = _build_distributions(tmp_path_factory, request)
128
+ return wheel
129
+
130
+
131
+ @pytest.fixture
132
+ def venv(tmp_path, setuptools_wheel):
133
+ """Virtual env with the version of setuptools under test installed"""
134
+ env = environment.VirtualEnv()
135
+ env.root = path.Path(tmp_path / 'venv')
136
+ env.create_opts = ['--no-setuptools', '--wheel=bundle']
137
+ # TODO: Use `--no-wheel` when setuptools implements its own bdist_wheel
138
+ env.req = str(setuptools_wheel)
139
+ # In some environments (eg. downstream distro packaging),
140
+ # where tox isn't used to run tests and PYTHONPATH is set to point to
141
+ # a specific setuptools codebase, PYTHONPATH will leak into the spawned
142
+ # processes.
143
+ # env.create() should install the just created setuptools
144
+ # wheel, but it doesn't if it finds another existing matching setuptools
145
+ # installation present on PYTHONPATH:
146
+ # `setuptools is already installed with the same version as the provided
147
+ # wheel. Use --force-reinstall to force an installation of the wheel.`
148
+ # This prevents leaking PYTHONPATH to the created environment.
149
+ with contexts.environment(PYTHONPATH=None):
150
+ return env.create()
151
+
152
+
153
+ @pytest.fixture
154
+ def venv_without_setuptools(tmp_path):
155
+ """Virtual env without any version of setuptools installed"""
156
+ env = environment.VirtualEnv()
157
+ env.root = path.Path(tmp_path / 'venv_without_setuptools')
158
+ env.create_opts = ['--no-setuptools', '--no-wheel']
159
+ env.ensure_env()
160
+ return env
161
+
162
+
163
+ @pytest.fixture
164
+ def bare_venv(tmp_path):
165
+ """Virtual env without any common packages installed"""
166
+ env = environment.VirtualEnv()
167
+ env.root = path.Path(tmp_path / 'bare_venv')
168
+ env.create_opts = ['--no-setuptools', '--no-pip', '--no-wheel', '--no-seed']
169
+ env.ensure_env()
170
+ return env
171
+
172
+
173
+ def make_sdist(dist_path, files):
174
+ """
175
+ Create a simple sdist tarball at dist_path, containing the files
176
+ listed in ``files`` as ``(filename, content)`` tuples.
177
+ """
178
+
179
+ # Distributions with only one file don't play well with pip.
180
+ assert len(files) > 1
181
+ with tarfile.open(dist_path, 'w:gz') as dist:
182
+ for filename, content in files:
183
+ file_bytes = io.BytesIO(content.encode('utf-8'))
184
+ file_info = tarfile.TarInfo(name=filename)
185
+ file_info.size = len(file_bytes.getvalue())
186
+ file_info.mtime = int(time.time())
187
+ dist.addfile(file_info, fileobj=file_bytes)
188
+
189
+
190
+ def make_trivial_sdist(dist_path, distname, version):
191
+ """
192
+ Create a simple sdist tarball at dist_path, containing just a simple
193
+ setup.py.
194
+ """
195
+
196
+ make_sdist(
197
+ dist_path,
198
+ [
199
+ (
200
+ 'setup.py',
201
+ DALS(
202
+ f"""\
203
+ import setuptools
204
+ setuptools.setup(
205
+ name={distname!r},
206
+ version={version!r}
207
+ )
208
+ """
209
+ ),
210
+ ),
211
+ ('setup.cfg', ''),
212
+ ],
213
+ )
214
+
215
+
216
+ def make_nspkg_sdist(dist_path, distname, version):
217
+ """
218
+ Make an sdist tarball with distname and version which also contains one
219
+ package with the same name as distname. The top-level package is
220
+ designated a namespace package).
221
+ """
222
+ # Assert that the distname contains at least one period
223
+ assert '.' in distname
224
+
225
+ parts = distname.split('.')
226
+ nspackage = parts[0]
227
+
228
+ packages = ['.'.join(parts[:idx]) for idx in range(1, len(parts) + 1)]
229
+
230
+ setup_py = DALS(
231
+ f"""\
232
+ import setuptools
233
+ setuptools.setup(
234
+ name={distname!r},
235
+ version={version!r},
236
+ packages={packages!r},
237
+ namespace_packages=[{nspackage!r}]
238
+ )
239
+ """
240
+ )
241
+
242
+ init = "__import__('pkg_resources').declare_namespace(__name__)"
243
+
244
+ files = [('setup.py', setup_py), (os.path.join(nspackage, '__init__.py'), init)]
245
+ for package in packages[1:]:
246
+ filename = os.path.join(*(package.split('.') + ['__init__.py']))
247
+ files.append((filename, ''))
248
+
249
+ make_sdist(dist_path, files)
250
+
251
+
252
+ def make_python_requires_sdist(dist_path, distname, version, python_requires):
253
+ make_sdist(
254
+ dist_path,
255
+ [
256
+ (
257
+ 'setup.py',
258
+ DALS(
259
+ """\
260
+ import setuptools
261
+ setuptools.setup(
262
+ name={name!r},
263
+ version={version!r},
264
+ python_requires={python_requires!r},
265
+ )
266
+ """
267
+ ).format(
268
+ name=distname, version=version, python_requires=python_requires
269
+ ),
270
+ ),
271
+ ('setup.cfg', ''),
272
+ ],
273
+ )
274
+
275
+
276
+ def create_setup_requires_package(
277
+ path,
278
+ distname='foobar',
279
+ version='0.1',
280
+ make_package=make_trivial_sdist,
281
+ setup_py_template=None,
282
+ setup_attrs=None,
283
+ use_setup_cfg=(),
284
+ ):
285
+ """Creates a source tree under path for a trivial test package that has a
286
+ single requirement in setup_requires--a tarball for that requirement is
287
+ also created and added to the dependency_links argument.
288
+
289
+ ``distname`` and ``version`` refer to the name/version of the package that
290
+ the test package requires via ``setup_requires``. The name of the test
291
+ package itself is just 'test_pkg'.
292
+ """
293
+
294
+ normalized_distname = safer_name(distname)
295
+ test_setup_attrs = {
296
+ 'name': 'test_pkg',
297
+ 'version': '0.0',
298
+ 'setup_requires': [f'{normalized_distname}=={version}'],
299
+ 'dependency_links': [os.path.abspath(path)],
300
+ }
301
+ if setup_attrs:
302
+ test_setup_attrs.update(setup_attrs)
303
+
304
+ test_pkg = os.path.join(path, 'test_pkg')
305
+ os.mkdir(test_pkg)
306
+
307
+ # setup.cfg
308
+ if use_setup_cfg:
309
+ options = []
310
+ metadata = []
311
+ for name in use_setup_cfg:
312
+ value = test_setup_attrs.pop(name)
313
+ if name in 'name version'.split():
314
+ section = metadata
315
+ else:
316
+ section = options
317
+ if isinstance(value, (tuple, list)):
318
+ value = ';'.join(value)
319
+ section.append(f'{name}: {value}')
320
+ test_setup_cfg_contents = DALS(
321
+ """
322
+ [metadata]
323
+ {metadata}
324
+ [options]
325
+ {options}
326
+ """
327
+ ).format(
328
+ options='\n'.join(options),
329
+ metadata='\n'.join(metadata),
330
+ )
331
+ else:
332
+ test_setup_cfg_contents = ''
333
+ with open(os.path.join(test_pkg, 'setup.cfg'), 'w', encoding="utf-8") as f:
334
+ f.write(test_setup_cfg_contents)
335
+
336
+ # setup.py
337
+ if setup_py_template is None:
338
+ setup_py_template = DALS(
339
+ """\
340
+ import setuptools
341
+ setuptools.setup(**%r)
342
+ """
343
+ )
344
+ with open(os.path.join(test_pkg, 'setup.py'), 'w', encoding="utf-8") as f:
345
+ f.write(setup_py_template % test_setup_attrs)
346
+
347
+ foobar_path = os.path.join(path, f'{normalized_distname}-{version}.tar.gz')
348
+ make_package(foobar_path, distname, version)
349
+
350
+ return test_pkg
351
+
352
+
353
+ @pytest.fixture
354
+ def pbr_package(tmp_path, monkeypatch, venv):
355
+ files = {
356
+ "pyproject.toml": DALS(
357
+ """
358
+ [build-system]
359
+ requires = ["setuptools"]
360
+ build-backend = "setuptools.build_meta"
361
+ """
362
+ ),
363
+ "setup.py": DALS(
364
+ """
365
+ __import__('setuptools').setup(
366
+ pbr=True,
367
+ setup_requires=["pbr"],
368
+ )
369
+ """
370
+ ),
371
+ "setup.cfg": DALS(
372
+ """
373
+ [metadata]
374
+ name = mypkg
375
+
376
+ [files]
377
+ packages =
378
+ mypkg
379
+ """
380
+ ),
381
+ "mypkg": {
382
+ "__init__.py": "",
383
+ "hello.py": "print('Hello world!')",
384
+ },
385
+ "other": {"test.txt": "Another file in here."},
386
+ }
387
+ venv.run(["python", "-m", "pip", "install", "pbr"])
388
+ prefix = tmp_path / 'mypkg'
389
+ prefix.mkdir()
390
+ jaraco.path.build(files, prefix=prefix)
391
+ monkeypatch.setenv('PBR_VERSION', "0.42")
392
+ return prefix
python_embeded/Lib/site-packages/setuptools/tests/mod_with_constant.py ADDED
@@ -0,0 +1 @@
 
 
1
+ value = 'three, sir!'
python_embeded/Lib/site-packages/setuptools/tests/namespaces.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import json
3
+ import textwrap
4
+ from pathlib import Path
5
+
6
+
7
+ def iter_namespace_pkgs(namespace):
8
+ parts = namespace.split(".")
9
+ for i in range(len(parts)):
10
+ yield ".".join(parts[: i + 1])
11
+
12
+
13
+ def build_namespace_package(tmpdir, name, version="1.0", impl="pkg_resources"):
14
+ src_dir = tmpdir / name
15
+ src_dir.mkdir()
16
+ setup_py = src_dir / 'setup.py'
17
+ namespace, _, rest = name.rpartition('.')
18
+ namespaces = list(iter_namespace_pkgs(namespace))
19
+ setup_args = {
20
+ "name": name,
21
+ "version": version,
22
+ "packages": namespaces,
23
+ }
24
+
25
+ if impl == "pkg_resources":
26
+ tmpl = '__import__("pkg_resources").declare_namespace(__name__)'
27
+ setup_args["namespace_packages"] = namespaces
28
+ elif impl == "pkgutil":
29
+ tmpl = '__path__ = __import__("pkgutil").extend_path(__path__, __name__)'
30
+ else:
31
+ raise ValueError(f"Cannot recognise {impl=} when creating namespaces")
32
+
33
+ args = json.dumps(setup_args, indent=4)
34
+ assert ast.literal_eval(args) # ensure it is valid Python
35
+
36
+ script = textwrap.dedent(
37
+ """\
38
+ import setuptools
39
+ args = {args}
40
+ setuptools.setup(**args)
41
+ """
42
+ ).format(args=args)
43
+ setup_py.write_text(script, encoding='utf-8')
44
+
45
+ ns_pkg_dir = Path(src_dir, namespace.replace(".", "/"))
46
+ ns_pkg_dir.mkdir(parents=True)
47
+
48
+ for ns in namespaces:
49
+ pkg_init = src_dir / ns.replace(".", "/") / '__init__.py'
50
+ pkg_init.write_text(tmpl, encoding='utf-8')
51
+
52
+ pkg_mod = ns_pkg_dir / (rest + '.py')
53
+ some_functionality = 'name = {rest!r}'.format(**locals())
54
+ pkg_mod.write_text(some_functionality, encoding='utf-8')
55
+ return src_dir
56
+
57
+
58
+ def build_pep420_namespace_package(tmpdir, name):
59
+ src_dir = tmpdir / name
60
+ src_dir.mkdir()
61
+ pyproject = src_dir / "pyproject.toml"
62
+ namespace, _, rest = name.rpartition(".")
63
+ script = f"""\
64
+ [build-system]
65
+ requires = ["setuptools"]
66
+ build-backend = "setuptools.build_meta"
67
+
68
+ [project]
69
+ name = "{name}"
70
+ version = "3.14159"
71
+ """
72
+ pyproject.write_text(textwrap.dedent(script), encoding='utf-8')
73
+ ns_pkg_dir = Path(src_dir, namespace.replace(".", "/"))
74
+ ns_pkg_dir.mkdir(parents=True)
75
+ pkg_mod = ns_pkg_dir / (rest + ".py")
76
+ some_functionality = f"name = {rest!r}"
77
+ pkg_mod.write_text(some_functionality, encoding='utf-8')
78
+ return src_dir
79
+
80
+
81
+ def make_site_dir(target):
82
+ """
83
+ Add a sitecustomize.py module in target to cause
84
+ target to be added to site dirs such that .pth files
85
+ are processed there.
86
+ """
87
+ sc = target / 'sitecustomize.py'
88
+ target_str = str(target)
89
+ tmpl = '__import__("site").addsitedir({target_str!r})'
90
+ sc.write_text(tmpl.format(**locals()), encoding='utf-8')
python_embeded/Lib/site-packages/setuptools/tests/script-with-bom.py ADDED
@@ -0,0 +1 @@
 
 
1
+ result = 'passed'
python_embeded/Lib/site-packages/setuptools/tests/test_archive_util.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import tarfile
3
+
4
+ import pytest
5
+
6
+ from setuptools import archive_util
7
+
8
+
9
+ @pytest.fixture
10
+ def tarfile_with_unicode(tmpdir):
11
+ """
12
+ Create a tarfile containing only a file whose name is
13
+ a zero byte file called testimäge.png.
14
+ """
15
+ tarobj = io.BytesIO()
16
+
17
+ with tarfile.open(fileobj=tarobj, mode="w:gz") as tgz:
18
+ data = b""
19
+
20
+ filename = "testimäge.png"
21
+
22
+ t = tarfile.TarInfo(filename)
23
+ t.size = len(data)
24
+
25
+ tgz.addfile(t, io.BytesIO(data))
26
+
27
+ target = tmpdir / 'unicode-pkg-1.0.tar.gz'
28
+ with open(str(target), mode='wb') as tf:
29
+ tf.write(tarobj.getvalue())
30
+ return str(target)
31
+
32
+
33
+ @pytest.mark.xfail(reason="#710 and #712")
34
+ def test_unicode_files(tarfile_with_unicode, tmpdir):
35
+ target = tmpdir / 'out'
36
+ archive_util.unpack_archive(tarfile_with_unicode, str(target))
python_embeded/Lib/site-packages/setuptools/tests/test_bdist_deprecations.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """develop tests"""
2
+
3
+ import sys
4
+ from unittest import mock
5
+
6
+ import pytest
7
+
8
+ from setuptools import SetuptoolsDeprecationWarning
9
+ from setuptools.dist import Distribution
10
+
11
+
12
+ @pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only')
13
+ @pytest.mark.xfail(reason="bdist_rpm is long deprecated, should we remove it? #1988")
14
+ @mock.patch('distutils.command.bdist_rpm.bdist_rpm')
15
+ def test_bdist_rpm_warning(distutils_cmd, tmpdir_cwd):
16
+ dist = Distribution(
17
+ dict(
18
+ script_name='setup.py',
19
+ script_args=['bdist_rpm'],
20
+ name='foo',
21
+ py_modules=['hi'],
22
+ )
23
+ )
24
+ dist.parse_command_line()
25
+ with pytest.warns(SetuptoolsDeprecationWarning):
26
+ dist.run_commands()
27
+
28
+ distutils_cmd.run.assert_called_once()
python_embeded/Lib/site-packages/setuptools/tests/test_bdist_egg.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """develop tests"""
2
+
3
+ import os
4
+ import re
5
+ import zipfile
6
+
7
+ import pytest
8
+
9
+ from setuptools.dist import Distribution
10
+
11
+ from . import contexts
12
+
13
+ SETUP_PY = """\
14
+ from setuptools import setup
15
+
16
+ setup(py_modules=['hi'])
17
+ """
18
+
19
+
20
+ @pytest.fixture
21
+ def setup_context(tmpdir):
22
+ with (tmpdir / 'setup.py').open('w') as f:
23
+ f.write(SETUP_PY)
24
+ with (tmpdir / 'hi.py').open('w') as f:
25
+ f.write('1\n')
26
+ with tmpdir.as_cwd():
27
+ yield tmpdir
28
+
29
+
30
+ class Test:
31
+ @pytest.mark.usefixtures("user_override")
32
+ @pytest.mark.usefixtures("setup_context")
33
+ def test_bdist_egg(self):
34
+ dist = Distribution(
35
+ dict(
36
+ script_name='setup.py',
37
+ script_args=['bdist_egg'],
38
+ name='foo',
39
+ py_modules=['hi'],
40
+ )
41
+ )
42
+ os.makedirs(os.path.join('build', 'src'))
43
+ with contexts.quiet():
44
+ dist.parse_command_line()
45
+ dist.run_commands()
46
+
47
+ # let's see if we got our egg link at the right place
48
+ [content] = os.listdir('dist')
49
+ assert re.match(r'foo-0.0.0-py[23].\d+.egg$', content)
50
+
51
+ @pytest.mark.xfail(
52
+ os.environ.get('PYTHONDONTWRITEBYTECODE', False),
53
+ reason="Byte code disabled",
54
+ )
55
+ @pytest.mark.usefixtures("user_override")
56
+ @pytest.mark.usefixtures("setup_context")
57
+ def test_exclude_source_files(self):
58
+ dist = Distribution(
59
+ dict(
60
+ script_name='setup.py',
61
+ script_args=['bdist_egg', '--exclude-source-files'],
62
+ py_modules=['hi'],
63
+ )
64
+ )
65
+ with contexts.quiet():
66
+ dist.parse_command_line()
67
+ dist.run_commands()
68
+ [dist_name] = os.listdir('dist')
69
+ dist_filename = os.path.join('dist', dist_name)
70
+ zip = zipfile.ZipFile(dist_filename)
71
+ names = list(zi.filename for zi in zip.filelist)
72
+ assert 'hi.pyc' in names
73
+ assert 'hi.py' not in names
python_embeded/Lib/site-packages/setuptools/tests/test_bdist_wheel.py ADDED
@@ -0,0 +1,708 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import builtins
4
+ import importlib
5
+ import os.path
6
+ import platform
7
+ import shutil
8
+ import stat
9
+ import struct
10
+ import sys
11
+ import sysconfig
12
+ from contextlib import suppress
13
+ from inspect import cleandoc
14
+ from zipfile import ZipFile
15
+
16
+ import jaraco.path
17
+ import pytest
18
+ from packaging import tags
19
+
20
+ import setuptools
21
+ from setuptools.command.bdist_wheel import bdist_wheel, get_abi_tag
22
+ from setuptools.dist import Distribution
23
+ from setuptools.warnings import SetuptoolsDeprecationWarning
24
+
25
+ from distutils.core import run_setup
26
+
27
+ DEFAULT_FILES = {
28
+ "dummy_dist-1.0.dist-info/top_level.txt",
29
+ "dummy_dist-1.0.dist-info/METADATA",
30
+ "dummy_dist-1.0.dist-info/WHEEL",
31
+ "dummy_dist-1.0.dist-info/RECORD",
32
+ }
33
+ DEFAULT_LICENSE_FILES = {
34
+ "LICENSE",
35
+ "LICENSE.txt",
36
+ "LICENCE",
37
+ "LICENCE.txt",
38
+ "COPYING",
39
+ "COPYING.md",
40
+ "NOTICE",
41
+ "NOTICE.rst",
42
+ "AUTHORS",
43
+ "AUTHORS.txt",
44
+ }
45
+ OTHER_IGNORED_FILES = {
46
+ "LICENSE~",
47
+ "AUTHORS~",
48
+ }
49
+ SETUPPY_EXAMPLE = """\
50
+ from setuptools import setup
51
+
52
+ setup(
53
+ name='dummy_dist',
54
+ version='1.0',
55
+ )
56
+ """
57
+
58
+
59
+ EXAMPLES = {
60
+ "dummy-dist": {
61
+ "setup.py": SETUPPY_EXAMPLE,
62
+ "licenses_dir": {"DUMMYFILE": ""},
63
+ **dict.fromkeys(DEFAULT_LICENSE_FILES | OTHER_IGNORED_FILES, ""),
64
+ },
65
+ "simple-dist": {
66
+ "setup.py": cleandoc(
67
+ """
68
+ from setuptools import setup
69
+
70
+ setup(
71
+ name="simple.dist",
72
+ version="0.1",
73
+ description="A testing distribution \N{SNOWMAN}",
74
+ extras_require={"voting": ["beaglevote"]},
75
+ )
76
+ """
77
+ ),
78
+ "simpledist": "",
79
+ },
80
+ "complex-dist": {
81
+ "setup.py": cleandoc(
82
+ """
83
+ from setuptools import setup
84
+
85
+ setup(
86
+ name="complex-dist",
87
+ version="0.1",
88
+ description="Another testing distribution \N{SNOWMAN}",
89
+ long_description="Another testing distribution \N{SNOWMAN}",
90
+ author="Illustrious Author",
91
+ author_email="illustrious@example.org",
92
+ url="http://example.org/exemplary",
93
+ packages=["complexdist"],
94
+ setup_requires=["setuptools"],
95
+ install_requires=["quux", "splort"],
96
+ extras_require={"simple": ["simple.dist"]},
97
+ entry_points={
98
+ "console_scripts": [
99
+ "complex-dist=complexdist:main",
100
+ "complex-dist2=complexdist:main",
101
+ ],
102
+ },
103
+ )
104
+ """
105
+ ),
106
+ "complexdist": {"__init__.py": "def main(): return"},
107
+ },
108
+ "headers-dist": {
109
+ "setup.py": cleandoc(
110
+ """
111
+ from setuptools import setup
112
+
113
+ setup(
114
+ name="headers.dist",
115
+ version="0.1",
116
+ description="A distribution with headers",
117
+ headers=["header.h"],
118
+ )
119
+ """
120
+ ),
121
+ "headersdist.py": "",
122
+ "header.h": "",
123
+ },
124
+ "commasinfilenames-dist": {
125
+ "setup.py": cleandoc(
126
+ """
127
+ from setuptools import setup
128
+
129
+ setup(
130
+ name="testrepo",
131
+ version="0.1",
132
+ packages=["mypackage"],
133
+ description="A test package with commas in file names",
134
+ include_package_data=True,
135
+ package_data={"mypackage.data": ["*"]},
136
+ )
137
+ """
138
+ ),
139
+ "mypackage": {
140
+ "__init__.py": "",
141
+ "data": {"__init__.py": "", "1,2,3.txt": ""},
142
+ },
143
+ "testrepo-0.1.0": {
144
+ "mypackage": {"__init__.py": ""},
145
+ },
146
+ },
147
+ "unicode-dist": {
148
+ "setup.py": cleandoc(
149
+ """
150
+ from setuptools import setup
151
+
152
+ setup(
153
+ name="unicode.dist",
154
+ version="0.1",
155
+ description="A testing distribution \N{SNOWMAN}",
156
+ packages=["unicodedist"],
157
+ zip_safe=True,
158
+ )
159
+ """
160
+ ),
161
+ "unicodedist": {"__init__.py": "", "åäö_日本語.py": ""},
162
+ },
163
+ "utf8-metadata-dist": {
164
+ "setup.cfg": cleandoc(
165
+ """
166
+ [metadata]
167
+ name = utf8-metadata-dist
168
+ version = 42
169
+ author_email = "John X. Ãørçeč" <john@utf8.org>, Γαμα קּ 東 <gama@utf8.org>
170
+ long_description = file: README.rst
171
+ """
172
+ ),
173
+ "README.rst": "UTF-8 描述 説明",
174
+ },
175
+ "licenses-dist": {
176
+ "setup.cfg": cleandoc(
177
+ """
178
+ [metadata]
179
+ name = licenses-dist
180
+ version = 1.0
181
+ license_files = **/LICENSE
182
+ """
183
+ ),
184
+ "LICENSE": "",
185
+ "src": {
186
+ "vendor": {"LICENSE": ""},
187
+ },
188
+ },
189
+ }
190
+
191
+
192
+ if sys.platform != "win32":
193
+ # ABI3 extensions don't really work on Windows
194
+ EXAMPLES["abi3extension-dist"] = {
195
+ "setup.py": cleandoc(
196
+ """
197
+ from setuptools import Extension, setup
198
+
199
+ setup(
200
+ name="extension.dist",
201
+ version="0.1",
202
+ description="A testing distribution \N{SNOWMAN}",
203
+ ext_modules=[
204
+ Extension(
205
+ name="extension", sources=["extension.c"], py_limited_api=True
206
+ )
207
+ ],
208
+ )
209
+ """
210
+ ),
211
+ "setup.cfg": "[bdist_wheel]\npy_limited_api=cp32",
212
+ "extension.c": "#define Py_LIMITED_API 0x03020000\n#include <Python.h>",
213
+ }
214
+
215
+
216
+ def bdist_wheel_cmd(**kwargs):
217
+ """Run command in the same process so that it is easier to collect coverage"""
218
+ dist_obj = (
219
+ run_setup("setup.py", stop_after="init")
220
+ if os.path.exists("setup.py")
221
+ else Distribution({"script_name": "%%build_meta%%"})
222
+ )
223
+ dist_obj.parse_config_files()
224
+ cmd = bdist_wheel(dist_obj)
225
+ for attr, value in kwargs.items():
226
+ setattr(cmd, attr, value)
227
+ cmd.finalize_options()
228
+ return cmd
229
+
230
+
231
+ def mkexample(tmp_path_factory, name):
232
+ basedir = tmp_path_factory.mktemp(name)
233
+ jaraco.path.build(EXAMPLES[name], prefix=str(basedir))
234
+ return basedir
235
+
236
+
237
+ @pytest.fixture(scope="session")
238
+ def wheel_paths(tmp_path_factory):
239
+ build_base = tmp_path_factory.mktemp("build")
240
+ dist_dir = tmp_path_factory.mktemp("dist")
241
+ for name in EXAMPLES:
242
+ example_dir = mkexample(tmp_path_factory, name)
243
+ build_dir = build_base / name
244
+ with jaraco.path.DirectoryStack().context(example_dir):
245
+ bdist_wheel_cmd(bdist_dir=str(build_dir), dist_dir=str(dist_dir)).run()
246
+
247
+ return sorted(str(fname) for fname in dist_dir.glob("*.whl"))
248
+
249
+
250
+ @pytest.fixture
251
+ def dummy_dist(tmp_path_factory):
252
+ return mkexample(tmp_path_factory, "dummy-dist")
253
+
254
+
255
+ @pytest.fixture
256
+ def licenses_dist(tmp_path_factory):
257
+ return mkexample(tmp_path_factory, "licenses-dist")
258
+
259
+
260
+ def test_no_scripts(wheel_paths):
261
+ """Make sure entry point scripts are not generated."""
262
+ path = next(path for path in wheel_paths if "complex_dist" in path)
263
+ for entry in ZipFile(path).infolist():
264
+ assert ".data/scripts/" not in entry.filename
265
+
266
+
267
+ def test_unicode_record(wheel_paths):
268
+ path = next(path for path in wheel_paths if "unicode_dist" in path)
269
+ with ZipFile(path) as zf:
270
+ record = zf.read("unicode_dist-0.1.dist-info/RECORD")
271
+
272
+ assert "åäö_日本語.py".encode() in record
273
+
274
+
275
+ UTF8_PKG_INFO = """\
276
+ Metadata-Version: 2.1
277
+ Name: helloworld
278
+ Version: 42
279
+ Author-email: "John X. Ãørçeč" <john@utf8.org>, Γαμα קּ 東 <gama@utf8.org>
280
+
281
+
282
+ UTF-8 描述 説明
283
+ """
284
+
285
+
286
+ def test_preserve_unicode_metadata(monkeypatch, tmp_path):
287
+ monkeypatch.chdir(tmp_path)
288
+ egginfo = tmp_path / "dummy_dist.egg-info"
289
+ distinfo = tmp_path / "dummy_dist.dist-info"
290
+
291
+ egginfo.mkdir()
292
+ (egginfo / "PKG-INFO").write_text(UTF8_PKG_INFO, encoding="utf-8")
293
+ (egginfo / "dependency_links.txt").touch()
294
+
295
+ class simpler_bdist_wheel(bdist_wheel):
296
+ """Avoid messing with setuptools/distutils internals"""
297
+
298
+ def __init__(self):
299
+ pass
300
+
301
+ @property
302
+ def license_paths(self):
303
+ return []
304
+
305
+ cmd_obj = simpler_bdist_wheel()
306
+ cmd_obj.egg2dist(egginfo, distinfo)
307
+
308
+ metadata = (distinfo / "METADATA").read_text(encoding="utf-8")
309
+ assert 'Author-email: "John X. Ãørçeč"' in metadata
310
+ assert "Γαμα קּ 東 " in metadata
311
+ assert "UTF-8 描述 説明" in metadata
312
+
313
+
314
+ def test_licenses_default(dummy_dist, monkeypatch, tmp_path):
315
+ monkeypatch.chdir(dummy_dist)
316
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
317
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
318
+ license_files = {
319
+ "dummy_dist-1.0.dist-info/licenses/" + fname
320
+ for fname in DEFAULT_LICENSE_FILES
321
+ }
322
+ assert set(wf.namelist()) == DEFAULT_FILES | license_files
323
+
324
+
325
+ def test_licenses_deprecated(dummy_dist, monkeypatch, tmp_path):
326
+ dummy_dist.joinpath("setup.cfg").write_text(
327
+ "[metadata]\nlicense_file=licenses_dir/DUMMYFILE", encoding="utf-8"
328
+ )
329
+ monkeypatch.chdir(dummy_dist)
330
+
331
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
332
+
333
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
334
+ license_files = {"dummy_dist-1.0.dist-info/licenses/licenses_dir/DUMMYFILE"}
335
+ assert set(wf.namelist()) == DEFAULT_FILES | license_files
336
+
337
+
338
+ @pytest.mark.parametrize(
339
+ ("config_file", "config"),
340
+ [
341
+ ("setup.cfg", "[metadata]\nlicense_files=licenses_dir/*\n LICENSE"),
342
+ ("setup.cfg", "[metadata]\nlicense_files=licenses_dir/*, LICENSE"),
343
+ (
344
+ "setup.py",
345
+ SETUPPY_EXAMPLE.replace(
346
+ ")", " license_files=['licenses_dir/DUMMYFILE', 'LICENSE'])"
347
+ ),
348
+ ),
349
+ ],
350
+ )
351
+ def test_licenses_override(dummy_dist, monkeypatch, tmp_path, config_file, config):
352
+ dummy_dist.joinpath(config_file).write_text(config, encoding="utf-8")
353
+ monkeypatch.chdir(dummy_dist)
354
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
355
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
356
+ license_files = {
357
+ "dummy_dist-1.0.dist-info/licenses/" + fname
358
+ for fname in {"licenses_dir/DUMMYFILE", "LICENSE"}
359
+ }
360
+ assert set(wf.namelist()) == DEFAULT_FILES | license_files
361
+ metadata = wf.read("dummy_dist-1.0.dist-info/METADATA").decode("utf8")
362
+ assert "License-File: licenses_dir/DUMMYFILE" in metadata
363
+ assert "License-File: LICENSE" in metadata
364
+
365
+
366
+ def test_licenses_preserve_folder_structure(licenses_dist, monkeypatch, tmp_path):
367
+ monkeypatch.chdir(licenses_dist)
368
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
369
+ print(os.listdir("dist"))
370
+ with ZipFile("dist/licenses_dist-1.0-py3-none-any.whl") as wf:
371
+ default_files = {name.replace("dummy_", "licenses_") for name in DEFAULT_FILES}
372
+ license_files = {
373
+ "licenses_dist-1.0.dist-info/licenses/LICENSE",
374
+ "licenses_dist-1.0.dist-info/licenses/src/vendor/LICENSE",
375
+ }
376
+ assert set(wf.namelist()) == default_files | license_files
377
+ metadata = wf.read("licenses_dist-1.0.dist-info/METADATA").decode("utf8")
378
+ assert "License-File: src/vendor/LICENSE" in metadata
379
+ assert "License-File: LICENSE" in metadata
380
+
381
+
382
+ def test_licenses_disabled(dummy_dist, monkeypatch, tmp_path):
383
+ dummy_dist.joinpath("setup.cfg").write_text(
384
+ "[metadata]\nlicense_files=\n", encoding="utf-8"
385
+ )
386
+ monkeypatch.chdir(dummy_dist)
387
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
388
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
389
+ assert set(wf.namelist()) == DEFAULT_FILES
390
+
391
+
392
+ def test_build_number(dummy_dist, monkeypatch, tmp_path):
393
+ monkeypatch.chdir(dummy_dist)
394
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), build_number="2").run()
395
+ with ZipFile("dist/dummy_dist-1.0-2-py3-none-any.whl") as wf:
396
+ filenames = set(wf.namelist())
397
+ assert "dummy_dist-1.0.dist-info/RECORD" in filenames
398
+ assert "dummy_dist-1.0.dist-info/METADATA" in filenames
399
+
400
+
401
+ def test_universal_deprecated(dummy_dist, monkeypatch, tmp_path):
402
+ monkeypatch.chdir(dummy_dist)
403
+ with pytest.warns(SetuptoolsDeprecationWarning, match=".*universal is deprecated"):
404
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), universal=True).run()
405
+
406
+ # For now we still respect the option
407
+ assert os.path.exists("dist/dummy_dist-1.0-py2.py3-none-any.whl")
408
+
409
+
410
+ EXTENSION_EXAMPLE = """\
411
+ #include <Python.h>
412
+
413
+ static PyMethodDef methods[] = {
414
+ { NULL, NULL, 0, NULL }
415
+ };
416
+
417
+ static struct PyModuleDef module_def = {
418
+ PyModuleDef_HEAD_INIT,
419
+ "extension",
420
+ "Dummy extension module",
421
+ -1,
422
+ methods
423
+ };
424
+
425
+ PyMODINIT_FUNC PyInit_extension(void) {
426
+ return PyModule_Create(&module_def);
427
+ }
428
+ """
429
+ EXTENSION_SETUPPY = """\
430
+ from __future__ import annotations
431
+
432
+ from setuptools import Extension, setup
433
+
434
+ setup(
435
+ name="extension.dist",
436
+ version="0.1",
437
+ description="A testing distribution \N{SNOWMAN}",
438
+ ext_modules=[Extension(name="extension", sources=["extension.c"])],
439
+ )
440
+ """
441
+
442
+
443
+ @pytest.mark.filterwarnings(
444
+ "once:Config variable '.*' is unset.*, Python ABI tag may be incorrect"
445
+ )
446
+ def test_limited_abi(monkeypatch, tmp_path, tmp_path_factory):
447
+ """Test that building a binary wheel with the limited ABI works."""
448
+ source_dir = tmp_path_factory.mktemp("extension_dist")
449
+ (source_dir / "setup.py").write_text(EXTENSION_SETUPPY, encoding="utf-8")
450
+ (source_dir / "extension.c").write_text(EXTENSION_EXAMPLE, encoding="utf-8")
451
+ build_dir = tmp_path.joinpath("build")
452
+ dist_dir = tmp_path.joinpath("dist")
453
+ monkeypatch.chdir(source_dir)
454
+ bdist_wheel_cmd(bdist_dir=str(build_dir), dist_dir=str(dist_dir)).run()
455
+
456
+
457
+ def test_build_from_readonly_tree(dummy_dist, monkeypatch, tmp_path):
458
+ basedir = str(tmp_path.joinpath("dummy"))
459
+ shutil.copytree(str(dummy_dist), basedir)
460
+ monkeypatch.chdir(basedir)
461
+
462
+ # Make the tree read-only
463
+ for root, _dirs, files in os.walk(basedir):
464
+ for fname in files:
465
+ os.chmod(os.path.join(root, fname), stat.S_IREAD)
466
+
467
+ bdist_wheel_cmd().run()
468
+
469
+
470
+ @pytest.mark.parametrize(
471
+ ("option", "compress_type"),
472
+ list(bdist_wheel.supported_compressions.items()),
473
+ ids=list(bdist_wheel.supported_compressions),
474
+ )
475
+ def test_compression(dummy_dist, monkeypatch, tmp_path, option, compress_type):
476
+ monkeypatch.chdir(dummy_dist)
477
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), compression=option).run()
478
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
479
+ filenames = set(wf.namelist())
480
+ assert "dummy_dist-1.0.dist-info/RECORD" in filenames
481
+ assert "dummy_dist-1.0.dist-info/METADATA" in filenames
482
+ for zinfo in wf.filelist:
483
+ assert zinfo.compress_type == compress_type
484
+
485
+
486
+ def test_wheelfile_line_endings(wheel_paths):
487
+ for path in wheel_paths:
488
+ with ZipFile(path) as wf:
489
+ wheelfile = next(fn for fn in wf.filelist if fn.filename.endswith("WHEEL"))
490
+ wheelfile_contents = wf.read(wheelfile)
491
+ assert b"\r" not in wheelfile_contents
492
+
493
+
494
+ def test_unix_epoch_timestamps(dummy_dist, monkeypatch, tmp_path):
495
+ monkeypatch.setenv("SOURCE_DATE_EPOCH", "0")
496
+ monkeypatch.chdir(dummy_dist)
497
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), build_number="2a").run()
498
+ with ZipFile("dist/dummy_dist-1.0-2a-py3-none-any.whl") as wf:
499
+ for zinfo in wf.filelist:
500
+ assert zinfo.date_time >= (1980, 1, 1, 0, 0, 0) # min epoch is used
501
+
502
+
503
+ def test_get_abi_tag_windows(monkeypatch):
504
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")
505
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313-win_amd64")
506
+ assert get_abi_tag() == "cp313"
507
+ monkeypatch.setattr(sys, "gettotalrefcount", lambda: 1, False)
508
+ assert get_abi_tag() == "cp313d"
509
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313t-win_amd64")
510
+ assert get_abi_tag() == "cp313td"
511
+ monkeypatch.delattr(sys, "gettotalrefcount")
512
+ assert get_abi_tag() == "cp313t"
513
+
514
+
515
+ def test_get_abi_tag_pypy_old(monkeypatch):
516
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
517
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy36-pp73")
518
+ assert get_abi_tag() == "pypy36_pp73"
519
+
520
+
521
+ def test_get_abi_tag_pypy_new(monkeypatch):
522
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy37-pp73-darwin")
523
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
524
+ assert get_abi_tag() == "pypy37_pp73"
525
+
526
+
527
+ def test_get_abi_tag_graalpy(monkeypatch):
528
+ monkeypatch.setattr(
529
+ sysconfig, "get_config_var", lambda x: "graalpy231-310-native-x86_64-linux"
530
+ )
531
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "graalpy")
532
+ assert get_abi_tag() == "graalpy231_310_native"
533
+
534
+
535
+ def test_get_abi_tag_fallback(monkeypatch):
536
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "unknown-python-310")
537
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "unknown-python")
538
+ assert get_abi_tag() == "unknown_python_310"
539
+
540
+
541
+ def test_platform_with_space(dummy_dist, monkeypatch):
542
+ """Ensure building on platforms with a space in the name succeed."""
543
+ monkeypatch.chdir(dummy_dist)
544
+ bdist_wheel_cmd(plat_name="isilon onefs").run()
545
+
546
+
547
+ def test_data_dir_with_tag_build(monkeypatch, tmp_path):
548
+ """
549
+ Setuptools allow authors to set PEP 440's local version segments
550
+ using ``egg_info.tag_build``. This should be reflected not only in the
551
+ ``.whl`` file name, but also in the ``.dist-info`` and ``.data`` dirs.
552
+ See pypa/setuptools#3997.
553
+ """
554
+ monkeypatch.chdir(tmp_path)
555
+ files = {
556
+ "setup.py": """
557
+ from setuptools import setup
558
+ setup(headers=["hello.h"])
559
+ """,
560
+ "setup.cfg": """
561
+ [metadata]
562
+ name = test
563
+ version = 1.0
564
+
565
+ [options.data_files]
566
+ hello/world = file.txt
567
+
568
+ [egg_info]
569
+ tag_build = +what
570
+ tag_date = 0
571
+ """,
572
+ "file.txt": "",
573
+ "hello.h": "",
574
+ }
575
+ for file, content in files.items():
576
+ with open(file, "w", encoding="utf-8") as fh:
577
+ fh.write(cleandoc(content))
578
+
579
+ bdist_wheel_cmd().run()
580
+
581
+ # Ensure .whl, .dist-info and .data contain the local segment
582
+ wheel_path = "dist/test-1.0+what-py3-none-any.whl"
583
+ assert os.path.exists(wheel_path)
584
+ entries = set(ZipFile(wheel_path).namelist())
585
+ for expected in (
586
+ "test-1.0+what.data/headers/hello.h",
587
+ "test-1.0+what.data/data/hello/world/file.txt",
588
+ "test-1.0+what.dist-info/METADATA",
589
+ "test-1.0+what.dist-info/WHEEL",
590
+ ):
591
+ assert expected in entries
592
+
593
+ for not_expected in (
594
+ "test.data/headers/hello.h",
595
+ "test-1.0.data/data/hello/world/file.txt",
596
+ "test.dist-info/METADATA",
597
+ "test-1.0.dist-info/WHEEL",
598
+ ):
599
+ assert not_expected not in entries
600
+
601
+
602
+ @pytest.mark.parametrize(
603
+ ("reported", "expected"),
604
+ [("linux-x86_64", "linux_i686"), ("linux-aarch64", "linux_armv7l")],
605
+ )
606
+ @pytest.mark.skipif(
607
+ platform.system() != "Linux", reason="Only makes sense to test on Linux"
608
+ )
609
+ def test_platform_linux32(reported, expected, monkeypatch):
610
+ monkeypatch.setattr(struct, "calcsize", lambda x: 4)
611
+ dist = setuptools.Distribution()
612
+ cmd = bdist_wheel(dist)
613
+ cmd.plat_name = reported
614
+ cmd.root_is_pure = False
615
+ _, _, actual = cmd.get_tag()
616
+ assert actual == expected
617
+
618
+
619
+ def test_no_ctypes(monkeypatch) -> None:
620
+ def _fake_import(name: str, *args, **kwargs):
621
+ if name == "ctypes":
622
+ raise ModuleNotFoundError(f"No module named {name}")
623
+
624
+ return importlib.__import__(name, *args, **kwargs)
625
+
626
+ with suppress(KeyError):
627
+ monkeypatch.delitem(sys.modules, "wheel.macosx_libfile")
628
+
629
+ # Install an importer shim that refuses to load ctypes
630
+ monkeypatch.setattr(builtins, "__import__", _fake_import)
631
+ with pytest.raises(ModuleNotFoundError, match="No module named ctypes"):
632
+ import wheel.macosx_libfile # noqa: F401
633
+
634
+ # Unload and reimport the bdist_wheel command module to make sure it won't try to
635
+ # import ctypes
636
+ monkeypatch.delitem(sys.modules, "setuptools.command.bdist_wheel")
637
+
638
+ import setuptools.command.bdist_wheel # noqa: F401
639
+
640
+
641
+ def test_dist_info_provided(dummy_dist, monkeypatch, tmp_path):
642
+ monkeypatch.chdir(dummy_dist)
643
+ distinfo = tmp_path / "dummy_dist.dist-info"
644
+
645
+ distinfo.mkdir()
646
+ (distinfo / "METADATA").write_text("name: helloworld", encoding="utf-8")
647
+
648
+ # We don't control the metadata. According to PEP-517, "The hook MAY also
649
+ # create other files inside this directory, and a build frontend MUST
650
+ # preserve".
651
+ (distinfo / "FOO").write_text("bar", encoding="utf-8")
652
+
653
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), dist_info_dir=str(distinfo)).run()
654
+ expected = {
655
+ "dummy_dist-1.0.dist-info/FOO",
656
+ "dummy_dist-1.0.dist-info/RECORD",
657
+ }
658
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
659
+ files_found = set(wf.namelist())
660
+ # Check that all expected files are there.
661
+ assert expected - files_found == set()
662
+ # Make sure there is no accidental egg-info bleeding into the wheel.
663
+ assert not [path for path in files_found if 'egg-info' in str(path)]
664
+
665
+
666
+ def test_allow_grace_period_parent_directory_license(monkeypatch, tmp_path):
667
+ # Motivation: https://github.com/pypa/setuptools/issues/4892
668
+ # TODO: Remove this test after deprecation period is over
669
+ files = {
670
+ "LICENSE.txt": "parent license", # <---- the license files are outside
671
+ "NOTICE.txt": "parent notice",
672
+ "python": {
673
+ "pyproject.toml": cleandoc(
674
+ """
675
+ [project]
676
+ name = "test-proj"
677
+ dynamic = ["version"] # <---- testing dynamic will not break
678
+ [tool.setuptools.dynamic]
679
+ version.file = "VERSION"
680
+ """
681
+ ),
682
+ "setup.cfg": cleandoc(
683
+ """
684
+ [metadata]
685
+ license_files =
686
+ ../LICENSE.txt
687
+ ../NOTICE.txt
688
+ """
689
+ ),
690
+ "VERSION": "42",
691
+ },
692
+ }
693
+ jaraco.path.build(files, prefix=str(tmp_path))
694
+ monkeypatch.chdir(tmp_path / "python")
695
+ msg = "Pattern '../.*.txt' cannot contain '..'"
696
+ with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
697
+ bdist_wheel_cmd().run()
698
+ with ZipFile("dist/test_proj-42-py3-none-any.whl") as wf:
699
+ files_found = set(wf.namelist())
700
+ expected_files = {
701
+ "test_proj-42.dist-info/licenses/LICENSE.txt",
702
+ "test_proj-42.dist-info/licenses/NOTICE.txt",
703
+ }
704
+ assert expected_files <= files_found
705
+
706
+ metadata = wf.read("test_proj-42.dist-info/METADATA").decode("utf8")
707
+ assert "License-File: LICENSE.txt" in metadata
708
+ assert "License-File: NOTICE.txt" in metadata
python_embeded/Lib/site-packages/setuptools/tests/test_build.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import Command
2
+ from setuptools.command.build import build
3
+ from setuptools.dist import Distribution
4
+
5
+
6
+ def test_distribution_gives_setuptools_build_obj(tmpdir_cwd):
7
+ """
8
+ Check that the setuptools Distribution uses the
9
+ setuptools specific build object.
10
+ """
11
+
12
+ dist = Distribution(
13
+ dict(
14
+ script_name='setup.py',
15
+ script_args=['build'],
16
+ packages=[],
17
+ package_data={'': ['path/*']},
18
+ )
19
+ )
20
+ assert isinstance(dist.get_command_obj("build"), build)
21
+
22
+
23
+ class Subcommand(Command):
24
+ """Dummy command to be used in tests"""
25
+
26
+ def initialize_options(self):
27
+ pass
28
+
29
+ def finalize_options(self):
30
+ pass
31
+
32
+ def run(self):
33
+ raise NotImplementedError("just to check if the command runs")