codekingpro commited on
Commit
bb91ac8
·
verified ·
1 Parent(s): cea4ed7

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/Lib/site-packages/setuptools/_distutils/command/__init__.py +23 -0
  2. python/Lib/site-packages/setuptools/_distutils/command/_framework_compat.py +54 -0
  3. python/Lib/site-packages/setuptools/_distutils/command/bdist.py +167 -0
  4. python/Lib/site-packages/setuptools/_distutils/command/bdist_dumb.py +141 -0
  5. python/Lib/site-packages/setuptools/_distutils/command/bdist_rpm.py +597 -0
  6. python/Lib/site-packages/setuptools/_distutils/command/build.py +156 -0
  7. python/Lib/site-packages/setuptools/_distutils/command/build_clib.py +199 -0
  8. python/Lib/site-packages/setuptools/_distutils/command/build_ext.py +811 -0
  9. python/Lib/site-packages/setuptools/_distutils/command/build_py.py +404 -0
  10. python/Lib/site-packages/setuptools/_distutils/command/build_scripts.py +150 -0
  11. python/Lib/site-packages/setuptools/_distutils/command/check.py +152 -0
  12. python/Lib/site-packages/setuptools/_distutils/command/clean.py +76 -0
  13. python/Lib/site-packages/setuptools/_distutils/command/config.py +348 -0
  14. python/Lib/site-packages/setuptools/_distutils/command/install.py +805 -0
  15. python/Lib/site-packages/setuptools/_distutils/command/install_data.py +94 -0
  16. python/Lib/site-packages/setuptools/_distutils/command/install_egg_info.py +90 -0
  17. python/Lib/site-packages/setuptools/_distutils/command/install_headers.py +46 -0
  18. python/Lib/site-packages/setuptools/_distutils/command/install_lib.py +236 -0
  19. python/Lib/site-packages/setuptools/_distutils/command/install_scripts.py +59 -0
  20. python/Lib/site-packages/setuptools/_distutils/command/sdist.py +521 -0
  21. python/Lib/site-packages/setuptools/_distutils/compat/__init__.py +18 -0
  22. python/Lib/site-packages/setuptools/_distutils/compat/numpy.py +2 -0
  23. python/Lib/site-packages/setuptools/_distutils/compat/py39.py +66 -0
  24. python/Lib/site-packages/setuptools/_distutils/tests/support.py +134 -0
  25. python/Lib/site-packages/setuptools/_distutils/tests/test_archive_util.py +342 -0
  26. python/Lib/site-packages/setuptools/_distutils/tests/test_bdist.py +47 -0
  27. python/Lib/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py +78 -0
  28. python/Lib/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py +127 -0
  29. python/Lib/site-packages/setuptools/_distutils/tests/test_build.py +49 -0
  30. python/Lib/site-packages/setuptools/_distutils/tests/test_build_clib.py +134 -0
  31. python/Lib/site-packages/setuptools/_distutils/tests/test_build_ext.py +628 -0
  32. python/Lib/site-packages/setuptools/_distutils/tests/test_build_py.py +196 -0
  33. python/Lib/site-packages/setuptools/_distutils/tests/test_build_scripts.py +96 -0
  34. python/Lib/site-packages/setuptools/_distutils/tests/test_check.py +194 -0
  35. python/Lib/site-packages/setuptools/_distutils/tests/test_clean.py +45 -0
  36. python/Lib/site-packages/setuptools/_distutils/tests/test_cmd.py +107 -0
  37. python/Lib/site-packages/setuptools/_distutils/tests/test_config_cmd.py +87 -0
  38. python/Lib/site-packages/setuptools/_distutils/tests/test_core.py +130 -0
  39. python/Lib/site-packages/setuptools/_distutils/tests/test_dir_util.py +139 -0
  40. python/Lib/site-packages/setuptools/_distutils/tests/test_dist.py +552 -0
  41. python/Lib/site-packages/setuptools/_distutils/tests/test_extension.py +117 -0
  42. python/Lib/site-packages/setuptools/_distutils/tests/test_file_util.py +95 -0
  43. python/Lib/site-packages/setuptools/_distutils/tests/test_filelist.py +336 -0
  44. python/Lib/site-packages/setuptools/_distutils/tests/test_install.py +245 -0
  45. python/Lib/site-packages/setuptools/_distutils/tests/test_install_data.py +74 -0
  46. python/Lib/site-packages/setuptools/_distutils/tests/test_install_headers.py +33 -0
  47. python/Lib/site-packages/setuptools/_vendor/autocommand/__pycache__/__init__.cpython-313.pyc +0 -0
  48. python/Lib/site-packages/setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-313.pyc +0 -0
  49. python/Lib/site-packages/setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-313.pyc +0 -0
  50. python/Lib/site-packages/setuptools/_vendor/autocommand/__pycache__/automain.cpython-313.pyc +0 -0
python/Lib/site-packages/setuptools/_distutils/command/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command
2
+
3
+ Package containing implementation of all the standard Distutils
4
+ commands."""
5
+
6
+ __all__ = [
7
+ 'build',
8
+ 'build_py',
9
+ 'build_ext',
10
+ 'build_clib',
11
+ 'build_scripts',
12
+ 'clean',
13
+ 'install',
14
+ 'install_lib',
15
+ 'install_headers',
16
+ 'install_scripts',
17
+ 'install_data',
18
+ 'sdist',
19
+ 'bdist',
20
+ 'bdist_dumb',
21
+ 'bdist_rpm',
22
+ 'check',
23
+ ]
python/Lib/site-packages/setuptools/_distutils/command/_framework_compat.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Backward compatibility for homebrew builds on macOS.
3
+ """
4
+
5
+ import functools
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ import sysconfig
10
+
11
+
12
+ @functools.lru_cache
13
+ def enabled():
14
+ """
15
+ Only enabled for Python 3.9 framework homebrew builds
16
+ except ensurepip and venv.
17
+ """
18
+ PY39 = (3, 9) < sys.version_info < (3, 10)
19
+ framework = sys.platform == 'darwin' and sys._framework
20
+ homebrew = "Cellar" in sysconfig.get_config_var('projectbase')
21
+ venv = sys.prefix != sys.base_prefix
22
+ ensurepip = os.environ.get("ENSUREPIP_OPTIONS")
23
+ return PY39 and framework and homebrew and not venv and not ensurepip
24
+
25
+
26
+ schemes = dict(
27
+ osx_framework_library=dict(
28
+ stdlib='{installed_base}/{platlibdir}/python{py_version_short}',
29
+ platstdlib='{platbase}/{platlibdir}/python{py_version_short}',
30
+ purelib='{homebrew_prefix}/lib/python{py_version_short}/site-packages',
31
+ platlib='{homebrew_prefix}/{platlibdir}/python{py_version_short}/site-packages',
32
+ include='{installed_base}/include/python{py_version_short}{abiflags}',
33
+ platinclude='{installed_platbase}/include/python{py_version_short}{abiflags}',
34
+ scripts='{homebrew_prefix}/bin',
35
+ data='{homebrew_prefix}',
36
+ )
37
+ )
38
+
39
+
40
+ @functools.lru_cache
41
+ def vars():
42
+ if not enabled():
43
+ return {}
44
+ homebrew_prefix = subprocess.check_output(['brew', '--prefix'], text=True).strip()
45
+ return locals()
46
+
47
+
48
+ def scheme(name):
49
+ """
50
+ Override the selected scheme for posix_prefix.
51
+ """
52
+ if not enabled() or not name.endswith('_prefix'):
53
+ return name
54
+ return 'osx_framework_library'
python/Lib/site-packages/setuptools/_distutils/command/bdist.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.bdist
2
+
3
+ Implements the Distutils 'bdist' command (create a built [binary]
4
+ distribution)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import warnings
10
+ from collections.abc import Callable
11
+ from typing import TYPE_CHECKING, ClassVar
12
+
13
+ from ..core import Command
14
+ from ..errors import DistutilsOptionError, DistutilsPlatformError
15
+ from ..util import get_platform
16
+
17
+ if TYPE_CHECKING:
18
+ from typing_extensions import deprecated
19
+ else:
20
+
21
+ def deprecated(message):
22
+ return lambda fn: fn
23
+
24
+
25
+ def show_formats():
26
+ """Print list of available formats (arguments to "--format" option)."""
27
+ from ..fancy_getopt import FancyGetopt
28
+
29
+ formats = [
30
+ ("formats=" + format, None, bdist.format_commands[format][1])
31
+ for format in bdist.format_commands
32
+ ]
33
+ pretty_printer = FancyGetopt(formats)
34
+ pretty_printer.print_help("List of available distribution formats:")
35
+
36
+
37
+ class ListCompat(dict[str, tuple[str, str]]):
38
+ # adapter to allow for Setuptools compatibility in format_commands
39
+ @deprecated("format_commands is now a dict. append is deprecated.")
40
+ def append(self, item: object) -> None:
41
+ warnings.warn(
42
+ "format_commands is now a dict. append is deprecated.",
43
+ DeprecationWarning,
44
+ stacklevel=2,
45
+ )
46
+
47
+
48
+ class bdist(Command):
49
+ description = "create a built (binary) distribution"
50
+
51
+ user_options = [
52
+ ('bdist-base=', 'b', "temporary directory for creating built distributions"),
53
+ (
54
+ 'plat-name=',
55
+ 'p',
56
+ "platform name to embed in generated filenames "
57
+ f"[default: {get_platform()}]",
58
+ ),
59
+ ('formats=', None, "formats for distribution (comma-separated list)"),
60
+ (
61
+ 'dist-dir=',
62
+ 'd',
63
+ "directory to put final built distributions in [default: dist]",
64
+ ),
65
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
66
+ (
67
+ 'owner=',
68
+ 'u',
69
+ "Owner name used when creating a tar file [default: current user]",
70
+ ),
71
+ (
72
+ 'group=',
73
+ 'g',
74
+ "Group name used when creating a tar file [default: current group]",
75
+ ),
76
+ ]
77
+
78
+ boolean_options: ClassVar[list[str]] = ['skip-build']
79
+
80
+ help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
81
+ ('help-formats', None, "lists available distribution formats", show_formats),
82
+ ]
83
+
84
+ # The following commands do not take a format option from bdist
85
+ no_format_option: ClassVar[tuple[str, ...]] = ('bdist_rpm',)
86
+
87
+ # This won't do in reality: will need to distinguish RPM-ish Linux,
88
+ # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.
89
+ default_format: ClassVar[dict[str, str]] = {'posix': 'gztar', 'nt': 'zip'}
90
+
91
+ # Define commands in preferred order for the --help-formats option
92
+ format_commands = ListCompat({
93
+ 'rpm': ('bdist_rpm', "RPM distribution"),
94
+ 'gztar': ('bdist_dumb', "gzip'ed tar file"),
95
+ 'bztar': ('bdist_dumb', "bzip2'ed tar file"),
96
+ 'xztar': ('bdist_dumb', "xz'ed tar file"),
97
+ 'ztar': ('bdist_dumb', "compressed tar file"),
98
+ 'tar': ('bdist_dumb', "tar file"),
99
+ 'zip': ('bdist_dumb', "ZIP file"),
100
+ })
101
+
102
+ # for compatibility until consumers only reference format_commands
103
+ format_command = format_commands
104
+
105
+ def initialize_options(self):
106
+ self.bdist_base = None
107
+ self.plat_name = None
108
+ self.formats = None
109
+ self.dist_dir = None
110
+ self.skip_build = False
111
+ self.group = None
112
+ self.owner = None
113
+
114
+ def finalize_options(self) -> None:
115
+ # have to finalize 'plat_name' before 'bdist_base'
116
+ if self.plat_name is None:
117
+ if self.skip_build:
118
+ self.plat_name = get_platform()
119
+ else:
120
+ self.plat_name = self.get_finalized_command('build').plat_name
121
+
122
+ # 'bdist_base' -- parent of per-built-distribution-format
123
+ # temporary directories (eg. we'll probably have
124
+ # "build/bdist.<plat>/dumb", "build/bdist.<plat>/rpm", etc.)
125
+ if self.bdist_base is None:
126
+ build_base = self.get_finalized_command('build').build_base
127
+ self.bdist_base = os.path.join(build_base, 'bdist.' + self.plat_name)
128
+
129
+ self.ensure_string_list('formats')
130
+ if self.formats is None:
131
+ try:
132
+ self.formats = [self.default_format[os.name]]
133
+ except KeyError:
134
+ raise DistutilsPlatformError(
135
+ "don't know how to create built distributions "
136
+ f"on platform {os.name}"
137
+ )
138
+
139
+ if self.dist_dir is None:
140
+ self.dist_dir = "dist"
141
+
142
+ def run(self) -> None:
143
+ # Figure out which sub-commands we need to run.
144
+ commands = []
145
+ for format in self.formats:
146
+ try:
147
+ commands.append(self.format_commands[format][0])
148
+ except KeyError:
149
+ raise DistutilsOptionError(f"invalid format '{format}'")
150
+
151
+ # Reinitialize and run each command.
152
+ for i in range(len(self.formats)):
153
+ cmd_name = commands[i]
154
+ sub_cmd = self.reinitialize_command(cmd_name)
155
+ if cmd_name not in self.no_format_option:
156
+ sub_cmd.format = self.formats[i]
157
+
158
+ # passing the owner and group names for tar archiving
159
+ if cmd_name == 'bdist_dumb':
160
+ sub_cmd.owner = self.owner
161
+ sub_cmd.group = self.group
162
+
163
+ # If we're going to need to run this command again, tell it to
164
+ # keep its temporary files around so subsequent runs go faster.
165
+ if cmd_name in commands[i + 1 :]:
166
+ sub_cmd.keep_temp = True
167
+ self.run_command(cmd_name)
python/Lib/site-packages/setuptools/_distutils/command/bdist_dumb.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.bdist_dumb
2
+
3
+ Implements the Distutils 'bdist_dumb' command (create a "dumb" built
4
+ distribution -- i.e., just an archive to be unpacked under $prefix or
5
+ $exec_prefix)."""
6
+
7
+ import os
8
+ from distutils._log import log
9
+ from typing import ClassVar
10
+
11
+ from ..core import Command
12
+ from ..dir_util import ensure_relative, remove_tree
13
+ from ..errors import DistutilsPlatformError
14
+ from ..sysconfig import get_python_version
15
+ from ..util import get_platform
16
+
17
+
18
+ class bdist_dumb(Command):
19
+ description = "create a \"dumb\" built distribution"
20
+
21
+ user_options = [
22
+ ('bdist-dir=', 'd', "temporary directory for creating the distribution"),
23
+ (
24
+ 'plat-name=',
25
+ 'p',
26
+ "platform name to embed in generated filenames "
27
+ f"[default: {get_platform()}]",
28
+ ),
29
+ (
30
+ 'format=',
31
+ 'f',
32
+ "archive format to create (tar, gztar, bztar, xztar, ztar, zip)",
33
+ ),
34
+ (
35
+ 'keep-temp',
36
+ 'k',
37
+ "keep the pseudo-installation tree around after creating the distribution archive",
38
+ ),
39
+ ('dist-dir=', 'd', "directory to put final built distributions in"),
40
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
41
+ (
42
+ 'relative',
43
+ None,
44
+ "build the archive using relative paths [default: false]",
45
+ ),
46
+ (
47
+ 'owner=',
48
+ 'u',
49
+ "Owner name used when creating a tar file [default: current user]",
50
+ ),
51
+ (
52
+ 'group=',
53
+ 'g',
54
+ "Group name used when creating a tar file [default: current group]",
55
+ ),
56
+ ]
57
+
58
+ boolean_options: ClassVar[list[str]] = ['keep-temp', 'skip-build', 'relative']
59
+
60
+ default_format = {'posix': 'gztar', 'nt': 'zip'}
61
+
62
+ def initialize_options(self):
63
+ self.bdist_dir = None
64
+ self.plat_name = None
65
+ self.format = None
66
+ self.keep_temp = False
67
+ self.dist_dir = None
68
+ self.skip_build = None
69
+ self.relative = False
70
+ self.owner = None
71
+ self.group = None
72
+
73
+ def finalize_options(self):
74
+ if self.bdist_dir is None:
75
+ bdist_base = self.get_finalized_command('bdist').bdist_base
76
+ self.bdist_dir = os.path.join(bdist_base, 'dumb')
77
+
78
+ if self.format is None:
79
+ try:
80
+ self.format = self.default_format[os.name]
81
+ except KeyError:
82
+ raise DistutilsPlatformError(
83
+ "don't know how to create dumb built distributions "
84
+ f"on platform {os.name}"
85
+ )
86
+
87
+ self.set_undefined_options(
88
+ 'bdist',
89
+ ('dist_dir', 'dist_dir'),
90
+ ('plat_name', 'plat_name'),
91
+ ('skip_build', 'skip_build'),
92
+ )
93
+
94
+ def run(self):
95
+ if not self.skip_build:
96
+ self.run_command('build')
97
+
98
+ install = self.reinitialize_command('install', reinit_subcommands=True)
99
+ install.root = self.bdist_dir
100
+ install.skip_build = self.skip_build
101
+ install.warn_dir = False
102
+
103
+ log.info("installing to %s", self.bdist_dir)
104
+ self.run_command('install')
105
+
106
+ # And make an archive relative to the root of the
107
+ # pseudo-installation tree.
108
+ archive_basename = f"{self.distribution.get_fullname()}.{self.plat_name}"
109
+
110
+ pseudoinstall_root = os.path.join(self.dist_dir, archive_basename)
111
+ if not self.relative:
112
+ archive_root = self.bdist_dir
113
+ else:
114
+ if self.distribution.has_ext_modules() and (
115
+ install.install_base != install.install_platbase
116
+ ):
117
+ raise DistutilsPlatformError(
118
+ "can't make a dumb built distribution where "
119
+ f"base and platbase are different ({install.install_base!r}, {install.install_platbase!r})"
120
+ )
121
+ else:
122
+ archive_root = os.path.join(
123
+ self.bdist_dir, ensure_relative(install.install_base)
124
+ )
125
+
126
+ # Make the archive
127
+ filename = self.make_archive(
128
+ pseudoinstall_root,
129
+ self.format,
130
+ root_dir=archive_root,
131
+ owner=self.owner,
132
+ group=self.group,
133
+ )
134
+ if self.distribution.has_ext_modules():
135
+ pyversion = get_python_version()
136
+ else:
137
+ pyversion = 'any'
138
+ self.distribution.dist_files.append(('bdist_dumb', pyversion, filename))
139
+
140
+ if not self.keep_temp:
141
+ remove_tree(self.bdist_dir)
python/Lib/site-packages/setuptools/_distutils/command/bdist_rpm.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.bdist_rpm
2
+
3
+ Implements the Distutils 'bdist_rpm' command (create RPM source and binary
4
+ distributions)."""
5
+
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ from distutils._log import log
10
+ from typing import ClassVar
11
+
12
+ from ..core import Command
13
+ from ..debug import DEBUG
14
+ from ..errors import (
15
+ DistutilsExecError,
16
+ DistutilsFileError,
17
+ DistutilsOptionError,
18
+ DistutilsPlatformError,
19
+ )
20
+ from ..file_util import write_file
21
+ from ..sysconfig import get_python_version
22
+
23
+
24
+ class bdist_rpm(Command):
25
+ description = "create an RPM distribution"
26
+
27
+ user_options = [
28
+ ('bdist-base=', None, "base directory for creating built distributions"),
29
+ (
30
+ 'rpm-base=',
31
+ None,
32
+ "base directory for creating RPMs (defaults to \"rpm\" under "
33
+ "--bdist-base; must be specified for RPM 2)",
34
+ ),
35
+ (
36
+ 'dist-dir=',
37
+ 'd',
38
+ "directory to put final RPM files in (and .spec files if --spec-only)",
39
+ ),
40
+ (
41
+ 'python=',
42
+ None,
43
+ "path to Python interpreter to hard-code in the .spec file "
44
+ "[default: \"python\"]",
45
+ ),
46
+ (
47
+ 'fix-python',
48
+ None,
49
+ "hard-code the exact path to the current Python interpreter in "
50
+ "the .spec file",
51
+ ),
52
+ ('spec-only', None, "only regenerate spec file"),
53
+ ('source-only', None, "only generate source RPM"),
54
+ ('binary-only', None, "only generate binary RPM"),
55
+ ('use-bzip2', None, "use bzip2 instead of gzip to create source distribution"),
56
+ # More meta-data: too RPM-specific to put in the setup script,
57
+ # but needs to go in the .spec file -- so we make these options
58
+ # to "bdist_rpm". The idea is that packagers would put this
59
+ # info in setup.cfg, although they are of course free to
60
+ # supply it on the command line.
61
+ (
62
+ 'distribution-name=',
63
+ None,
64
+ "name of the (Linux) distribution to which this "
65
+ "RPM applies (*not* the name of the module distribution!)",
66
+ ),
67
+ ('group=', None, "package classification [default: \"Development/Libraries\"]"),
68
+ ('release=', None, "RPM release number"),
69
+ ('serial=', None, "RPM serial number"),
70
+ (
71
+ 'vendor=',
72
+ None,
73
+ "RPM \"vendor\" (eg. \"Joe Blow <joe@example.com>\") "
74
+ "[default: maintainer or author from setup script]",
75
+ ),
76
+ (
77
+ 'packager=',
78
+ None,
79
+ "RPM packager (eg. \"Jane Doe <jane@example.net>\") [default: vendor]",
80
+ ),
81
+ ('doc-files=', None, "list of documentation files (space or comma-separated)"),
82
+ ('changelog=', None, "RPM changelog"),
83
+ ('icon=', None, "name of icon file"),
84
+ ('provides=', None, "capabilities provided by this package"),
85
+ ('requires=', None, "capabilities required by this package"),
86
+ ('conflicts=', None, "capabilities which conflict with this package"),
87
+ ('build-requires=', None, "capabilities required to build this package"),
88
+ ('obsoletes=', None, "capabilities made obsolete by this package"),
89
+ ('no-autoreq', None, "do not automatically calculate dependencies"),
90
+ # Actions to take when building RPM
91
+ ('keep-temp', 'k', "don't clean up RPM build directory"),
92
+ ('no-keep-temp', None, "clean up RPM build directory [default]"),
93
+ (
94
+ 'use-rpm-opt-flags',
95
+ None,
96
+ "compile with RPM_OPT_FLAGS when building from source RPM",
97
+ ),
98
+ ('no-rpm-opt-flags', None, "do not pass any RPM CFLAGS to compiler"),
99
+ ('rpm3-mode', None, "RPM 3 compatibility mode (default)"),
100
+ ('rpm2-mode', None, "RPM 2 compatibility mode"),
101
+ # Add the hooks necessary for specifying custom scripts
102
+ ('prep-script=', None, "Specify a script for the PREP phase of RPM building"),
103
+ ('build-script=', None, "Specify a script for the BUILD phase of RPM building"),
104
+ (
105
+ 'pre-install=',
106
+ None,
107
+ "Specify a script for the pre-INSTALL phase of RPM building",
108
+ ),
109
+ (
110
+ 'install-script=',
111
+ None,
112
+ "Specify a script for the INSTALL phase of RPM building",
113
+ ),
114
+ (
115
+ 'post-install=',
116
+ None,
117
+ "Specify a script for the post-INSTALL phase of RPM building",
118
+ ),
119
+ (
120
+ 'pre-uninstall=',
121
+ None,
122
+ "Specify a script for the pre-UNINSTALL phase of RPM building",
123
+ ),
124
+ (
125
+ 'post-uninstall=',
126
+ None,
127
+ "Specify a script for the post-UNINSTALL phase of RPM building",
128
+ ),
129
+ ('clean-script=', None, "Specify a script for the CLEAN phase of RPM building"),
130
+ (
131
+ 'verify-script=',
132
+ None,
133
+ "Specify a script for the VERIFY phase of the RPM build",
134
+ ),
135
+ # Allow a packager to explicitly force an architecture
136
+ ('force-arch=', None, "Force an architecture onto the RPM build process"),
137
+ ('quiet', 'q', "Run the INSTALL phase of RPM building in quiet mode"),
138
+ ]
139
+
140
+ boolean_options: ClassVar[list[str]] = [
141
+ 'keep-temp',
142
+ 'use-rpm-opt-flags',
143
+ 'rpm3-mode',
144
+ 'no-autoreq',
145
+ 'quiet',
146
+ ]
147
+
148
+ negative_opt: ClassVar[dict[str, str]] = {
149
+ 'no-keep-temp': 'keep-temp',
150
+ 'no-rpm-opt-flags': 'use-rpm-opt-flags',
151
+ 'rpm2-mode': 'rpm3-mode',
152
+ }
153
+
154
+ def initialize_options(self):
155
+ self.bdist_base = None
156
+ self.rpm_base = None
157
+ self.dist_dir = None
158
+ self.python = None
159
+ self.fix_python = None
160
+ self.spec_only = None
161
+ self.binary_only = None
162
+ self.source_only = None
163
+ self.use_bzip2 = None
164
+
165
+ self.distribution_name = None
166
+ self.group = None
167
+ self.release = None
168
+ self.serial = None
169
+ self.vendor = None
170
+ self.packager = None
171
+ self.doc_files = None
172
+ self.changelog = None
173
+ self.icon = None
174
+
175
+ self.prep_script = None
176
+ self.build_script = None
177
+ self.install_script = None
178
+ self.clean_script = None
179
+ self.verify_script = None
180
+ self.pre_install = None
181
+ self.post_install = None
182
+ self.pre_uninstall = None
183
+ self.post_uninstall = None
184
+ self.prep = None
185
+ self.provides = None
186
+ self.requires = None
187
+ self.conflicts = None
188
+ self.build_requires = None
189
+ self.obsoletes = None
190
+
191
+ self.keep_temp = False
192
+ self.use_rpm_opt_flags = True
193
+ self.rpm3_mode = True
194
+ self.no_autoreq = False
195
+
196
+ self.force_arch = None
197
+ self.quiet = False
198
+
199
+ def finalize_options(self) -> None:
200
+ self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))
201
+ if self.rpm_base is None:
202
+ if not self.rpm3_mode:
203
+ raise DistutilsOptionError("you must specify --rpm-base in RPM 2 mode")
204
+ self.rpm_base = os.path.join(self.bdist_base, "rpm")
205
+
206
+ if self.python is None:
207
+ if self.fix_python:
208
+ self.python = sys.executable
209
+ else:
210
+ self.python = "python3"
211
+ elif self.fix_python:
212
+ raise DistutilsOptionError(
213
+ "--python and --fix-python are mutually exclusive options"
214
+ )
215
+
216
+ if os.name != 'posix':
217
+ raise DistutilsPlatformError(
218
+ f"don't know how to create RPM distributions on platform {os.name}"
219
+ )
220
+ if self.binary_only and self.source_only:
221
+ raise DistutilsOptionError(
222
+ "cannot supply both '--source-only' and '--binary-only'"
223
+ )
224
+
225
+ # don't pass CFLAGS to pure python distributions
226
+ if not self.distribution.has_ext_modules():
227
+ self.use_rpm_opt_flags = False
228
+
229
+ self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
230
+ self.finalize_package_data()
231
+
232
+ def finalize_package_data(self) -> None:
233
+ self.ensure_string('group', "Development/Libraries")
234
+ self.ensure_string(
235
+ 'vendor',
236
+ f"{self.distribution.get_contact()} <{self.distribution.get_contact_email()}>",
237
+ )
238
+ self.ensure_string('packager')
239
+ self.ensure_string_list('doc_files')
240
+ if isinstance(self.doc_files, list):
241
+ for readme in ('README', 'README.txt'):
242
+ if os.path.exists(readme) and readme not in self.doc_files:
243
+ self.doc_files.append(readme)
244
+
245
+ self.ensure_string('release', "1")
246
+ self.ensure_string('serial') # should it be an int?
247
+
248
+ self.ensure_string('distribution_name')
249
+
250
+ self.ensure_string('changelog')
251
+ # Format changelog correctly
252
+ self.changelog = self._format_changelog(self.changelog)
253
+
254
+ self.ensure_filename('icon')
255
+
256
+ self.ensure_filename('prep_script')
257
+ self.ensure_filename('build_script')
258
+ self.ensure_filename('install_script')
259
+ self.ensure_filename('clean_script')
260
+ self.ensure_filename('verify_script')
261
+ self.ensure_filename('pre_install')
262
+ self.ensure_filename('post_install')
263
+ self.ensure_filename('pre_uninstall')
264
+ self.ensure_filename('post_uninstall')
265
+
266
+ # XXX don't forget we punted on summaries and descriptions -- they
267
+ # should be handled here eventually!
268
+
269
+ # Now *this* is some meta-data that belongs in the setup script...
270
+ self.ensure_string_list('provides')
271
+ self.ensure_string_list('requires')
272
+ self.ensure_string_list('conflicts')
273
+ self.ensure_string_list('build_requires')
274
+ self.ensure_string_list('obsoletes')
275
+
276
+ self.ensure_string('force_arch')
277
+
278
+ def run(self) -> None: # noqa: C901
279
+ if DEBUG:
280
+ print("before _get_package_data():")
281
+ print("vendor =", self.vendor)
282
+ print("packager =", self.packager)
283
+ print("doc_files =", self.doc_files)
284
+ print("changelog =", self.changelog)
285
+
286
+ # make directories
287
+ if self.spec_only:
288
+ spec_dir = self.dist_dir
289
+ self.mkpath(spec_dir)
290
+ else:
291
+ rpm_dir = {}
292
+ for d in ('SOURCES', 'SPECS', 'BUILD', 'RPMS', 'SRPMS'):
293
+ rpm_dir[d] = os.path.join(self.rpm_base, d)
294
+ self.mkpath(rpm_dir[d])
295
+ spec_dir = rpm_dir['SPECS']
296
+
297
+ # Spec file goes into 'dist_dir' if '--spec-only specified',
298
+ # build/rpm.<plat> otherwise.
299
+ spec_path = os.path.join(spec_dir, f"{self.distribution.get_name()}.spec")
300
+ self.execute(
301
+ write_file, (spec_path, self._make_spec_file()), f"writing '{spec_path}'"
302
+ )
303
+
304
+ if self.spec_only: # stop if requested
305
+ return
306
+
307
+ # Make a source distribution and copy to SOURCES directory with
308
+ # optional icon.
309
+ saved_dist_files = self.distribution.dist_files[:]
310
+ sdist = self.reinitialize_command('sdist')
311
+ if self.use_bzip2:
312
+ sdist.formats = ['bztar']
313
+ else:
314
+ sdist.formats = ['gztar']
315
+ self.run_command('sdist')
316
+ self.distribution.dist_files = saved_dist_files
317
+
318
+ source = sdist.get_archive_files()[0]
319
+ source_dir = rpm_dir['SOURCES']
320
+ self.copy_file(source, source_dir)
321
+
322
+ if self.icon:
323
+ if os.path.exists(self.icon):
324
+ self.copy_file(self.icon, source_dir)
325
+ else:
326
+ raise DistutilsFileError(f"icon file '{self.icon}' does not exist")
327
+
328
+ # build package
329
+ log.info("building RPMs")
330
+ rpm_cmd = ['rpmbuild']
331
+
332
+ if self.source_only: # what kind of RPMs?
333
+ rpm_cmd.append('-bs')
334
+ elif self.binary_only:
335
+ rpm_cmd.append('-bb')
336
+ else:
337
+ rpm_cmd.append('-ba')
338
+ rpm_cmd.extend(['--define', f'__python {self.python}'])
339
+ if self.rpm3_mode:
340
+ rpm_cmd.extend(['--define', f'_topdir {os.path.abspath(self.rpm_base)}'])
341
+ if not self.keep_temp:
342
+ rpm_cmd.append('--clean')
343
+
344
+ if self.quiet:
345
+ rpm_cmd.append('--quiet')
346
+
347
+ rpm_cmd.append(spec_path)
348
+ # Determine the binary rpm names that should be built out of this spec
349
+ # file
350
+ # Note that some of these may not be really built (if the file
351
+ # list is empty)
352
+ nvr_string = "%{name}-%{version}-%{release}"
353
+ src_rpm = nvr_string + ".src.rpm"
354
+ non_src_rpm = "%{arch}/" + nvr_string + ".%{arch}.rpm"
355
+ q_cmd = rf"rpm -q --qf '{src_rpm} {non_src_rpm}\n' --specfile '{spec_path}'"
356
+
357
+ out = os.popen(q_cmd)
358
+ try:
359
+ binary_rpms = []
360
+ source_rpm = None
361
+ while True:
362
+ line = out.readline()
363
+ if not line:
364
+ break
365
+ ell = line.strip().split()
366
+ assert len(ell) == 2
367
+ binary_rpms.append(ell[1])
368
+ # The source rpm is named after the first entry in the spec file
369
+ if source_rpm is None:
370
+ source_rpm = ell[0]
371
+
372
+ status = out.close()
373
+ if status:
374
+ raise DistutilsExecError(f"Failed to execute: {q_cmd!r}")
375
+
376
+ finally:
377
+ out.close()
378
+
379
+ self.spawn(rpm_cmd)
380
+
381
+ if self.distribution.has_ext_modules():
382
+ pyversion = get_python_version()
383
+ else:
384
+ pyversion = 'any'
385
+
386
+ if not self.binary_only:
387
+ srpm = os.path.join(rpm_dir['SRPMS'], source_rpm)
388
+ assert os.path.exists(srpm)
389
+ self.move_file(srpm, self.dist_dir)
390
+ filename = os.path.join(self.dist_dir, source_rpm)
391
+ self.distribution.dist_files.append(('bdist_rpm', pyversion, filename))
392
+
393
+ if not self.source_only:
394
+ for rpm in binary_rpms:
395
+ rpm = os.path.join(rpm_dir['RPMS'], rpm)
396
+ if os.path.exists(rpm):
397
+ self.move_file(rpm, self.dist_dir)
398
+ filename = os.path.join(self.dist_dir, os.path.basename(rpm))
399
+ self.distribution.dist_files.append((
400
+ 'bdist_rpm',
401
+ pyversion,
402
+ filename,
403
+ ))
404
+
405
+ def _dist_path(self, path):
406
+ return os.path.join(self.dist_dir, os.path.basename(path))
407
+
408
+ def _make_spec_file(self): # noqa: C901
409
+ """Generate the text of an RPM spec file and return it as a
410
+ list of strings (one per line).
411
+ """
412
+ # definitions and headers
413
+ spec_file = [
414
+ '%define name ' + self.distribution.get_name(),
415
+ '%define version ' + self.distribution.get_version().replace('-', '_'),
416
+ '%define unmangled_version ' + self.distribution.get_version(),
417
+ '%define release ' + self.release.replace('-', '_'),
418
+ '',
419
+ 'Summary: ' + (self.distribution.get_description() or "UNKNOWN"),
420
+ ]
421
+
422
+ # Workaround for #14443 which affects some RPM based systems such as
423
+ # RHEL6 (and probably derivatives)
424
+ vendor_hook = subprocess.getoutput('rpm --eval %{__os_install_post}')
425
+ # Generate a potential replacement value for __os_install_post (whilst
426
+ # normalizing the whitespace to simplify the test for whether the
427
+ # invocation of brp-python-bytecompile passes in __python):
428
+ vendor_hook = '\n'.join([
429
+ f' {line.strip()} \\' for line in vendor_hook.splitlines()
430
+ ])
431
+ problem = "brp-python-bytecompile \\\n"
432
+ fixed = "brp-python-bytecompile %{__python} \\\n"
433
+ fixed_hook = vendor_hook.replace(problem, fixed)
434
+ if fixed_hook != vendor_hook:
435
+ spec_file.append('# Workaround for https://bugs.python.org/issue14443')
436
+ spec_file.append('%define __os_install_post ' + fixed_hook + '\n')
437
+
438
+ # put locale summaries into spec file
439
+ # XXX not supported for now (hard to put a dictionary
440
+ # in a config file -- arg!)
441
+ # for locale in self.summaries.keys():
442
+ # spec_file.append('Summary(%s): %s' % (locale,
443
+ # self.summaries[locale]))
444
+
445
+ spec_file.extend([
446
+ 'Name: %{name}',
447
+ 'Version: %{version}',
448
+ 'Release: %{release}',
449
+ ])
450
+
451
+ # XXX yuck! this filename is available from the "sdist" command,
452
+ # but only after it has run: and we create the spec file before
453
+ # running "sdist", in case of --spec-only.
454
+ if self.use_bzip2:
455
+ spec_file.append('Source0: %{name}-%{unmangled_version}.tar.bz2')
456
+ else:
457
+ spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz')
458
+
459
+ spec_file.extend([
460
+ 'License: ' + (self.distribution.get_license() or "UNKNOWN"),
461
+ 'Group: ' + self.group,
462
+ 'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
463
+ 'Prefix: %{_prefix}',
464
+ ])
465
+
466
+ if not self.force_arch:
467
+ # noarch if no extension modules
468
+ if not self.distribution.has_ext_modules():
469
+ spec_file.append('BuildArch: noarch')
470
+ else:
471
+ spec_file.append(f'BuildArch: {self.force_arch}')
472
+
473
+ for field in (
474
+ 'Vendor',
475
+ 'Packager',
476
+ 'Provides',
477
+ 'Requires',
478
+ 'Conflicts',
479
+ 'Obsoletes',
480
+ ):
481
+ val = getattr(self, field.lower())
482
+ if isinstance(val, list):
483
+ spec_file.append('{}: {}'.format(field, ' '.join(val)))
484
+ elif val is not None:
485
+ spec_file.append(f'{field}: {val}')
486
+
487
+ if self.distribution.get_url():
488
+ spec_file.append('Url: ' + self.distribution.get_url())
489
+
490
+ if self.distribution_name:
491
+ spec_file.append('Distribution: ' + self.distribution_name)
492
+
493
+ if self.build_requires:
494
+ spec_file.append('BuildRequires: ' + ' '.join(self.build_requires))
495
+
496
+ if self.icon:
497
+ spec_file.append('Icon: ' + os.path.basename(self.icon))
498
+
499
+ if self.no_autoreq:
500
+ spec_file.append('AutoReq: 0')
501
+
502
+ spec_file.extend([
503
+ '',
504
+ '%description',
505
+ self.distribution.get_long_description() or "",
506
+ ])
507
+
508
+ # put locale descriptions into spec file
509
+ # XXX again, suppressed because config file syntax doesn't
510
+ # easily support this ;-(
511
+ # for locale in self.descriptions.keys():
512
+ # spec_file.extend([
513
+ # '',
514
+ # '%description -l ' + locale,
515
+ # self.descriptions[locale],
516
+ # ])
517
+
518
+ # rpm scripts
519
+ # figure out default build script
520
+ def_setup_call = f"{self.python} {os.path.basename(sys.argv[0])}"
521
+ def_build = f"{def_setup_call} build"
522
+ if self.use_rpm_opt_flags:
523
+ def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build
524
+
525
+ # insert contents of files
526
+
527
+ # XXX this is kind of misleading: user-supplied options are files
528
+ # that we open and interpolate into the spec file, but the defaults
529
+ # are just text that we drop in as-is. Hmmm.
530
+
531
+ install_cmd = f'{def_setup_call} install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES'
532
+
533
+ script_options = [
534
+ ('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"),
535
+ ('build', 'build_script', def_build),
536
+ ('install', 'install_script', install_cmd),
537
+ ('clean', 'clean_script', "rm -rf $RPM_BUILD_ROOT"),
538
+ ('verifyscript', 'verify_script', None),
539
+ ('pre', 'pre_install', None),
540
+ ('post', 'post_install', None),
541
+ ('preun', 'pre_uninstall', None),
542
+ ('postun', 'post_uninstall', None),
543
+ ]
544
+
545
+ for rpm_opt, attr, default in script_options:
546
+ # Insert contents of file referred to, if no file is referred to
547
+ # use 'default' as contents of script
548
+ val = getattr(self, attr)
549
+ if val or default:
550
+ spec_file.extend([
551
+ '',
552
+ '%' + rpm_opt,
553
+ ])
554
+ if val:
555
+ with open(val) as f:
556
+ spec_file.extend(f.read().split('\n'))
557
+ else:
558
+ spec_file.append(default)
559
+
560
+ # files section
561
+ spec_file.extend([
562
+ '',
563
+ '%files -f INSTALLED_FILES',
564
+ '%defattr(-,root,root)',
565
+ ])
566
+
567
+ if self.doc_files:
568
+ spec_file.append('%doc ' + ' '.join(self.doc_files))
569
+
570
+ if self.changelog:
571
+ spec_file.extend([
572
+ '',
573
+ '%changelog',
574
+ ])
575
+ spec_file.extend(self.changelog)
576
+
577
+ return spec_file
578
+
579
+ def _format_changelog(self, changelog):
580
+ """Format the changelog correctly and convert it to a list of strings"""
581
+ if not changelog:
582
+ return changelog
583
+ new_changelog = []
584
+ for line in changelog.strip().split('\n'):
585
+ line = line.strip()
586
+ if line[0] == '*':
587
+ new_changelog.extend(['', line])
588
+ elif line[0] == '-':
589
+ new_changelog.append(line)
590
+ else:
591
+ new_changelog.append(' ' + line)
592
+
593
+ # strip trailing newline inserted by first changelog entry
594
+ if not new_changelog[0]:
595
+ del new_changelog[0]
596
+
597
+ return new_changelog
python/Lib/site-packages/setuptools/_distutils/command/build.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build
2
+
3
+ Implements the Distutils 'build' command."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import sys
9
+ import sysconfig
10
+ from collections.abc import Callable
11
+ from typing import ClassVar
12
+
13
+ from ..ccompiler import show_compilers
14
+ from ..core import Command
15
+ from ..errors import DistutilsOptionError
16
+ from ..util import get_platform
17
+
18
+
19
+ class build(Command):
20
+ description = "build everything needed to install"
21
+
22
+ user_options = [
23
+ ('build-base=', 'b', "base directory for build library"),
24
+ ('build-purelib=', None, "build directory for platform-neutral distributions"),
25
+ ('build-platlib=', None, "build directory for platform-specific distributions"),
26
+ (
27
+ 'build-lib=',
28
+ None,
29
+ "build directory for all distribution (defaults to either build-purelib or build-platlib",
30
+ ),
31
+ ('build-scripts=', None, "build directory for scripts"),
32
+ ('build-temp=', 't', "temporary build directory"),
33
+ (
34
+ 'plat-name=',
35
+ 'p',
36
+ f"platform name to build for, if supported [default: {get_platform()}]",
37
+ ),
38
+ ('compiler=', 'c', "specify the compiler type"),
39
+ ('parallel=', 'j', "number of parallel build jobs"),
40
+ ('debug', 'g', "compile extensions and libraries with debugging information"),
41
+ ('force', 'f', "forcibly build everything (ignore file timestamps)"),
42
+ ('executable=', 'e', "specify final destination interpreter path (build.py)"),
43
+ ]
44
+
45
+ boolean_options: ClassVar[list[str]] = ['debug', 'force']
46
+
47
+ help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
48
+ ('help-compiler', None, "list available compilers", show_compilers),
49
+ ]
50
+
51
+ def initialize_options(self):
52
+ self.build_base = 'build'
53
+ # these are decided only after 'build_base' has its final value
54
+ # (unless overridden by the user or client)
55
+ self.build_purelib = None
56
+ self.build_platlib = None
57
+ self.build_lib = None
58
+ self.build_temp = None
59
+ self.build_scripts = None
60
+ self.compiler = None
61
+ self.plat_name = None
62
+ self.debug = None
63
+ self.force = False
64
+ self.executable = None
65
+ self.parallel = None
66
+
67
+ def finalize_options(self) -> None: # noqa: C901
68
+ if self.plat_name is None:
69
+ self.plat_name = get_platform()
70
+ else:
71
+ # plat-name only supported for windows (other platforms are
72
+ # supported via ./configure flags, if at all). Avoid misleading
73
+ # other platforms.
74
+ if os.name != 'nt':
75
+ raise DistutilsOptionError(
76
+ "--plat-name only supported on Windows (try "
77
+ "using './configure --help' on your platform)"
78
+ )
79
+
80
+ plat_specifier = f".{self.plat_name}-{sys.implementation.cache_tag}"
81
+
82
+ # Python 3.13+ with --disable-gil shouldn't share build directories
83
+ if sysconfig.get_config_var('Py_GIL_DISABLED'):
84
+ plat_specifier += 't'
85
+
86
+ # Make it so Python 2.x and Python 2.x with --with-pydebug don't
87
+ # share the same build directories. Doing so confuses the build
88
+ # process for C modules
89
+ if hasattr(sys, 'gettotalrefcount'):
90
+ plat_specifier += '-pydebug'
91
+
92
+ # 'build_purelib' and 'build_platlib' just default to 'lib' and
93
+ # 'lib.<plat>' under the base build directory. We only use one of
94
+ # them for a given distribution, though --
95
+ if self.build_purelib is None:
96
+ self.build_purelib = os.path.join(self.build_base, 'lib')
97
+ if self.build_platlib is None:
98
+ self.build_platlib = os.path.join(self.build_base, 'lib' + plat_specifier)
99
+
100
+ # 'build_lib' is the actual directory that we will use for this
101
+ # particular module distribution -- if user didn't supply it, pick
102
+ # one of 'build_purelib' or 'build_platlib'.
103
+ if self.build_lib is None:
104
+ if self.distribution.has_ext_modules():
105
+ self.build_lib = self.build_platlib
106
+ else:
107
+ self.build_lib = self.build_purelib
108
+
109
+ # 'build_temp' -- temporary directory for compiler turds,
110
+ # "build/temp.<plat>"
111
+ if self.build_temp is None:
112
+ self.build_temp = os.path.join(self.build_base, 'temp' + plat_specifier)
113
+ if self.build_scripts is None:
114
+ self.build_scripts = os.path.join(
115
+ self.build_base,
116
+ f'scripts-{sys.version_info.major}.{sys.version_info.minor}',
117
+ )
118
+
119
+ if self.executable is None and sys.executable:
120
+ self.executable = os.path.normpath(sys.executable)
121
+
122
+ if isinstance(self.parallel, str):
123
+ try:
124
+ self.parallel = int(self.parallel)
125
+ except ValueError:
126
+ raise DistutilsOptionError("parallel should be an integer")
127
+
128
+ def run(self) -> None:
129
+ # Run all relevant sub-commands. This will be some subset of:
130
+ # - build_py - pure Python modules
131
+ # - build_clib - standalone C libraries
132
+ # - build_ext - Python extensions
133
+ # - build_scripts - (Python) scripts
134
+ for cmd_name in self.get_sub_commands():
135
+ self.run_command(cmd_name)
136
+
137
+ # -- Predicates for the sub-command list ---------------------------
138
+
139
+ def has_pure_modules(self):
140
+ return self.distribution.has_pure_modules()
141
+
142
+ def has_c_libraries(self):
143
+ return self.distribution.has_c_libraries()
144
+
145
+ def has_ext_modules(self):
146
+ return self.distribution.has_ext_modules()
147
+
148
+ def has_scripts(self):
149
+ return self.distribution.has_scripts()
150
+
151
+ sub_commands = [
152
+ ('build_py', has_pure_modules),
153
+ ('build_clib', has_c_libraries),
154
+ ('build_ext', has_ext_modules),
155
+ ('build_scripts', has_scripts),
156
+ ]
python/Lib/site-packages/setuptools/_distutils/command/build_clib.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build_clib
2
+
3
+ Implements the Distutils 'build_clib' command, to build a C/C++ library
4
+ that is included in the module distribution and needed by an extension
5
+ module."""
6
+
7
+ # XXX this module has *lots* of code ripped-off quite transparently from
8
+ # build_ext.py -- not surprisingly really, as the work required to build
9
+ # a static library from a collection of C source files is not really all
10
+ # that different from what's required to build a shared object file from
11
+ # a collection of C source files. Nevertheless, I haven't done the
12
+ # necessary refactoring to account for the overlap in code between the
13
+ # two modules, mainly because a number of subtle details changed in the
14
+ # cut 'n paste. Sigh.
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from collections.abc import Callable
19
+ from distutils._log import log
20
+ from typing import ClassVar
21
+
22
+ from ..ccompiler import new_compiler, show_compilers
23
+ from ..core import Command
24
+ from ..errors import DistutilsSetupError
25
+ from ..sysconfig import customize_compiler
26
+
27
+
28
+ class build_clib(Command):
29
+ description = "build C/C++ libraries used by Python extensions"
30
+
31
+ user_options: ClassVar[list[tuple[str, str, str]]] = [
32
+ ('build-clib=', 'b', "directory to build C/C++ libraries to"),
33
+ ('build-temp=', 't', "directory to put temporary build by-products"),
34
+ ('debug', 'g', "compile with debugging information"),
35
+ ('force', 'f', "forcibly build everything (ignore file timestamps)"),
36
+ ('compiler=', 'c', "specify the compiler type"),
37
+ ]
38
+
39
+ boolean_options: ClassVar[list[str]] = ['debug', 'force']
40
+
41
+ help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
42
+ ('help-compiler', None, "list available compilers", show_compilers),
43
+ ]
44
+
45
+ def initialize_options(self):
46
+ self.build_clib = None
47
+ self.build_temp = None
48
+
49
+ # List of libraries to build
50
+ self.libraries = None
51
+
52
+ # Compilation options for all libraries
53
+ self.include_dirs = None
54
+ self.define = None
55
+ self.undef = None
56
+ self.debug = None
57
+ self.force = False
58
+ self.compiler = None
59
+
60
+ def finalize_options(self) -> None:
61
+ # This might be confusing: both build-clib and build-temp default
62
+ # to build-temp as defined by the "build" command. This is because
63
+ # I think that C libraries are really just temporary build
64
+ # by-products, at least from the point of view of building Python
65
+ # extensions -- but I want to keep my options open.
66
+ self.set_undefined_options(
67
+ 'build',
68
+ ('build_temp', 'build_clib'),
69
+ ('build_temp', 'build_temp'),
70
+ ('compiler', 'compiler'),
71
+ ('debug', 'debug'),
72
+ ('force', 'force'),
73
+ )
74
+
75
+ self.libraries = self.distribution.libraries
76
+ if self.libraries:
77
+ self.check_library_list(self.libraries)
78
+
79
+ if self.include_dirs is None:
80
+ self.include_dirs = self.distribution.include_dirs or []
81
+ if isinstance(self.include_dirs, str):
82
+ self.include_dirs = self.include_dirs.split(os.pathsep)
83
+
84
+ # XXX same as for build_ext -- what about 'self.define' and
85
+ # 'self.undef' ?
86
+
87
+ def run(self) -> None:
88
+ if not self.libraries:
89
+ return
90
+
91
+ self.compiler = new_compiler(compiler=self.compiler, force=self.force)
92
+ customize_compiler(self.compiler)
93
+
94
+ if self.include_dirs is not None:
95
+ self.compiler.set_include_dirs(self.include_dirs)
96
+ if self.define is not None:
97
+ # 'define' option is a list of (name,value) tuples
98
+ for name, value in self.define:
99
+ self.compiler.define_macro(name, value)
100
+ if self.undef is not None:
101
+ for macro in self.undef:
102
+ self.compiler.undefine_macro(macro)
103
+
104
+ self.build_libraries(self.libraries)
105
+
106
+ def check_library_list(self, libraries) -> None:
107
+ """Ensure that the list of libraries is valid.
108
+
109
+ `library` is presumably provided as a command option 'libraries'.
110
+ This method checks that it is a list of 2-tuples, where the tuples
111
+ are (library_name, build_info_dict).
112
+
113
+ Raise DistutilsSetupError if the structure is invalid anywhere;
114
+ just returns otherwise.
115
+ """
116
+ if not isinstance(libraries, list):
117
+ raise DistutilsSetupError("'libraries' option must be a list of tuples")
118
+
119
+ for lib in libraries:
120
+ if not isinstance(lib, tuple) and len(lib) != 2:
121
+ raise DistutilsSetupError("each element of 'libraries' must a 2-tuple")
122
+
123
+ name, build_info = lib
124
+
125
+ if not isinstance(name, str):
126
+ raise DistutilsSetupError(
127
+ "first element of each tuple in 'libraries' "
128
+ "must be a string (the library name)"
129
+ )
130
+
131
+ if '/' in name or (os.sep != '/' and os.sep in name):
132
+ raise DistutilsSetupError(
133
+ f"bad library name '{lib[0]}': may not contain directory separators"
134
+ )
135
+
136
+ if not isinstance(build_info, dict):
137
+ raise DistutilsSetupError(
138
+ "second element of each tuple in 'libraries' "
139
+ "must be a dictionary (build info)"
140
+ )
141
+
142
+ def get_library_names(self):
143
+ # Assume the library list is valid -- 'check_library_list()' is
144
+ # called from 'finalize_options()', so it should be!
145
+ if not self.libraries:
146
+ return None
147
+
148
+ lib_names = []
149
+ for lib_name, _build_info in self.libraries:
150
+ lib_names.append(lib_name)
151
+ return lib_names
152
+
153
+ def get_source_files(self):
154
+ self.check_library_list(self.libraries)
155
+ filenames = []
156
+ for lib_name, build_info in self.libraries:
157
+ sources = build_info.get('sources')
158
+ if sources is None or not isinstance(sources, (list, tuple)):
159
+ raise DistutilsSetupError(
160
+ f"in 'libraries' option (library '{lib_name}'), "
161
+ "'sources' must be present and must be "
162
+ "a list of source filenames"
163
+ )
164
+
165
+ filenames.extend(sources)
166
+ return filenames
167
+
168
+ def build_libraries(self, libraries) -> None:
169
+ for lib_name, build_info in libraries:
170
+ sources = build_info.get('sources')
171
+ if sources is None or not isinstance(sources, (list, tuple)):
172
+ raise DistutilsSetupError(
173
+ f"in 'libraries' option (library '{lib_name}'), "
174
+ "'sources' must be present and must be "
175
+ "a list of source filenames"
176
+ )
177
+ sources = list(sources)
178
+
179
+ log.info("building '%s' library", lib_name)
180
+
181
+ # First, compile the source code to object files in the library
182
+ # directory. (This should probably change to putting object
183
+ # files in a temporary build directory.)
184
+ macros = build_info.get('macros')
185
+ include_dirs = build_info.get('include_dirs')
186
+ objects = self.compiler.compile(
187
+ sources,
188
+ output_dir=self.build_temp,
189
+ macros=macros,
190
+ include_dirs=include_dirs,
191
+ debug=self.debug,
192
+ )
193
+
194
+ # Now "link" the object files together into a static library.
195
+ # (On Unix at least, this isn't really linking -- it just
196
+ # builds an archive. Whatever.)
197
+ self.compiler.create_static_lib(
198
+ objects, lib_name, output_dir=self.build_clib, debug=self.debug
199
+ )
python/Lib/site-packages/setuptools/_distutils/command/build_ext.py ADDED
@@ -0,0 +1,811 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build_ext
2
+
3
+ Implements the Distutils 'build_ext' command, for building extension
4
+ modules (currently limited to C extensions, should accommodate C++
5
+ extensions ASAP)."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import os
11
+ import re
12
+ import sys
13
+ from collections.abc import Callable
14
+ from distutils._log import log
15
+ from site import USER_BASE
16
+ from typing import ClassVar
17
+
18
+ from .._modified import newer_group
19
+ from ..ccompiler import new_compiler, show_compilers
20
+ from ..core import Command
21
+ from ..errors import (
22
+ CCompilerError,
23
+ CompileError,
24
+ DistutilsError,
25
+ DistutilsOptionError,
26
+ DistutilsPlatformError,
27
+ DistutilsSetupError,
28
+ )
29
+ from ..extension import Extension
30
+ from ..sysconfig import customize_compiler, get_config_h_filename, get_python_version
31
+ from ..util import get_platform, is_freethreaded, is_mingw
32
+
33
+ # An extension name is just a dot-separated list of Python NAMEs (ie.
34
+ # the same as a fully-qualified module name).
35
+ extension_name_re = re.compile(r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
36
+
37
+
38
+ class build_ext(Command):
39
+ description = "build C/C++ extensions (compile/link to build directory)"
40
+
41
+ # XXX thoughts on how to deal with complex command-line options like
42
+ # these, i.e. how to make it so fancy_getopt can suck them off the
43
+ # command line and make it look like setup.py defined the appropriate
44
+ # lists of tuples of what-have-you.
45
+ # - each command needs a callback to process its command-line options
46
+ # - Command.__init__() needs access to its share of the whole
47
+ # command line (must ultimately come from
48
+ # Distribution.parse_command_line())
49
+ # - it then calls the current command class' option-parsing
50
+ # callback to deal with weird options like -D, which have to
51
+ # parse the option text and churn out some custom data
52
+ # structure
53
+ # - that data structure (in this case, a list of 2-tuples)
54
+ # will then be present in the command object by the time
55
+ # we get to finalize_options() (i.e. the constructor
56
+ # takes care of both command-line and client options
57
+ # in between initialize_options() and finalize_options())
58
+
59
+ sep_by = f" (separated by '{os.pathsep}')"
60
+ user_options = [
61
+ ('build-lib=', 'b', "directory for compiled extension modules"),
62
+ ('build-temp=', 't', "directory for temporary files (build by-products)"),
63
+ (
64
+ 'plat-name=',
65
+ 'p',
66
+ "platform name to cross-compile for, if supported "
67
+ f"[default: {get_platform()}]",
68
+ ),
69
+ (
70
+ 'inplace',
71
+ 'i',
72
+ "ignore build-lib and put compiled extensions into the source "
73
+ "directory alongside your pure Python modules",
74
+ ),
75
+ (
76
+ 'include-dirs=',
77
+ 'I',
78
+ "list of directories to search for header files" + sep_by,
79
+ ),
80
+ ('define=', 'D', "C preprocessor macros to define"),
81
+ ('undef=', 'U', "C preprocessor macros to undefine"),
82
+ ('libraries=', 'l', "external C libraries to link with"),
83
+ (
84
+ 'library-dirs=',
85
+ 'L',
86
+ "directories to search for external C libraries" + sep_by,
87
+ ),
88
+ ('rpath=', 'R', "directories to search for shared C libraries at runtime"),
89
+ ('link-objects=', 'O', "extra explicit link objects to include in the link"),
90
+ ('debug', 'g', "compile/link with debugging information"),
91
+ ('force', 'f', "forcibly build everything (ignore file timestamps)"),
92
+ ('compiler=', 'c', "specify the compiler type"),
93
+ ('parallel=', 'j', "number of parallel build jobs"),
94
+ ('swig-cpp', None, "make SWIG create C++ files (default is C)"),
95
+ ('swig-opts=', None, "list of SWIG command line options"),
96
+ ('swig=', None, "path to the SWIG executable"),
97
+ ('user', None, "add user include, library and rpath"),
98
+ ]
99
+
100
+ boolean_options: ClassVar[list[str]] = [
101
+ 'inplace',
102
+ 'debug',
103
+ 'force',
104
+ 'swig-cpp',
105
+ 'user',
106
+ ]
107
+
108
+ help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
109
+ ('help-compiler', None, "list available compilers", show_compilers),
110
+ ]
111
+
112
+ def initialize_options(self):
113
+ self.extensions = None
114
+ self.build_lib = None
115
+ self.plat_name = None
116
+ self.build_temp = None
117
+ self.inplace = False
118
+ self.package = None
119
+
120
+ self.include_dirs = None
121
+ self.define = None
122
+ self.undef = None
123
+ self.libraries = None
124
+ self.library_dirs = None
125
+ self.rpath = None
126
+ self.link_objects = None
127
+ self.debug = None
128
+ self.force = None
129
+ self.compiler = None
130
+ self.swig = None
131
+ self.swig_cpp = None
132
+ self.swig_opts = None
133
+ self.user = None
134
+ self.parallel = None
135
+
136
+ @staticmethod
137
+ def _python_lib_dir(sysconfig):
138
+ """
139
+ Resolve Python's library directory for building extensions
140
+ that rely on a shared Python library.
141
+
142
+ See python/cpython#44264 and python/cpython#48686
143
+ """
144
+ if not sysconfig.get_config_var('Py_ENABLE_SHARED'):
145
+ return
146
+
147
+ if sysconfig.python_build:
148
+ yield '.'
149
+ return
150
+
151
+ if sys.platform == 'zos':
152
+ # On z/OS, a user is not required to install Python to
153
+ # a predetermined path, but can use Python portably
154
+ installed_dir = sysconfig.get_config_var('base')
155
+ lib_dir = sysconfig.get_config_var('platlibdir')
156
+ yield os.path.join(installed_dir, lib_dir)
157
+ else:
158
+ # building third party extensions
159
+ yield sysconfig.get_config_var('LIBDIR')
160
+
161
+ def finalize_options(self) -> None: # noqa: C901
162
+ from distutils import sysconfig
163
+
164
+ self.set_undefined_options(
165
+ 'build',
166
+ ('build_lib', 'build_lib'),
167
+ ('build_temp', 'build_temp'),
168
+ ('compiler', 'compiler'),
169
+ ('debug', 'debug'),
170
+ ('force', 'force'),
171
+ ('parallel', 'parallel'),
172
+ ('plat_name', 'plat_name'),
173
+ )
174
+
175
+ if self.package is None:
176
+ self.package = self.distribution.ext_package
177
+
178
+ self.extensions = self.distribution.ext_modules
179
+
180
+ # Make sure Python's include directories (for Python.h, pyconfig.h,
181
+ # etc.) are in the include search path.
182
+ py_include = sysconfig.get_python_inc()
183
+ plat_py_include = sysconfig.get_python_inc(plat_specific=True)
184
+ if self.include_dirs is None:
185
+ self.include_dirs = self.distribution.include_dirs or []
186
+ if isinstance(self.include_dirs, str):
187
+ self.include_dirs = self.include_dirs.split(os.pathsep)
188
+
189
+ # If in a virtualenv, add its include directory
190
+ # Issue 16116
191
+ if sys.exec_prefix != sys.base_exec_prefix:
192
+ self.include_dirs.append(os.path.join(sys.exec_prefix, 'include'))
193
+
194
+ # Put the Python "system" include dir at the end, so that
195
+ # any local include dirs take precedence.
196
+ self.include_dirs.extend(py_include.split(os.path.pathsep))
197
+ if plat_py_include != py_include:
198
+ self.include_dirs.extend(plat_py_include.split(os.path.pathsep))
199
+
200
+ self.ensure_string_list('libraries')
201
+ self.ensure_string_list('link_objects')
202
+
203
+ # Life is easier if we're not forever checking for None, so
204
+ # simplify these options to empty lists if unset
205
+ if self.libraries is None:
206
+ self.libraries = []
207
+ if self.library_dirs is None:
208
+ self.library_dirs = []
209
+ elif isinstance(self.library_dirs, str):
210
+ self.library_dirs = self.library_dirs.split(os.pathsep)
211
+
212
+ if self.rpath is None:
213
+ self.rpath = []
214
+ elif isinstance(self.rpath, str):
215
+ self.rpath = self.rpath.split(os.pathsep)
216
+
217
+ # for extensions under windows use different directories
218
+ # for Release and Debug builds.
219
+ # also Python's library directory must be appended to library_dirs
220
+ if os.name == 'nt' and not is_mingw():
221
+ # the 'libs' directory is for binary installs - we assume that
222
+ # must be the *native* platform. But we don't really support
223
+ # cross-compiling via a binary install anyway, so we let it go.
224
+ self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
225
+ if sys.base_exec_prefix != sys.prefix: # Issue 16116
226
+ self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs'))
227
+ if self.debug:
228
+ self.build_temp = os.path.join(self.build_temp, "Debug")
229
+ else:
230
+ self.build_temp = os.path.join(self.build_temp, "Release")
231
+
232
+ # Append the source distribution include and library directories,
233
+ # this allows distutils on windows to work in the source tree
234
+ self.include_dirs.append(os.path.dirname(get_config_h_filename()))
235
+ self.library_dirs.append(sys.base_exec_prefix)
236
+
237
+ # Use the .lib files for the correct architecture
238
+ if self.plat_name == 'win32':
239
+ suffix = 'win32'
240
+ else:
241
+ # win-amd64
242
+ suffix = self.plat_name[4:]
243
+ new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
244
+ if suffix:
245
+ new_lib = os.path.join(new_lib, suffix)
246
+ self.library_dirs.append(new_lib)
247
+
248
+ # For extensions under Cygwin, Python's library directory must be
249
+ # appended to library_dirs
250
+ if sys.platform[:6] == 'cygwin':
251
+ if not sysconfig.python_build:
252
+ # building third party extensions
253
+ self.library_dirs.append(
254
+ os.path.join(
255
+ sys.prefix, "lib", "python" + get_python_version(), "config"
256
+ )
257
+ )
258
+ else:
259
+ # building python standard extensions
260
+ self.library_dirs.append('.')
261
+
262
+ self.library_dirs.extend(self._python_lib_dir(sysconfig))
263
+
264
+ # The argument parsing will result in self.define being a string, but
265
+ # it has to be a list of 2-tuples. All the preprocessor symbols
266
+ # specified by the 'define' option will be set to '1'. Multiple
267
+ # symbols can be separated with commas.
268
+
269
+ if self.define:
270
+ defines = self.define.split(',')
271
+ self.define = [(symbol, '1') for symbol in defines]
272
+
273
+ # The option for macros to undefine is also a string from the
274
+ # option parsing, but has to be a list. Multiple symbols can also
275
+ # be separated with commas here.
276
+ if self.undef:
277
+ self.undef = self.undef.split(',')
278
+
279
+ if self.swig_opts is None:
280
+ self.swig_opts = []
281
+ else:
282
+ self.swig_opts = self.swig_opts.split(' ')
283
+
284
+ # Finally add the user include and library directories if requested
285
+ if self.user:
286
+ user_include = os.path.join(USER_BASE, "include")
287
+ user_lib = os.path.join(USER_BASE, "lib")
288
+ if os.path.isdir(user_include):
289
+ self.include_dirs.append(user_include)
290
+ if os.path.isdir(user_lib):
291
+ self.library_dirs.append(user_lib)
292
+ self.rpath.append(user_lib)
293
+
294
+ if isinstance(self.parallel, str):
295
+ try:
296
+ self.parallel = int(self.parallel)
297
+ except ValueError:
298
+ raise DistutilsOptionError("parallel should be an integer")
299
+
300
+ def run(self) -> None: # noqa: C901
301
+ # 'self.extensions', as supplied by setup.py, is a list of
302
+ # Extension instances. See the documentation for Extension (in
303
+ # distutils.extension) for details.
304
+ #
305
+ # For backwards compatibility with Distutils 0.8.2 and earlier, we
306
+ # also allow the 'extensions' list to be a list of tuples:
307
+ # (ext_name, build_info)
308
+ # where build_info is a dictionary containing everything that
309
+ # Extension instances do except the name, with a few things being
310
+ # differently named. We convert these 2-tuples to Extension
311
+ # instances as needed.
312
+
313
+ if not self.extensions:
314
+ return
315
+
316
+ # If we were asked to build any C/C++ libraries, make sure that the
317
+ # directory where we put them is in the library search path for
318
+ # linking extensions.
319
+ if self.distribution.has_c_libraries():
320
+ build_clib = self.get_finalized_command('build_clib')
321
+ self.libraries.extend(build_clib.get_library_names() or [])
322
+ self.library_dirs.append(build_clib.build_clib)
323
+
324
+ # Setup the CCompiler object that we'll use to do all the
325
+ # compiling and linking
326
+ self.compiler = new_compiler(
327
+ compiler=self.compiler,
328
+ verbose=self.verbose,
329
+ force=self.force,
330
+ )
331
+ customize_compiler(self.compiler)
332
+ # If we are cross-compiling, init the compiler now (if we are not
333
+ # cross-compiling, init would not hurt, but people may rely on
334
+ # late initialization of compiler even if they shouldn't...)
335
+ if os.name == 'nt' and self.plat_name != get_platform():
336
+ self.compiler.initialize(self.plat_name)
337
+
338
+ # The official Windows free threaded Python installer doesn't set
339
+ # Py_GIL_DISABLED because its pyconfig.h is shared with the
340
+ # default build, so define it here (pypa/setuptools#4662).
341
+ if os.name == 'nt' and is_freethreaded():
342
+ self.compiler.define_macro('Py_GIL_DISABLED', '1')
343
+
344
+ # And make sure that any compile/link-related options (which might
345
+ # come from the command-line or from the setup script) are set in
346
+ # that CCompiler object -- that way, they automatically apply to
347
+ # all compiling and linking done here.
348
+ if self.include_dirs is not None:
349
+ self.compiler.set_include_dirs(self.include_dirs)
350
+ if self.define is not None:
351
+ # 'define' option is a list of (name,value) tuples
352
+ for name, value in self.define:
353
+ self.compiler.define_macro(name, value)
354
+ if self.undef is not None:
355
+ for macro in self.undef:
356
+ self.compiler.undefine_macro(macro)
357
+ if self.libraries is not None:
358
+ self.compiler.set_libraries(self.libraries)
359
+ if self.library_dirs is not None:
360
+ self.compiler.set_library_dirs(self.library_dirs)
361
+ if self.rpath is not None:
362
+ self.compiler.set_runtime_library_dirs(self.rpath)
363
+ if self.link_objects is not None:
364
+ self.compiler.set_link_objects(self.link_objects)
365
+
366
+ # Now actually compile and link everything.
367
+ self.build_extensions()
368
+
369
+ def check_extensions_list(self, extensions) -> None: # noqa: C901
370
+ """Ensure that the list of extensions (presumably provided as a
371
+ command option 'extensions') is valid, i.e. it is a list of
372
+ Extension objects. We also support the old-style list of 2-tuples,
373
+ where the tuples are (ext_name, build_info), which are converted to
374
+ Extension instances here.
375
+
376
+ Raise DistutilsSetupError if the structure is invalid anywhere;
377
+ just returns otherwise.
378
+ """
379
+ if not isinstance(extensions, list):
380
+ raise DistutilsSetupError(
381
+ "'ext_modules' option must be a list of Extension instances"
382
+ )
383
+
384
+ for i, ext in enumerate(extensions):
385
+ if isinstance(ext, Extension):
386
+ continue # OK! (assume type-checking done
387
+ # by Extension constructor)
388
+
389
+ if not isinstance(ext, tuple) or len(ext) != 2:
390
+ raise DistutilsSetupError(
391
+ "each element of 'ext_modules' option must be an "
392
+ "Extension instance or 2-tuple"
393
+ )
394
+
395
+ ext_name, build_info = ext
396
+
397
+ log.warning(
398
+ "old-style (ext_name, build_info) tuple found in "
399
+ "ext_modules for extension '%s' "
400
+ "-- please convert to Extension instance",
401
+ ext_name,
402
+ )
403
+
404
+ if not (isinstance(ext_name, str) and extension_name_re.match(ext_name)):
405
+ raise DistutilsSetupError(
406
+ "first element of each tuple in 'ext_modules' "
407
+ "must be the extension name (a string)"
408
+ )
409
+
410
+ if not isinstance(build_info, dict):
411
+ raise DistutilsSetupError(
412
+ "second element of each tuple in 'ext_modules' "
413
+ "must be a dictionary (build info)"
414
+ )
415
+
416
+ # OK, the (ext_name, build_info) dict is type-safe: convert it
417
+ # to an Extension instance.
418
+ ext = Extension(ext_name, build_info['sources'])
419
+
420
+ # Easy stuff: one-to-one mapping from dict elements to
421
+ # instance attributes.
422
+ for key in (
423
+ 'include_dirs',
424
+ 'library_dirs',
425
+ 'libraries',
426
+ 'extra_objects',
427
+ 'extra_compile_args',
428
+ 'extra_link_args',
429
+ ):
430
+ val = build_info.get(key)
431
+ if val is not None:
432
+ setattr(ext, key, val)
433
+
434
+ # Medium-easy stuff: same syntax/semantics, different names.
435
+ ext.runtime_library_dirs = build_info.get('rpath')
436
+ if 'def_file' in build_info:
437
+ log.warning("'def_file' element of build info dict no longer supported")
438
+
439
+ # Non-trivial stuff: 'macros' split into 'define_macros'
440
+ # and 'undef_macros'.
441
+ macros = build_info.get('macros')
442
+ if macros:
443
+ ext.define_macros = []
444
+ ext.undef_macros = []
445
+ for macro in macros:
446
+ if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
447
+ raise DistutilsSetupError(
448
+ "'macros' element of build info dict must be 1- or 2-tuple"
449
+ )
450
+ if len(macro) == 1:
451
+ ext.undef_macros.append(macro[0])
452
+ elif len(macro) == 2:
453
+ ext.define_macros.append(macro)
454
+
455
+ extensions[i] = ext
456
+
457
+ def get_source_files(self):
458
+ self.check_extensions_list(self.extensions)
459
+ filenames = []
460
+
461
+ # Wouldn't it be neat if we knew the names of header files too...
462
+ for ext in self.extensions:
463
+ filenames.extend(ext.sources)
464
+ return filenames
465
+
466
+ def get_outputs(self):
467
+ # Sanity check the 'extensions' list -- can't assume this is being
468
+ # done in the same run as a 'build_extensions()' call (in fact, we
469
+ # can probably assume that it *isn't*!).
470
+ self.check_extensions_list(self.extensions)
471
+
472
+ # And build the list of output (built) filenames. Note that this
473
+ # ignores the 'inplace' flag, and assumes everything goes in the
474
+ # "build" tree.
475
+ return [self.get_ext_fullpath(ext.name) for ext in self.extensions]
476
+
477
+ def build_extensions(self) -> None:
478
+ # First, sanity-check the 'extensions' list
479
+ self.check_extensions_list(self.extensions)
480
+ if self.parallel:
481
+ self._build_extensions_parallel()
482
+ else:
483
+ self._build_extensions_serial()
484
+
485
+ def _build_extensions_parallel(self):
486
+ workers = self.parallel
487
+ if self.parallel is True:
488
+ workers = os.cpu_count() # may return None
489
+ try:
490
+ from concurrent.futures import ThreadPoolExecutor
491
+ except ImportError:
492
+ workers = None
493
+
494
+ if workers is None:
495
+ self._build_extensions_serial()
496
+ return
497
+
498
+ with ThreadPoolExecutor(max_workers=workers) as executor:
499
+ futures = [
500
+ executor.submit(self.build_extension, ext) for ext in self.extensions
501
+ ]
502
+ for ext, fut in zip(self.extensions, futures):
503
+ with self._filter_build_errors(ext):
504
+ fut.result()
505
+
506
+ def _build_extensions_serial(self):
507
+ for ext in self.extensions:
508
+ with self._filter_build_errors(ext):
509
+ self.build_extension(ext)
510
+
511
+ @contextlib.contextmanager
512
+ def _filter_build_errors(self, ext):
513
+ try:
514
+ yield
515
+ except (CCompilerError, DistutilsError, CompileError) as e:
516
+ if not ext.optional:
517
+ raise
518
+ self.warn(f'building extension "{ext.name}" failed: {e}')
519
+
520
+ def build_extension(self, ext) -> None:
521
+ sources = ext.sources
522
+ if sources is None or not isinstance(sources, (list, tuple)):
523
+ raise DistutilsSetupError(
524
+ f"in 'ext_modules' option (extension '{ext.name}'), "
525
+ "'sources' must be present and must be "
526
+ "a list of source filenames"
527
+ )
528
+ # sort to make the resulting .so file build reproducible
529
+ sources = sorted(sources)
530
+
531
+ ext_path = self.get_ext_fullpath(ext.name)
532
+ depends = sources + ext.depends
533
+ if not (self.force or newer_group(depends, ext_path, 'newer')):
534
+ log.debug("skipping '%s' extension (up-to-date)", ext.name)
535
+ return
536
+ else:
537
+ log.info("building '%s' extension", ext.name)
538
+
539
+ # First, scan the sources for SWIG definition files (.i), run
540
+ # SWIG on 'em to create .c files, and modify the sources list
541
+ # accordingly.
542
+ sources = self.swig_sources(sources, ext)
543
+
544
+ # Next, compile the source code to object files.
545
+
546
+ # XXX not honouring 'define_macros' or 'undef_macros' -- the
547
+ # CCompiler API needs to change to accommodate this, and I
548
+ # want to do one thing at a time!
549
+
550
+ # Two possible sources for extra compiler arguments:
551
+ # - 'extra_compile_args' in Extension object
552
+ # - CFLAGS environment variable (not particularly
553
+ # elegant, but people seem to expect it and I
554
+ # guess it's useful)
555
+ # The environment variable should take precedence, and
556
+ # any sensible compiler will give precedence to later
557
+ # command line args. Hence we combine them in order:
558
+ extra_args = ext.extra_compile_args or []
559
+
560
+ macros = ext.define_macros[:]
561
+ for undef in ext.undef_macros:
562
+ macros.append((undef,))
563
+
564
+ objects = self.compiler.compile(
565
+ sources,
566
+ output_dir=self.build_temp,
567
+ macros=macros,
568
+ include_dirs=ext.include_dirs,
569
+ debug=self.debug,
570
+ extra_postargs=extra_args,
571
+ depends=ext.depends,
572
+ )
573
+
574
+ # XXX outdated variable, kept here in case third-part code
575
+ # needs it.
576
+ self._built_objects = objects[:]
577
+
578
+ # Now link the object files together into a "shared object" --
579
+ # of course, first we have to figure out all the other things
580
+ # that go into the mix.
581
+ if ext.extra_objects:
582
+ objects.extend(ext.extra_objects)
583
+ extra_args = ext.extra_link_args or []
584
+
585
+ # Detect target language, if not provided
586
+ language = ext.language or self.compiler.detect_language(sources)
587
+
588
+ self.compiler.link_shared_object(
589
+ objects,
590
+ ext_path,
591
+ libraries=self.get_libraries(ext),
592
+ library_dirs=ext.library_dirs,
593
+ runtime_library_dirs=ext.runtime_library_dirs,
594
+ extra_postargs=extra_args,
595
+ export_symbols=self.get_export_symbols(ext),
596
+ debug=self.debug,
597
+ build_temp=self.build_temp,
598
+ target_lang=language,
599
+ )
600
+
601
+ def swig_sources(self, sources, extension):
602
+ """Walk the list of source files in 'sources', looking for SWIG
603
+ interface (.i) files. Run SWIG on all that are found, and
604
+ return a modified 'sources' list with SWIG source files replaced
605
+ by the generated C (or C++) files.
606
+ """
607
+ new_sources = []
608
+ swig_sources = []
609
+ swig_targets = {}
610
+
611
+ # XXX this drops generated C/C++ files into the source tree, which
612
+ # is fine for developers who want to distribute the generated
613
+ # source -- but there should be an option to put SWIG output in
614
+ # the temp dir.
615
+
616
+ if self.swig_cpp:
617
+ log.warning("--swig-cpp is deprecated - use --swig-opts=-c++")
618
+
619
+ if (
620
+ self.swig_cpp
621
+ or ('-c++' in self.swig_opts)
622
+ or ('-c++' in extension.swig_opts)
623
+ ):
624
+ target_ext = '.cpp'
625
+ else:
626
+ target_ext = '.c'
627
+
628
+ for source in sources:
629
+ (base, ext) = os.path.splitext(source)
630
+ if ext == ".i": # SWIG interface file
631
+ new_sources.append(base + '_wrap' + target_ext)
632
+ swig_sources.append(source)
633
+ swig_targets[source] = new_sources[-1]
634
+ else:
635
+ new_sources.append(source)
636
+
637
+ if not swig_sources:
638
+ return new_sources
639
+
640
+ swig = self.swig or self.find_swig()
641
+ swig_cmd = [swig, "-python"]
642
+ swig_cmd.extend(self.swig_opts)
643
+ if self.swig_cpp:
644
+ swig_cmd.append("-c++")
645
+
646
+ # Do not override commandline arguments
647
+ if not self.swig_opts:
648
+ swig_cmd.extend(extension.swig_opts)
649
+
650
+ for source in swig_sources:
651
+ target = swig_targets[source]
652
+ log.info("swigging %s to %s", source, target)
653
+ self.spawn(swig_cmd + ["-o", target, source])
654
+
655
+ return new_sources
656
+
657
+ def find_swig(self):
658
+ """Return the name of the SWIG executable. On Unix, this is
659
+ just "swig" -- it should be in the PATH. Tries a bit harder on
660
+ Windows.
661
+ """
662
+ if os.name == "posix":
663
+ return "swig"
664
+ elif os.name == "nt":
665
+ # Look for SWIG in its standard installation directory on
666
+ # Windows (or so I presume!). If we find it there, great;
667
+ # if not, act like Unix and assume it's in the PATH.
668
+ for vers in ("1.3", "1.2", "1.1"):
669
+ fn = os.path.join(f"c:\\swig{vers}", "swig.exe")
670
+ if os.path.isfile(fn):
671
+ return fn
672
+ else:
673
+ return "swig.exe"
674
+ else:
675
+ raise DistutilsPlatformError(
676
+ f"I don't know how to find (much less run) SWIG on platform '{os.name}'"
677
+ )
678
+
679
+ # -- Name generators -----------------------------------------------
680
+ # (extension names, filenames, whatever)
681
+ def get_ext_fullpath(self, ext_name: str) -> str:
682
+ """Returns the path of the filename for a given extension.
683
+
684
+ The file is located in `build_lib` or directly in the package
685
+ (inplace option).
686
+ """
687
+ fullname = self.get_ext_fullname(ext_name)
688
+ modpath = fullname.split('.')
689
+ filename = self.get_ext_filename(modpath[-1])
690
+
691
+ if not self.inplace:
692
+ # no further work needed
693
+ # returning :
694
+ # build_dir/package/path/filename
695
+ filename = os.path.join(*modpath[:-1] + [filename])
696
+ return os.path.join(self.build_lib, filename)
697
+
698
+ # the inplace option requires to find the package directory
699
+ # using the build_py command for that
700
+ package = '.'.join(modpath[0:-1])
701
+ build_py = self.get_finalized_command('build_py')
702
+ package_dir = os.path.abspath(build_py.get_package_dir(package))
703
+
704
+ # returning
705
+ # package_dir/filename
706
+ return os.path.join(package_dir, filename)
707
+
708
+ def get_ext_fullname(self, ext_name: str) -> str:
709
+ """Returns the fullname of a given extension name.
710
+
711
+ Adds the `package.` prefix"""
712
+ if self.package is None:
713
+ return ext_name
714
+ else:
715
+ return self.package + '.' + ext_name
716
+
717
+ def get_ext_filename(self, ext_name: str) -> str:
718
+ r"""Convert the name of an extension (eg. "foo.bar") into the name
719
+ of the file from which it will be loaded (eg. "foo/bar.so", or
720
+ "foo\bar.pyd").
721
+ """
722
+ from ..sysconfig import get_config_var
723
+
724
+ ext_path = ext_name.split('.')
725
+ ext_suffix = get_config_var('EXT_SUFFIX')
726
+ return os.path.join(*ext_path) + ext_suffix
727
+
728
+ def get_export_symbols(self, ext: Extension) -> list[str]:
729
+ """Return the list of symbols that a shared extension has to
730
+ export. This either uses 'ext.export_symbols' or, if it's not
731
+ provided, "PyInit_" + module_name. Only relevant on Windows, where
732
+ the .pyd file (DLL) must export the module "PyInit_" function.
733
+ """
734
+ name = self._get_module_name_for_symbol(ext)
735
+ try:
736
+ # Unicode module name support as defined in PEP-489
737
+ # https://peps.python.org/pep-0489/#export-hook-name
738
+ name.encode('ascii')
739
+ except UnicodeEncodeError:
740
+ suffix = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii')
741
+ else:
742
+ suffix = "_" + name
743
+
744
+ initfunc_name = "PyInit" + suffix
745
+ if initfunc_name not in ext.export_symbols:
746
+ ext.export_symbols.append(initfunc_name)
747
+ return ext.export_symbols
748
+
749
+ def _get_module_name_for_symbol(self, ext):
750
+ # Package name should be used for `__init__` modules
751
+ # https://github.com/python/cpython/issues/80074
752
+ # https://github.com/pypa/setuptools/issues/4826
753
+ parts = ext.name.split(".")
754
+ if parts[-1] == "__init__" and len(parts) >= 2:
755
+ return parts[-2]
756
+ return parts[-1]
757
+
758
+ def get_libraries(self, ext: Extension) -> list[str]: # noqa: C901
759
+ """Return the list of libraries to link against when building a
760
+ shared extension. On most platforms, this is just 'ext.libraries';
761
+ on Windows, we add the Python library (eg. python20.dll).
762
+ """
763
+ # The python library is always needed on Windows. For MSVC, this
764
+ # is redundant, since the library is mentioned in a pragma in
765
+ # pyconfig.h that MSVC groks. The other Windows compilers all seem
766
+ # to need it mentioned explicitly, though, so that's what we do.
767
+ # Append '_d' to the python import library on debug builds.
768
+ if sys.platform == "win32" and not is_mingw():
769
+ from .._msvccompiler import MSVCCompiler
770
+
771
+ if not isinstance(self.compiler, MSVCCompiler):
772
+ template = "python%d%d"
773
+ if self.debug:
774
+ template = template + '_d'
775
+ pythonlib = template % (
776
+ sys.hexversion >> 24,
777
+ (sys.hexversion >> 16) & 0xFF,
778
+ )
779
+ # don't extend ext.libraries, it may be shared with other
780
+ # extensions, it is a reference to the original list
781
+ return ext.libraries + [pythonlib]
782
+ else:
783
+ # On Android only the main executable and LD_PRELOADs are considered
784
+ # to be RTLD_GLOBAL, all the dependencies of the main executable
785
+ # remain RTLD_LOCAL and so the shared libraries must be linked with
786
+ # libpython when python is built with a shared python library (issue
787
+ # bpo-21536).
788
+ # On Cygwin (and if required, other POSIX-like platforms based on
789
+ # Windows like MinGW) it is simply necessary that all symbols in
790
+ # shared libraries are resolved at link time.
791
+ from ..sysconfig import get_config_var
792
+
793
+ link_libpython = False
794
+ if get_config_var('Py_ENABLE_SHARED'):
795
+ # A native build on an Android device or on Cygwin
796
+ if hasattr(sys, 'getandroidapilevel'):
797
+ link_libpython = True
798
+ elif sys.platform == 'cygwin' or is_mingw():
799
+ link_libpython = True
800
+ elif '_PYTHON_HOST_PLATFORM' in os.environ:
801
+ # We are cross-compiling for one of the relevant platforms
802
+ if get_config_var('ANDROID_API_LEVEL') != 0:
803
+ link_libpython = True
804
+ elif get_config_var('MACHDEP') == 'cygwin':
805
+ link_libpython = True
806
+
807
+ if link_libpython:
808
+ ldversion = get_config_var('LDVERSION')
809
+ return ext.libraries + ['python' + ldversion]
810
+
811
+ return ext.libraries
python/Lib/site-packages/setuptools/_distutils/command/build_py.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build_py
2
+
3
+ Implements the Distutils 'build_py' command."""
4
+
5
+ import glob
6
+ import importlib.util
7
+ import os
8
+ import sys
9
+ from distutils._log import log
10
+ from typing import ClassVar
11
+
12
+ from ..core import Command
13
+ from ..errors import DistutilsFileError, DistutilsOptionError
14
+ from ..util import convert_path
15
+
16
+
17
+ class build_py(Command):
18
+ description = "\"build\" pure Python modules (copy to build directory)"
19
+
20
+ user_options = [
21
+ ('build-lib=', 'd', "directory to \"build\" (copy) to"),
22
+ ('compile', 'c', "compile .py to .pyc"),
23
+ ('no-compile', None, "don't compile .py files [default]"),
24
+ (
25
+ 'optimize=',
26
+ 'O',
27
+ "also compile with optimization: -O1 for \"python -O\", "
28
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
29
+ ),
30
+ ('force', 'f', "forcibly build everything (ignore file timestamps)"),
31
+ ]
32
+
33
+ boolean_options: ClassVar[list[str]] = ['compile', 'force']
34
+ negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
35
+
36
+ def initialize_options(self):
37
+ self.build_lib = None
38
+ self.py_modules = None
39
+ self.package = None
40
+ self.package_data = None
41
+ self.package_dir = None
42
+ self.compile = False
43
+ self.optimize = 0
44
+ self.force = None
45
+
46
+ def finalize_options(self) -> None:
47
+ self.set_undefined_options(
48
+ 'build', ('build_lib', 'build_lib'), ('force', 'force')
49
+ )
50
+
51
+ # Get the distribution options that are aliases for build_py
52
+ # options -- list of packages and list of modules.
53
+ self.packages = self.distribution.packages
54
+ self.py_modules = self.distribution.py_modules
55
+ self.package_data = self.distribution.package_data
56
+ self.package_dir = {}
57
+ if self.distribution.package_dir:
58
+ for name, path in self.distribution.package_dir.items():
59
+ self.package_dir[name] = convert_path(path)
60
+ self.data_files = self.get_data_files()
61
+
62
+ # Ick, copied straight from install_lib.py (fancy_getopt needs a
63
+ # type system! Hell, *everything* needs a type system!!!)
64
+ if not isinstance(self.optimize, int):
65
+ try:
66
+ self.optimize = int(self.optimize)
67
+ assert 0 <= self.optimize <= 2
68
+ except (ValueError, AssertionError):
69
+ raise DistutilsOptionError("optimize must be 0, 1, or 2")
70
+
71
+ def run(self) -> None:
72
+ # XXX copy_file by default preserves atime and mtime. IMHO this is
73
+ # the right thing to do, but perhaps it should be an option -- in
74
+ # particular, a site administrator might want installed files to
75
+ # reflect the time of installation rather than the last
76
+ # modification time before the installed release.
77
+
78
+ # XXX copy_file by default preserves mode, which appears to be the
79
+ # wrong thing to do: if a file is read-only in the working
80
+ # directory, we want it to be installed read/write so that the next
81
+ # installation of the same module distribution can overwrite it
82
+ # without problems. (This might be a Unix-specific issue.) Thus
83
+ # we turn off 'preserve_mode' when copying to the build directory,
84
+ # since the build directory is supposed to be exactly what the
85
+ # installation will look like (ie. we preserve mode when
86
+ # installing).
87
+
88
+ # Two options control which modules will be installed: 'packages'
89
+ # and 'py_modules'. The former lets us work with whole packages, not
90
+ # specifying individual modules at all; the latter is for
91
+ # specifying modules one-at-a-time.
92
+
93
+ if self.py_modules:
94
+ self.build_modules()
95
+ if self.packages:
96
+ self.build_packages()
97
+ self.build_package_data()
98
+
99
+ self.byte_compile(self.get_outputs(include_bytecode=False))
100
+
101
+ def get_data_files(self):
102
+ """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
103
+ data = []
104
+ if not self.packages:
105
+ return data
106
+ for package in self.packages:
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
+ # Length of path to strip from found files
114
+ plen = 0
115
+ if src_dir:
116
+ plen = len(src_dir) + 1
117
+
118
+ # Strip directory from globbed filenames
119
+ filenames = [file[plen:] for file in self.find_data_files(package, src_dir)]
120
+ data.append((package, src_dir, build_dir, filenames))
121
+ return data
122
+
123
+ def find_data_files(self, package, src_dir):
124
+ """Return filenames for package's data files in 'src_dir'"""
125
+ globs = self.package_data.get('', []) + self.package_data.get(package, [])
126
+ files = []
127
+ for pattern in globs:
128
+ # Each pattern has to be converted to a platform-specific path
129
+ filelist = glob.glob(
130
+ os.path.join(glob.escape(src_dir), convert_path(pattern))
131
+ )
132
+ # Files that match more than one pattern are only added once
133
+ files.extend([
134
+ fn for fn in filelist if fn not in files and os.path.isfile(fn)
135
+ ])
136
+ return files
137
+
138
+ def build_package_data(self) -> None:
139
+ """Copy data files into build directory"""
140
+ for _package, src_dir, build_dir, filenames in self.data_files:
141
+ for filename in filenames:
142
+ target = os.path.join(build_dir, filename)
143
+ self.mkpath(os.path.dirname(target))
144
+ self.copy_file(
145
+ os.path.join(src_dir, filename), target, preserve_mode=False
146
+ )
147
+
148
+ def get_package_dir(self, package):
149
+ """Return the directory, relative to the top of the source
150
+ distribution, where package 'package' should be found
151
+ (at least according to the 'package_dir' option, if any)."""
152
+ path = package.split('.')
153
+
154
+ if not self.package_dir:
155
+ if path:
156
+ return os.path.join(*path)
157
+ else:
158
+ return ''
159
+ else:
160
+ tail = []
161
+ while path:
162
+ try:
163
+ pdir = self.package_dir['.'.join(path)]
164
+ except KeyError:
165
+ tail.insert(0, path[-1])
166
+ del path[-1]
167
+ else:
168
+ tail.insert(0, pdir)
169
+ return os.path.join(*tail)
170
+ else:
171
+ # Oops, got all the way through 'path' without finding a
172
+ # match in package_dir. If package_dir defines a directory
173
+ # for the root (nameless) package, then fallback on it;
174
+ # otherwise, we might as well have not consulted
175
+ # package_dir at all, as we just use the directory implied
176
+ # by 'tail' (which should be the same as the original value
177
+ # of 'path' at this point).
178
+ pdir = self.package_dir.get('')
179
+ if pdir is not None:
180
+ tail.insert(0, pdir)
181
+
182
+ if tail:
183
+ return os.path.join(*tail)
184
+ else:
185
+ return ''
186
+
187
+ def check_package(self, package, package_dir):
188
+ # Empty dir name means current directory, which we can probably
189
+ # assume exists. Also, os.path.exists and isdir don't know about
190
+ # my "empty string means current dir" convention, so we have to
191
+ # circumvent them.
192
+ if package_dir != "":
193
+ if not os.path.exists(package_dir):
194
+ raise DistutilsFileError(
195
+ f"package directory '{package_dir}' does not exist"
196
+ )
197
+ if not os.path.isdir(package_dir):
198
+ raise DistutilsFileError(
199
+ f"supposed package directory '{package_dir}' exists, "
200
+ "but is not a directory"
201
+ )
202
+
203
+ # Directories without __init__.py are namespace packages (PEP 420).
204
+ if package:
205
+ init_py = os.path.join(package_dir, "__init__.py")
206
+ if os.path.isfile(init_py):
207
+ return init_py
208
+
209
+ # Either not in a package at all (__init__.py not expected), or
210
+ # __init__.py doesn't exist -- so don't return the filename.
211
+ return None
212
+
213
+ def check_module(self, module, module_file):
214
+ if not os.path.isfile(module_file):
215
+ log.warning("file %s (for module %s) not found", module_file, module)
216
+ return False
217
+ else:
218
+ return True
219
+
220
+ def find_package_modules(self, package, package_dir):
221
+ self.check_package(package, package_dir)
222
+ module_files = glob.glob(os.path.join(glob.escape(package_dir), "*.py"))
223
+ modules = []
224
+ setup_script = os.path.abspath(self.distribution.script_name)
225
+
226
+ for f in module_files:
227
+ abs_f = os.path.abspath(f)
228
+ if abs_f != setup_script:
229
+ module = os.path.splitext(os.path.basename(f))[0]
230
+ modules.append((package, module, f))
231
+ else:
232
+ self.debug_print(f"excluding {setup_script}")
233
+ return modules
234
+
235
+ def find_modules(self):
236
+ """Finds individually-specified Python modules, ie. those listed by
237
+ module name in 'self.py_modules'. Returns a list of tuples (package,
238
+ module_base, filename): 'package' is a tuple of the path through
239
+ package-space to the module; 'module_base' is the bare (no
240
+ packages, no dots) module name, and 'filename' is the path to the
241
+ ".py" file (relative to the distribution root) that implements the
242
+ module.
243
+ """
244
+ # Map package names to tuples of useful info about the package:
245
+ # (package_dir, checked)
246
+ # package_dir - the directory where we'll find source files for
247
+ # this package
248
+ # checked - true if we have checked that the package directory
249
+ # is valid (exists, contains __init__.py, ... ?)
250
+ packages = {}
251
+
252
+ # List of (package, module, filename) tuples to return
253
+ modules = []
254
+
255
+ # We treat modules-in-packages almost the same as toplevel modules,
256
+ # just the "package" for a toplevel is empty (either an empty
257
+ # string or empty list, depending on context). Differences:
258
+ # - don't check for __init__.py in directory for empty package
259
+ for module in self.py_modules:
260
+ path = module.split('.')
261
+ package = '.'.join(path[0:-1])
262
+ module_base = path[-1]
263
+
264
+ try:
265
+ (package_dir, checked) = packages[package]
266
+ except KeyError:
267
+ package_dir = self.get_package_dir(package)
268
+ checked = False
269
+
270
+ if not checked:
271
+ init_py = self.check_package(package, package_dir)
272
+ packages[package] = (package_dir, 1)
273
+ if init_py:
274
+ modules.append((package, "__init__", init_py))
275
+
276
+ # XXX perhaps we should also check for just .pyc files
277
+ # (so greedy closed-source bastards can distribute Python
278
+ # modules too)
279
+ module_file = os.path.join(package_dir, module_base + ".py")
280
+ if not self.check_module(module, module_file):
281
+ continue
282
+
283
+ modules.append((package, module_base, module_file))
284
+
285
+ return modules
286
+
287
+ def find_all_modules(self):
288
+ """Compute the list of all modules that will be built, whether
289
+ they are specified one-module-at-a-time ('self.py_modules') or
290
+ by whole packages ('self.packages'). Return a list of tuples
291
+ (package, module, module_file), just like 'find_modules()' and
292
+ 'find_package_modules()' do."""
293
+ modules = []
294
+ if self.py_modules:
295
+ modules.extend(self.find_modules())
296
+ if self.packages:
297
+ for package in self.packages:
298
+ package_dir = self.get_package_dir(package)
299
+ m = self.find_package_modules(package, package_dir)
300
+ modules.extend(m)
301
+ return modules
302
+
303
+ def get_source_files(self):
304
+ return [module[-1] for module in self.find_all_modules()]
305
+
306
+ def get_module_outfile(self, build_dir, package, module):
307
+ outfile_path = [build_dir] + list(package) + [module + ".py"]
308
+ return os.path.join(*outfile_path)
309
+
310
+ def get_outputs(self, include_bytecode: bool = True) -> list[str]:
311
+ modules = self.find_all_modules()
312
+ outputs = []
313
+ for package, module, _module_file in modules:
314
+ package = package.split('.')
315
+ filename = self.get_module_outfile(self.build_lib, package, module)
316
+ outputs.append(filename)
317
+ if include_bytecode:
318
+ if self.compile:
319
+ outputs.append(
320
+ importlib.util.cache_from_source(filename, optimization='')
321
+ )
322
+ if self.optimize > 0:
323
+ outputs.append(
324
+ importlib.util.cache_from_source(
325
+ filename, optimization=self.optimize
326
+ )
327
+ )
328
+
329
+ outputs += [
330
+ os.path.join(build_dir, filename)
331
+ for package, src_dir, build_dir, filenames in self.data_files
332
+ for filename in filenames
333
+ ]
334
+
335
+ return outputs
336
+
337
+ def build_module(self, module, module_file, package):
338
+ if isinstance(package, str):
339
+ package = package.split('.')
340
+ elif not isinstance(package, (list, tuple)):
341
+ raise TypeError(
342
+ "'package' must be a string (dot-separated), list, or tuple"
343
+ )
344
+
345
+ # Now put the module source file into the "build" area -- this is
346
+ # easy, we just copy it somewhere under self.build_lib (the build
347
+ # directory for Python source).
348
+ outfile = self.get_module_outfile(self.build_lib, package, module)
349
+ dir = os.path.dirname(outfile)
350
+ self.mkpath(dir)
351
+ return self.copy_file(module_file, outfile, preserve_mode=False)
352
+
353
+ def build_modules(self) -> None:
354
+ modules = self.find_modules()
355
+ for package, module, module_file in modules:
356
+ # Now "build" the module -- ie. copy the source file to
357
+ # self.build_lib (the build directory for Python source).
358
+ # (Actually, it gets copied to the directory for this package
359
+ # under self.build_lib.)
360
+ self.build_module(module, module_file, package)
361
+
362
+ def build_packages(self) -> None:
363
+ for package in self.packages:
364
+ # Get list of (package, module, module_file) tuples based on
365
+ # scanning the package directory. 'package' is only included
366
+ # in the tuple so that 'find_modules()' and
367
+ # 'find_package_tuples()' have a consistent interface; it's
368
+ # ignored here (apart from a sanity check). Also, 'module' is
369
+ # the *unqualified* module name (ie. no dots, no package -- we
370
+ # already know its package!), and 'module_file' is the path to
371
+ # the .py file, relative to the current directory
372
+ # (ie. including 'package_dir').
373
+ package_dir = self.get_package_dir(package)
374
+ modules = self.find_package_modules(package, package_dir)
375
+
376
+ # Now loop over the modules we found, "building" each one (just
377
+ # copy it to self.build_lib).
378
+ for package_, module, module_file in modules:
379
+ assert package == package_
380
+ self.build_module(module, module_file, package)
381
+
382
+ def byte_compile(self, files) -> None:
383
+ if sys.dont_write_bytecode:
384
+ self.warn('byte-compiling is disabled, skipping.')
385
+ return
386
+
387
+ from ..util import byte_compile
388
+
389
+ prefix = self.build_lib
390
+ if prefix[-1] != os.sep:
391
+ prefix = prefix + os.sep
392
+
393
+ # XXX this code is essentially the same as the 'byte_compile()
394
+ # method of the "install_lib" command, except for the determination
395
+ # of the 'prefix' string. Hmmm.
396
+ if self.compile:
397
+ byte_compile(files, optimize=0, force=self.force, prefix=prefix)
398
+ if self.optimize > 0:
399
+ byte_compile(
400
+ files,
401
+ optimize=self.optimize,
402
+ force=self.force,
403
+ prefix=prefix,
404
+ )
python/Lib/site-packages/setuptools/_distutils/command/build_scripts.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build_scripts
2
+
3
+ Implements the Distutils 'build_scripts' command."""
4
+
5
+ import os
6
+ import re
7
+ import tokenize
8
+ from distutils._log import log
9
+ from stat import ST_MODE
10
+ from typing import ClassVar
11
+
12
+ from .._modified import newer
13
+ from ..core import Command
14
+ from ..util import convert_path
15
+
16
+ shebang_pattern = re.compile('^#!.*python[0-9.]*([ \t].*)?$')
17
+ """
18
+ Pattern matching a Python interpreter indicated in first line of a script.
19
+ """
20
+
21
+ # for Setuptools compatibility
22
+ first_line_re = shebang_pattern
23
+
24
+
25
+ class build_scripts(Command):
26
+ description = "\"build\" scripts (copy and fixup #! line)"
27
+
28
+ user_options: ClassVar[list[tuple[str, str, str]]] = [
29
+ ('build-dir=', 'd', "directory to \"build\" (copy) to"),
30
+ ('force', 'f', "forcibly build everything (ignore file timestamps"),
31
+ ('executable=', 'e', "specify final destination interpreter path"),
32
+ ]
33
+
34
+ boolean_options: ClassVar[list[str]] = ['force']
35
+
36
+ def initialize_options(self):
37
+ self.build_dir = None
38
+ self.scripts = None
39
+ self.force = None
40
+ self.executable = None
41
+
42
+ def finalize_options(self):
43
+ self.set_undefined_options(
44
+ 'build',
45
+ ('build_scripts', 'build_dir'),
46
+ ('force', 'force'),
47
+ ('executable', 'executable'),
48
+ )
49
+ self.scripts = self.distribution.scripts
50
+
51
+ def get_source_files(self):
52
+ return self.scripts
53
+
54
+ def run(self):
55
+ if not self.scripts:
56
+ return
57
+ self.copy_scripts()
58
+
59
+ def copy_scripts(self):
60
+ """
61
+ Copy each script listed in ``self.scripts``.
62
+
63
+ If a script is marked as a Python script (first line matches
64
+ 'shebang_pattern', i.e. starts with ``#!`` and contains
65
+ "python"), then adjust in the copy the first line to refer to
66
+ the current Python interpreter.
67
+ """
68
+ self.mkpath(self.build_dir)
69
+ outfiles = []
70
+ updated_files = []
71
+ for script in self.scripts:
72
+ self._copy_script(script, outfiles, updated_files)
73
+
74
+ self._change_modes(outfiles)
75
+
76
+ return outfiles, updated_files
77
+
78
+ def _copy_script(self, script, outfiles, updated_files):
79
+ shebang_match = None
80
+ script = convert_path(script)
81
+ outfile = os.path.join(self.build_dir, os.path.basename(script))
82
+ outfiles.append(outfile)
83
+
84
+ if not self.force and not newer(script, outfile):
85
+ log.debug("not copying %s (up-to-date)", script)
86
+ return
87
+
88
+ # Always open the file, but ignore failures in dry-run mode
89
+ # in order to attempt to copy directly.
90
+ f = tokenize.open(script)
91
+
92
+ first_line = f.readline()
93
+ if not first_line:
94
+ self.warn(f"{script} is an empty file (skipping)")
95
+ return
96
+
97
+ shebang_match = shebang_pattern.match(first_line)
98
+
99
+ updated_files.append(outfile)
100
+ if shebang_match:
101
+ log.info("copying and adjusting %s -> %s", script, self.build_dir)
102
+ post_interp = shebang_match.group(1) or ''
103
+ shebang = "#!" + self.executable + post_interp + "\n"
104
+ self._validate_shebang(shebang, f.encoding)
105
+ with open(outfile, "w", encoding=f.encoding) as outf:
106
+ outf.write(shebang)
107
+ outf.writelines(f.readlines())
108
+ if f:
109
+ f.close()
110
+ else:
111
+ if f:
112
+ f.close()
113
+ self.copy_file(script, outfile)
114
+
115
+ def _change_modes(self, outfiles):
116
+ if os.name != 'posix':
117
+ return
118
+
119
+ for file in outfiles:
120
+ self._change_mode(file)
121
+
122
+ def _change_mode(self, file):
123
+ oldmode = os.stat(file)[ST_MODE] & 0o7777
124
+ newmode = (oldmode | 0o555) & 0o7777
125
+ if newmode != oldmode:
126
+ log.info("changing mode of %s from %o to %o", file, oldmode, newmode)
127
+ os.chmod(file, newmode)
128
+
129
+ @staticmethod
130
+ def _validate_shebang(shebang, encoding):
131
+ # Python parser starts to read a script using UTF-8 until
132
+ # it gets a #coding:xxx cookie. The shebang has to be the
133
+ # first line of a file, the #coding:xxx cookie cannot be
134
+ # written before. So the shebang has to be encodable to
135
+ # UTF-8.
136
+ try:
137
+ shebang.encode('utf-8')
138
+ except UnicodeEncodeError:
139
+ raise ValueError(f"The shebang ({shebang!r}) is not encodable to utf-8")
140
+
141
+ # If the script is encoded to a custom encoding (use a
142
+ # #coding:xxx cookie), the shebang has to be encodable to
143
+ # the script encoding too.
144
+ try:
145
+ shebang.encode(encoding)
146
+ except UnicodeEncodeError:
147
+ raise ValueError(
148
+ f"The shebang ({shebang!r}) is not encodable "
149
+ f"to the script encoding ({encoding})"
150
+ )
python/Lib/site-packages/setuptools/_distutils/command/check.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.check
2
+
3
+ Implements the Distutils 'check' command.
4
+ """
5
+
6
+ import contextlib
7
+ from typing import ClassVar
8
+
9
+ from ..core import Command
10
+ from ..errors import DistutilsSetupError
11
+
12
+ with contextlib.suppress(ImportError):
13
+ import docutils.frontend
14
+ import docutils.nodes
15
+ import docutils.parsers.rst
16
+ import docutils.utils
17
+
18
+ class SilentReporter(docutils.utils.Reporter):
19
+ def __init__(
20
+ self,
21
+ source,
22
+ report_level,
23
+ halt_level,
24
+ stream=None,
25
+ debug=False,
26
+ encoding='ascii',
27
+ error_handler='replace',
28
+ ):
29
+ self.messages = []
30
+ super().__init__(
31
+ source, report_level, halt_level, stream, debug, encoding, error_handler
32
+ )
33
+
34
+ def system_message(self, level, message, *children, **kwargs):
35
+ self.messages.append((level, message, children, kwargs))
36
+ return docutils.nodes.system_message(
37
+ message, *children, level=level, type=self.levels[level], **kwargs
38
+ )
39
+
40
+
41
+ class check(Command):
42
+ """This command checks the meta-data of the package."""
43
+
44
+ description = "perform some checks on the package"
45
+ user_options: ClassVar[list[tuple[str, str, str]]] = [
46
+ ('metadata', 'm', 'Verify meta-data'),
47
+ (
48
+ 'restructuredtext',
49
+ 'r',
50
+ 'Checks if long string meta-data syntax are reStructuredText-compliant',
51
+ ),
52
+ ('strict', 's', 'Will exit with an error if a check fails'),
53
+ ]
54
+
55
+ boolean_options: ClassVar[list[str]] = ['metadata', 'restructuredtext', 'strict']
56
+
57
+ def initialize_options(self):
58
+ """Sets default values for options."""
59
+ self.restructuredtext = False
60
+ self.metadata = 1
61
+ self.strict = False
62
+ self._warnings = 0
63
+
64
+ def finalize_options(self):
65
+ pass
66
+
67
+ def warn(self, msg):
68
+ """Counts the number of warnings that occurs."""
69
+ self._warnings += 1
70
+ return Command.warn(self, msg)
71
+
72
+ def run(self):
73
+ """Runs the command."""
74
+ # perform the various tests
75
+ if self.metadata:
76
+ self.check_metadata()
77
+ if self.restructuredtext:
78
+ if 'docutils' in globals():
79
+ try:
80
+ self.check_restructuredtext()
81
+ except TypeError as exc:
82
+ raise DistutilsSetupError(str(exc))
83
+ elif self.strict:
84
+ raise DistutilsSetupError('The docutils package is needed.')
85
+
86
+ # let's raise an error in strict mode, if we have at least
87
+ # one warning
88
+ if self.strict and self._warnings > 0:
89
+ raise DistutilsSetupError('Please correct your package.')
90
+
91
+ def check_metadata(self):
92
+ """Ensures that all required elements of meta-data are supplied.
93
+
94
+ Required fields:
95
+ name, version
96
+
97
+ Warns if any are missing.
98
+ """
99
+ metadata = self.distribution.metadata
100
+
101
+ missing = [
102
+ attr for attr in ('name', 'version') if not getattr(metadata, attr, None)
103
+ ]
104
+
105
+ if missing:
106
+ self.warn("missing required meta-data: {}".format(', '.join(missing)))
107
+
108
+ def check_restructuredtext(self):
109
+ """Checks if the long string fields are reST-compliant."""
110
+ data = self.distribution.get_long_description()
111
+ for warning in self._check_rst_data(data):
112
+ line = warning[-1].get('line')
113
+ if line is None:
114
+ warning = warning[1]
115
+ else:
116
+ warning = f'{warning[1]} (line {line})'
117
+ self.warn(warning)
118
+
119
+ def _check_rst_data(self, data):
120
+ """Returns warnings when the provided data doesn't compile."""
121
+ # the include and csv_table directives need this to be a path
122
+ source_path = self.distribution.script_name or 'setup.py'
123
+ parser = docutils.parsers.rst.Parser()
124
+ settings = docutils.frontend.OptionParser(
125
+ components=(docutils.parsers.rst.Parser,)
126
+ ).get_default_values()
127
+ settings.tab_width = 4
128
+ settings.pep_references = None
129
+ settings.rfc_references = None
130
+ reporter = SilentReporter(
131
+ source_path,
132
+ settings.report_level,
133
+ settings.halt_level,
134
+ stream=settings.warning_stream,
135
+ debug=settings.debug,
136
+ encoding=settings.error_encoding,
137
+ error_handler=settings.error_encoding_error_handler,
138
+ )
139
+
140
+ document = docutils.nodes.document(settings, reporter, source=source_path)
141
+ document.note_source(source_path, -1)
142
+ try:
143
+ parser.parse(data, document)
144
+ except (AttributeError, TypeError) as e:
145
+ reporter.messages.append((
146
+ -1,
147
+ f'Could not finish the parsing: {e}.',
148
+ '',
149
+ {},
150
+ ))
151
+
152
+ return reporter.messages
python/Lib/site-packages/setuptools/_distutils/command/clean.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.clean
2
+
3
+ Implements the Distutils 'clean' command."""
4
+
5
+ # contributed by Bastian Kleineidam <calvin@cs.uni-sb.de>, added 2000-03-18
6
+
7
+ import os
8
+ from distutils._log import log
9
+ from typing import ClassVar
10
+
11
+ from ..core import Command
12
+ from ..dir_util import remove_tree
13
+
14
+
15
+ class clean(Command):
16
+ description = "clean up temporary files from 'build' command"
17
+ user_options = [
18
+ ('build-base=', 'b', "base build directory [default: 'build.build-base']"),
19
+ (
20
+ 'build-lib=',
21
+ None,
22
+ "build directory for all modules [default: 'build.build-lib']",
23
+ ),
24
+ ('build-temp=', 't', "temporary build directory [default: 'build.build-temp']"),
25
+ (
26
+ 'build-scripts=',
27
+ None,
28
+ "build directory for scripts [default: 'build.build-scripts']",
29
+ ),
30
+ ('bdist-base=', None, "temporary directory for built distributions"),
31
+ ('all', 'a', "remove all build output, not just temporary by-products"),
32
+ ]
33
+
34
+ boolean_options: ClassVar[list[str]] = ['all']
35
+
36
+ def initialize_options(self):
37
+ self.build_base = None
38
+ self.build_lib = None
39
+ self.build_temp = None
40
+ self.build_scripts = None
41
+ self.bdist_base = None
42
+ self.all = None
43
+
44
+ def finalize_options(self):
45
+ self.set_undefined_options(
46
+ 'build',
47
+ ('build_base', 'build_base'),
48
+ ('build_lib', 'build_lib'),
49
+ ('build_scripts', 'build_scripts'),
50
+ ('build_temp', 'build_temp'),
51
+ )
52
+ self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))
53
+
54
+ def run(self):
55
+ # remove the build/temp.<plat> directory (unless it's already
56
+ # gone)
57
+ if os.path.exists(self.build_temp):
58
+ remove_tree(self.build_temp)
59
+ else:
60
+ log.debug("'%s' does not exist -- can't clean it", self.build_temp)
61
+
62
+ if self.all:
63
+ # remove build directories
64
+ for directory in (self.build_lib, self.bdist_base, self.build_scripts):
65
+ if os.path.exists(directory):
66
+ remove_tree(directory)
67
+ else:
68
+ log.warning("'%s' does not exist -- can't clean it", directory)
69
+
70
+ # just for the heck of it, try to remove the base build directory:
71
+ # we might have emptied it right now, but if not we don't care
72
+ try:
73
+ os.rmdir(self.build_base)
74
+ log.info("removing '%s'", self.build_base)
75
+ except OSError:
76
+ pass
python/Lib/site-packages/setuptools/_distutils/command/config.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.config
2
+
3
+ Implements the Distutils 'config' command, a (mostly) empty command class
4
+ that exists mainly to be sub-classed by specific module distributions and
5
+ applications. The idea is that while every "config" command is different,
6
+ at least they're all named the same, and users always see "config" in the
7
+ list of standard commands. Also, this is a good place to put common
8
+ configure-like tasks: "try to compile this C code", or "figure out where
9
+ this header file lives".
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import pathlib
16
+ import re
17
+ from collections.abc import Sequence
18
+ from distutils._log import log
19
+
20
+ from ..ccompiler import CCompiler, CompileError, LinkError, new_compiler
21
+ from ..core import Command
22
+ from ..errors import DistutilsExecError
23
+ from ..sysconfig import customize_compiler
24
+
25
+ LANG_EXT = {"c": ".c", "c++": ".cxx"}
26
+
27
+
28
+ class config(Command):
29
+ description = "prepare to build"
30
+
31
+ user_options = [
32
+ ('compiler=', None, "specify the compiler type"),
33
+ ('cc=', None, "specify the compiler executable"),
34
+ ('include-dirs=', 'I', "list of directories to search for header files"),
35
+ ('define=', 'D', "C preprocessor macros to define"),
36
+ ('undef=', 'U', "C preprocessor macros to undefine"),
37
+ ('libraries=', 'l', "external C libraries to link with"),
38
+ ('library-dirs=', 'L', "directories to search for external C libraries"),
39
+ ('noisy', None, "show every action (compile, link, run, ...) taken"),
40
+ (
41
+ 'dump-source',
42
+ None,
43
+ "dump generated source files before attempting to compile them",
44
+ ),
45
+ ]
46
+
47
+ # The three standard command methods: since the "config" command
48
+ # does nothing by default, these are empty.
49
+
50
+ def initialize_options(self):
51
+ self.compiler = None
52
+ self.cc = None
53
+ self.include_dirs = None
54
+ self.libraries = None
55
+ self.library_dirs = None
56
+
57
+ # maximal output for now
58
+ self.noisy = 1
59
+ self.dump_source = 1
60
+
61
+ # list of temporary files generated along-the-way that we have
62
+ # to clean at some point
63
+ self.temp_files = []
64
+
65
+ def finalize_options(self):
66
+ if self.include_dirs is None:
67
+ self.include_dirs = self.distribution.include_dirs or []
68
+ elif isinstance(self.include_dirs, str):
69
+ self.include_dirs = self.include_dirs.split(os.pathsep)
70
+
71
+ if self.libraries is None:
72
+ self.libraries = []
73
+ elif isinstance(self.libraries, str):
74
+ self.libraries = [self.libraries]
75
+
76
+ if self.library_dirs is None:
77
+ self.library_dirs = []
78
+ elif isinstance(self.library_dirs, str):
79
+ self.library_dirs = self.library_dirs.split(os.pathsep)
80
+
81
+ def run(self):
82
+ pass
83
+
84
+ # Utility methods for actual "config" commands. The interfaces are
85
+ # loosely based on Autoconf macros of similar names. Sub-classes
86
+ # may use these freely.
87
+
88
+ def _check_compiler(self):
89
+ """Check that 'self.compiler' really is a CCompiler object;
90
+ if not, make it one.
91
+ """
92
+ if not isinstance(self.compiler, CCompiler):
93
+ self.compiler = new_compiler(compiler=self.compiler, force=True)
94
+ customize_compiler(self.compiler)
95
+ if self.include_dirs:
96
+ self.compiler.set_include_dirs(self.include_dirs)
97
+ if self.libraries:
98
+ self.compiler.set_libraries(self.libraries)
99
+ if self.library_dirs:
100
+ self.compiler.set_library_dirs(self.library_dirs)
101
+
102
+ def _gen_temp_sourcefile(self, body, headers, lang):
103
+ filename = "_configtest" + LANG_EXT[lang]
104
+ with open(filename, "w", encoding='utf-8') as file:
105
+ if headers:
106
+ for header in headers:
107
+ file.write(f"#include <{header}>\n")
108
+ file.write("\n")
109
+ file.write(body)
110
+ if body[-1] != "\n":
111
+ file.write("\n")
112
+ return filename
113
+
114
+ def _preprocess(self, body, headers, include_dirs, lang):
115
+ src = self._gen_temp_sourcefile(body, headers, lang)
116
+ out = "_configtest.i"
117
+ self.temp_files.extend([src, out])
118
+ self.compiler.preprocess(src, out, include_dirs=include_dirs)
119
+ return (src, out)
120
+
121
+ def _compile(self, body, headers, include_dirs, lang):
122
+ src = self._gen_temp_sourcefile(body, headers, lang)
123
+ if self.dump_source:
124
+ dump_file(src, f"compiling '{src}':")
125
+ (obj,) = self.compiler.object_filenames([src])
126
+ self.temp_files.extend([src, obj])
127
+ self.compiler.compile([src], include_dirs=include_dirs)
128
+ return (src, obj)
129
+
130
+ def _link(self, body, headers, include_dirs, libraries, library_dirs, lang):
131
+ (src, obj) = self._compile(body, headers, include_dirs, lang)
132
+ prog = os.path.splitext(os.path.basename(src))[0]
133
+ self.compiler.link_executable(
134
+ [obj],
135
+ prog,
136
+ libraries=libraries,
137
+ library_dirs=library_dirs,
138
+ target_lang=lang,
139
+ )
140
+
141
+ if self.compiler.exe_extension is not None:
142
+ prog = prog + self.compiler.exe_extension
143
+ self.temp_files.append(prog)
144
+
145
+ return (src, obj, prog)
146
+
147
+ def _clean(self, *filenames):
148
+ if not filenames:
149
+ filenames = self.temp_files
150
+ self.temp_files = []
151
+ log.info("removing: %s", ' '.join(filenames))
152
+ for filename in filenames:
153
+ try:
154
+ os.remove(filename)
155
+ except OSError:
156
+ pass
157
+
158
+ # XXX need access to the header search path and maybe default macros.
159
+
160
+ def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
161
+ """Construct a source file from 'body' (a string containing lines
162
+ of C/C++ code) and 'headers' (a list of header files to include)
163
+ and run it through the preprocessor. Return true if the
164
+ preprocessor succeeded, false if there were any errors.
165
+ ('body' probably isn't of much use, but what the heck.)
166
+ """
167
+ self._check_compiler()
168
+ ok = True
169
+ try:
170
+ self._preprocess(body, headers, include_dirs, lang)
171
+ except CompileError:
172
+ ok = False
173
+
174
+ self._clean()
175
+ return ok
176
+
177
+ def search_cpp(self, pattern, body=None, headers=None, include_dirs=None, lang="c"):
178
+ """Construct a source file (just like 'try_cpp()'), run it through
179
+ the preprocessor, and return true if any line of the output matches
180
+ 'pattern'. 'pattern' should either be a compiled regex object or a
181
+ string containing a regex. If both 'body' and 'headers' are None,
182
+ preprocesses an empty file -- which can be useful to determine the
183
+ symbols the preprocessor and compiler set by default.
184
+ """
185
+ self._check_compiler()
186
+ src, out = self._preprocess(body, headers, include_dirs, lang)
187
+
188
+ if isinstance(pattern, str):
189
+ pattern = re.compile(pattern)
190
+
191
+ with open(out, encoding='utf-8') as file:
192
+ match = any(pattern.search(line) for line in file)
193
+
194
+ self._clean()
195
+ return match
196
+
197
+ def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
198
+ """Try to compile a source file built from 'body' and 'headers'.
199
+ Return true on success, false otherwise.
200
+ """
201
+ self._check_compiler()
202
+ try:
203
+ self._compile(body, headers, include_dirs, lang)
204
+ ok = True
205
+ except CompileError:
206
+ ok = False
207
+
208
+ log.info(ok and "success!" or "failure.")
209
+ self._clean()
210
+ return ok
211
+
212
+ def try_link(
213
+ self,
214
+ body,
215
+ headers=None,
216
+ include_dirs=None,
217
+ libraries=None,
218
+ library_dirs=None,
219
+ lang="c",
220
+ ):
221
+ """Try to compile and link a source file, built from 'body' and
222
+ 'headers', to executable form. Return true on success, false
223
+ otherwise.
224
+ """
225
+ self._check_compiler()
226
+ try:
227
+ self._link(body, headers, include_dirs, libraries, library_dirs, lang)
228
+ ok = True
229
+ except (CompileError, LinkError):
230
+ ok = False
231
+
232
+ log.info(ok and "success!" or "failure.")
233
+ self._clean()
234
+ return ok
235
+
236
+ def try_run(
237
+ self,
238
+ body,
239
+ headers=None,
240
+ include_dirs=None,
241
+ libraries=None,
242
+ library_dirs=None,
243
+ lang="c",
244
+ ):
245
+ """Try to compile, link to an executable, and run a program
246
+ built from 'body' and 'headers'. Return true on success, false
247
+ otherwise.
248
+ """
249
+ self._check_compiler()
250
+ try:
251
+ src, obj, exe = self._link(
252
+ body, headers, include_dirs, libraries, library_dirs, lang
253
+ )
254
+ self.spawn([exe])
255
+ ok = True
256
+ except (CompileError, LinkError, DistutilsExecError):
257
+ ok = False
258
+
259
+ log.info(ok and "success!" or "failure.")
260
+ self._clean()
261
+ return ok
262
+
263
+ # -- High-level methods --------------------------------------------
264
+ # (these are the ones that are actually likely to be useful
265
+ # when implementing a real-world config command!)
266
+
267
+ def check_func(
268
+ self,
269
+ func,
270
+ headers=None,
271
+ include_dirs=None,
272
+ libraries=None,
273
+ library_dirs=None,
274
+ decl=False,
275
+ call=False,
276
+ ):
277
+ """Determine if function 'func' is available by constructing a
278
+ source file that refers to 'func', and compiles and links it.
279
+ If everything succeeds, returns true; otherwise returns false.
280
+
281
+ The constructed source file starts out by including the header
282
+ files listed in 'headers'. If 'decl' is true, it then declares
283
+ 'func' (as "int func()"); you probably shouldn't supply 'headers'
284
+ and set 'decl' true in the same call, or you might get errors about
285
+ a conflicting declarations for 'func'. Finally, the constructed
286
+ 'main()' function either references 'func' or (if 'call' is true)
287
+ calls it. 'libraries' and 'library_dirs' are used when
288
+ linking.
289
+ """
290
+ self._check_compiler()
291
+ body = []
292
+ if decl:
293
+ body.append(f"int {func} ();")
294
+ body.append("int main () {")
295
+ if call:
296
+ body.append(f" {func}();")
297
+ else:
298
+ body.append(f" {func};")
299
+ body.append("}")
300
+ body = "\n".join(body) + "\n"
301
+
302
+ return self.try_link(body, headers, include_dirs, libraries, library_dirs)
303
+
304
+ def check_lib(
305
+ self,
306
+ library,
307
+ library_dirs=None,
308
+ headers=None,
309
+ include_dirs=None,
310
+ other_libraries: Sequence[str] = [],
311
+ ):
312
+ """Determine if 'library' is available to be linked against,
313
+ without actually checking that any particular symbols are provided
314
+ by it. 'headers' will be used in constructing the source file to
315
+ be compiled, but the only effect of this is to check if all the
316
+ header files listed are available. Any libraries listed in
317
+ 'other_libraries' will be included in the link, in case 'library'
318
+ has symbols that depend on other libraries.
319
+ """
320
+ self._check_compiler()
321
+ return self.try_link(
322
+ "int main (void) { }",
323
+ headers,
324
+ include_dirs,
325
+ [library] + list(other_libraries),
326
+ library_dirs,
327
+ )
328
+
329
+ def check_header(self, header, include_dirs=None, library_dirs=None, lang="c"):
330
+ """Determine if the system header file named by 'header_file'
331
+ exists and can be found by the preprocessor; return true if so,
332
+ false otherwise.
333
+ """
334
+ return self.try_cpp(
335
+ body="/* No body */", headers=[header], include_dirs=include_dirs
336
+ )
337
+
338
+
339
+ def dump_file(filename, head=None):
340
+ """Dumps a file content into log.info.
341
+
342
+ If head is not None, will be dumped before the file content.
343
+ """
344
+ if head is None:
345
+ log.info('%s', filename)
346
+ else:
347
+ log.info(head)
348
+ log.info(pathlib.Path(filename).read_text(encoding='utf-8'))
python/Lib/site-packages/setuptools/_distutils/command/install.py ADDED
@@ -0,0 +1,805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install
2
+
3
+ Implements the Distutils 'install' command."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import collections
8
+ import contextlib
9
+ import itertools
10
+ import os
11
+ import sys
12
+ import sysconfig
13
+ from distutils._log import log
14
+ from site import USER_BASE, USER_SITE
15
+ from typing import ClassVar
16
+
17
+ from ..core import Command
18
+ from ..debug import DEBUG
19
+ from ..errors import DistutilsOptionError, DistutilsPlatformError
20
+ from ..file_util import write_file
21
+ from ..sysconfig import get_config_vars
22
+ from ..util import change_root, convert_path, get_platform, subst_vars
23
+ from . import _framework_compat as fw
24
+
25
+ HAS_USER_SITE = True
26
+
27
+ WINDOWS_SCHEME = {
28
+ 'purelib': '{base}/Lib/site-packages',
29
+ 'platlib': '{base}/Lib/site-packages',
30
+ 'headers': '{base}/Include/{dist_name}',
31
+ 'scripts': '{base}/Scripts',
32
+ 'data': '{base}',
33
+ }
34
+
35
+ INSTALL_SCHEMES = {
36
+ 'posix_prefix': {
37
+ 'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages',
38
+ 'platlib': '{platbase}/{platlibdir}/{implementation_lower}'
39
+ '{py_version_short}/site-packages',
40
+ 'headers': '{base}/include/{implementation_lower}'
41
+ '{py_version_short}{abiflags}/{dist_name}',
42
+ 'scripts': '{base}/bin',
43
+ 'data': '{base}',
44
+ },
45
+ 'posix_home': {
46
+ 'purelib': '{base}/lib/{implementation_lower}',
47
+ 'platlib': '{base}/{platlibdir}/{implementation_lower}',
48
+ 'headers': '{base}/include/{implementation_lower}/{dist_name}',
49
+ 'scripts': '{base}/bin',
50
+ 'data': '{base}',
51
+ },
52
+ 'nt': WINDOWS_SCHEME,
53
+ 'pypy': {
54
+ 'purelib': '{base}/site-packages',
55
+ 'platlib': '{base}/site-packages',
56
+ 'headers': '{base}/include/{dist_name}',
57
+ 'scripts': '{base}/bin',
58
+ 'data': '{base}',
59
+ },
60
+ 'pypy_nt': {
61
+ 'purelib': '{base}/site-packages',
62
+ 'platlib': '{base}/site-packages',
63
+ 'headers': '{base}/include/{dist_name}',
64
+ 'scripts': '{base}/Scripts',
65
+ 'data': '{base}',
66
+ },
67
+ }
68
+
69
+ # user site schemes
70
+ if HAS_USER_SITE:
71
+ INSTALL_SCHEMES['nt_user'] = {
72
+ 'purelib': '{usersite}',
73
+ 'platlib': '{usersite}',
74
+ 'headers': '{userbase}/{implementation}{py_version_nodot_plat}'
75
+ '/Include/{dist_name}',
76
+ 'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',
77
+ 'data': '{userbase}',
78
+ }
79
+
80
+ INSTALL_SCHEMES['posix_user'] = {
81
+ 'purelib': '{usersite}',
82
+ 'platlib': '{usersite}',
83
+ 'headers': '{userbase}/include/{implementation_lower}'
84
+ '{py_version_short}{abiflags}/{dist_name}',
85
+ 'scripts': '{userbase}/bin',
86
+ 'data': '{userbase}',
87
+ }
88
+
89
+
90
+ INSTALL_SCHEMES.update(fw.schemes)
91
+
92
+
93
+ # The keys to an installation scheme; if any new types of files are to be
94
+ # installed, be sure to add an entry to every installation scheme above,
95
+ # and to SCHEME_KEYS here.
96
+ SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')
97
+
98
+
99
+ def _load_sysconfig_schemes():
100
+ with contextlib.suppress(AttributeError):
101
+ return {
102
+ scheme: sysconfig.get_paths(scheme, expand=False)
103
+ for scheme in sysconfig.get_scheme_names()
104
+ }
105
+
106
+
107
+ def _load_schemes():
108
+ """
109
+ Extend default schemes with schemes from sysconfig.
110
+ """
111
+
112
+ sysconfig_schemes = _load_sysconfig_schemes() or {}
113
+
114
+ return {
115
+ scheme: {
116
+ **INSTALL_SCHEMES.get(scheme, {}),
117
+ **sysconfig_schemes.get(scheme, {}),
118
+ }
119
+ for scheme in set(itertools.chain(INSTALL_SCHEMES, sysconfig_schemes))
120
+ }
121
+
122
+
123
+ def _get_implementation():
124
+ if hasattr(sys, 'pypy_version_info'):
125
+ return 'PyPy'
126
+ else:
127
+ return 'Python'
128
+
129
+
130
+ def _select_scheme(ob, name):
131
+ scheme = _inject_headers(name, _load_scheme(_resolve_scheme(name)))
132
+ vars(ob).update(_remove_set(ob, _scheme_attrs(scheme)))
133
+
134
+
135
+ def _remove_set(ob, attrs):
136
+ """
137
+ Include only attrs that are None in ob.
138
+ """
139
+ return {key: value for key, value in attrs.items() if getattr(ob, key) is None}
140
+
141
+
142
+ def _resolve_scheme(name):
143
+ os_name, sep, key = name.partition('_')
144
+ try:
145
+ resolved = sysconfig.get_preferred_scheme(key)
146
+ except Exception:
147
+ resolved = fw.scheme(name)
148
+ return resolved
149
+
150
+
151
+ def _load_scheme(name):
152
+ return _load_schemes()[name]
153
+
154
+
155
+ def _inject_headers(name, scheme):
156
+ """
157
+ Given a scheme name and the resolved scheme,
158
+ if the scheme does not include headers, resolve
159
+ the fallback scheme for the name and use headers
160
+ from it. pypa/distutils#88
161
+ """
162
+ # Bypass the preferred scheme, which may not
163
+ # have defined headers.
164
+ fallback = _load_scheme(name)
165
+ scheme.setdefault('headers', fallback['headers'])
166
+ return scheme
167
+
168
+
169
+ def _scheme_attrs(scheme):
170
+ """Resolve install directories by applying the install schemes."""
171
+ return {f'install_{key}': scheme[key] for key in SCHEME_KEYS}
172
+
173
+
174
+ class install(Command):
175
+ description = "install everything from build directory"
176
+
177
+ user_options = [
178
+ # Select installation scheme and set base director(y|ies)
179
+ ('prefix=', None, "installation prefix"),
180
+ ('exec-prefix=', None, "(Unix only) prefix for platform-specific files"),
181
+ ('home=', None, "(Unix only) home directory to install under"),
182
+ # Or, just set the base director(y|ies)
183
+ (
184
+ 'install-base=',
185
+ None,
186
+ "base installation directory (instead of --prefix or --home)",
187
+ ),
188
+ (
189
+ 'install-platbase=',
190
+ None,
191
+ "base installation directory for platform-specific files (instead of --exec-prefix or --home)",
192
+ ),
193
+ ('root=', None, "install everything relative to this alternate root directory"),
194
+ # Or, explicitly set the installation scheme
195
+ (
196
+ 'install-purelib=',
197
+ None,
198
+ "installation directory for pure Python module distributions",
199
+ ),
200
+ (
201
+ 'install-platlib=',
202
+ None,
203
+ "installation directory for non-pure module distributions",
204
+ ),
205
+ (
206
+ 'install-lib=',
207
+ None,
208
+ "installation directory for all module distributions (overrides --install-purelib and --install-platlib)",
209
+ ),
210
+ ('install-headers=', None, "installation directory for C/C++ headers"),
211
+ ('install-scripts=', None, "installation directory for Python scripts"),
212
+ ('install-data=', None, "installation directory for data files"),
213
+ # Byte-compilation options -- see install_lib.py for details, as
214
+ # these are duplicated from there (but only install_lib does
215
+ # anything with them).
216
+ ('compile', 'c', "compile .py to .pyc [default]"),
217
+ ('no-compile', None, "don't compile .py files"),
218
+ (
219
+ 'optimize=',
220
+ 'O',
221
+ "also compile with optimization: -O1 for \"python -O\", "
222
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
223
+ ),
224
+ # Miscellaneous control options
225
+ ('force', 'f', "force installation (overwrite any existing files)"),
226
+ ('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
227
+ # Where to install documentation (eventually!)
228
+ # ('doc-format=', None, "format of documentation to generate"),
229
+ # ('install-man=', None, "directory for Unix man pages"),
230
+ # ('install-html=', None, "directory for HTML documentation"),
231
+ # ('install-info=', None, "directory for GNU info files"),
232
+ ('record=', None, "filename in which to record list of installed files"),
233
+ ]
234
+
235
+ boolean_options: ClassVar[list[str]] = ['compile', 'force', 'skip-build']
236
+
237
+ if HAS_USER_SITE:
238
+ user_options.append((
239
+ 'user',
240
+ None,
241
+ f"install in user site-package '{USER_SITE}'",
242
+ ))
243
+ boolean_options.append('user')
244
+
245
+ negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
246
+
247
+ def initialize_options(self) -> None:
248
+ """Initializes options."""
249
+ # High-level options: these select both an installation base
250
+ # and scheme.
251
+ self.prefix: str | None = None
252
+ self.exec_prefix: str | None = None
253
+ self.home: str | None = None
254
+ self.user = False
255
+
256
+ # These select only the installation base; it's up to the user to
257
+ # specify the installation scheme (currently, that means supplying
258
+ # the --install-{platlib,purelib,scripts,data} options).
259
+ self.install_base = None
260
+ self.install_platbase = None
261
+ self.root: str | None = None
262
+
263
+ # These options are the actual installation directories; if not
264
+ # supplied by the user, they are filled in using the installation
265
+ # scheme implied by prefix/exec-prefix/home and the contents of
266
+ # that installation scheme.
267
+ self.install_purelib = None # for pure module distributions
268
+ self.install_platlib = None # non-pure (dists w/ extensions)
269
+ self.install_headers = None # for C/C++ headers
270
+ self.install_lib: str | None = None # set to either purelib or platlib
271
+ self.install_scripts = None
272
+ self.install_data = None
273
+ self.install_userbase = USER_BASE
274
+ self.install_usersite = USER_SITE
275
+
276
+ self.compile = None
277
+ self.optimize = None
278
+
279
+ # Deprecated
280
+ # These two are for putting non-packagized distributions into their
281
+ # own directory and creating a .pth file if it makes sense.
282
+ # 'extra_path' comes from the setup file; 'install_path_file' can
283
+ # be turned off if it makes no sense to install a .pth file. (But
284
+ # better to install it uselessly than to guess wrong and not
285
+ # install it when it's necessary and would be used!) Currently,
286
+ # 'install_path_file' is always true unless some outsider meddles
287
+ # with it.
288
+ self.extra_path = None
289
+ self.install_path_file = True
290
+
291
+ # 'force' forces installation, even if target files are not
292
+ # out-of-date. 'skip_build' skips running the "build" command,
293
+ # handy if you know it's not necessary. 'warn_dir' (which is *not*
294
+ # a user option, it's just there so the bdist_* commands can turn
295
+ # it off) determines whether we warn about installing to a
296
+ # directory not in sys.path.
297
+ self.force = False
298
+ self.skip_build = False
299
+ self.warn_dir = True
300
+
301
+ # These are only here as a conduit from the 'build' command to the
302
+ # 'install_*' commands that do the real work. ('build_base' isn't
303
+ # actually used anywhere, but it might be useful in future.) They
304
+ # are not user options, because if the user told the install
305
+ # command where the build directory is, that wouldn't affect the
306
+ # build command.
307
+ self.build_base = None
308
+ self.build_lib = None
309
+
310
+ # Not defined yet because we don't know anything about
311
+ # documentation yet.
312
+ # self.install_man = None
313
+ # self.install_html = None
314
+ # self.install_info = None
315
+
316
+ self.record = None
317
+
318
+ # -- Option finalizing methods -------------------------------------
319
+ # (This is rather more involved than for most commands,
320
+ # because this is where the policy for installing third-
321
+ # party Python modules on various platforms given a wide
322
+ # array of user input is decided. Yes, it's quite complex!)
323
+
324
+ def finalize_options(self) -> None: # noqa: C901
325
+ """Finalizes options."""
326
+ # This method (and its helpers, like 'finalize_unix()',
327
+ # 'finalize_other()', and 'select_scheme()') is where the default
328
+ # installation directories for modules, extension modules, and
329
+ # anything else we care to install from a Python module
330
+ # distribution. Thus, this code makes a pretty important policy
331
+ # statement about how third-party stuff is added to a Python
332
+ # installation! Note that the actual work of installation is done
333
+ # by the relatively simple 'install_*' commands; they just take
334
+ # their orders from the installation directory options determined
335
+ # here.
336
+
337
+ # Check for errors/inconsistencies in the options; first, stuff
338
+ # that's wrong on any platform.
339
+
340
+ if (self.prefix or self.exec_prefix or self.home) and (
341
+ self.install_base or self.install_platbase
342
+ ):
343
+ raise DistutilsOptionError(
344
+ "must supply either prefix/exec-prefix/home or install-base/install-platbase -- not both"
345
+ )
346
+
347
+ if self.home and (self.prefix or self.exec_prefix):
348
+ raise DistutilsOptionError(
349
+ "must supply either home or prefix/exec-prefix -- not both"
350
+ )
351
+
352
+ if self.user and (
353
+ self.prefix
354
+ or self.exec_prefix
355
+ or self.home
356
+ or self.install_base
357
+ or self.install_platbase
358
+ ):
359
+ raise DistutilsOptionError(
360
+ "can't combine user with prefix, "
361
+ "exec_prefix/home, or install_(plat)base"
362
+ )
363
+
364
+ # Next, stuff that's wrong (or dubious) only on certain platforms.
365
+ if os.name != "posix":
366
+ if self.exec_prefix:
367
+ self.warn("exec-prefix option ignored on this platform")
368
+ self.exec_prefix = None
369
+
370
+ # Now the interesting logic -- so interesting that we farm it out
371
+ # to other methods. The goal of these methods is to set the final
372
+ # values for the install_{lib,scripts,data,...} options, using as
373
+ # input a heady brew of prefix, exec_prefix, home, install_base,
374
+ # install_platbase, user-supplied versions of
375
+ # install_{purelib,platlib,lib,scripts,data,...}, and the
376
+ # install schemes. Phew!
377
+
378
+ self.dump_dirs("pre-finalize_{unix,other}")
379
+
380
+ if os.name == 'posix':
381
+ self.finalize_unix()
382
+ else:
383
+ self.finalize_other()
384
+
385
+ self.dump_dirs("post-finalize_{unix,other}()")
386
+
387
+ # Expand configuration variables, tilde, etc. in self.install_base
388
+ # and self.install_platbase -- that way, we can use $base or
389
+ # $platbase in the other installation directories and not worry
390
+ # about needing recursive variable expansion (shudder).
391
+
392
+ py_version = sys.version.split()[0]
393
+ (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
394
+ try:
395
+ abiflags = sys.abiflags
396
+ except AttributeError:
397
+ # sys.abiflags may not be defined on all platforms.
398
+ abiflags = ''
399
+ local_vars = {
400
+ 'dist_name': self.distribution.get_name(),
401
+ 'dist_version': self.distribution.get_version(),
402
+ 'dist_fullname': self.distribution.get_fullname(),
403
+ 'py_version': py_version,
404
+ 'py_version_short': f'{sys.version_info.major}.{sys.version_info.minor}',
405
+ 'py_version_nodot': f'{sys.version_info.major}{sys.version_info.minor}',
406
+ 'sys_prefix': prefix,
407
+ 'prefix': prefix,
408
+ 'sys_exec_prefix': exec_prefix,
409
+ 'exec_prefix': exec_prefix,
410
+ 'abiflags': abiflags,
411
+ 'platlibdir': getattr(sys, 'platlibdir', 'lib'),
412
+ 'implementation_lower': _get_implementation().lower(),
413
+ 'implementation': _get_implementation(),
414
+ }
415
+
416
+ # vars for compatibility on older Pythons
417
+ compat_vars = dict(
418
+ # Python 3.9 and earlier
419
+ py_version_nodot_plat=getattr(sys, 'winver', '').replace('.', ''),
420
+ )
421
+
422
+ if HAS_USER_SITE:
423
+ local_vars['userbase'] = self.install_userbase
424
+ local_vars['usersite'] = self.install_usersite
425
+
426
+ self.config_vars = collections.ChainMap(
427
+ local_vars,
428
+ sysconfig.get_config_vars(),
429
+ compat_vars,
430
+ fw.vars(),
431
+ )
432
+
433
+ self.expand_basedirs()
434
+
435
+ self.dump_dirs("post-expand_basedirs()")
436
+
437
+ # Now define config vars for the base directories so we can expand
438
+ # everything else.
439
+ local_vars['base'] = self.install_base
440
+ local_vars['platbase'] = self.install_platbase
441
+
442
+ if DEBUG:
443
+ from pprint import pprint
444
+
445
+ print("config vars:")
446
+ pprint(dict(self.config_vars))
447
+
448
+ # Expand "~" and configuration variables in the installation
449
+ # directories.
450
+ self.expand_dirs()
451
+
452
+ self.dump_dirs("post-expand_dirs()")
453
+
454
+ # Create directories in the home dir:
455
+ if self.user:
456
+ self.create_home_path()
457
+
458
+ # Pick the actual directory to install all modules to: either
459
+ # install_purelib or install_platlib, depending on whether this
460
+ # module distribution is pure or not. Of course, if the user
461
+ # already specified install_lib, use their selection.
462
+ if self.install_lib is None:
463
+ if self.distribution.has_ext_modules(): # has extensions: non-pure
464
+ self.install_lib = self.install_platlib
465
+ else:
466
+ self.install_lib = self.install_purelib
467
+
468
+ # Convert directories from Unix /-separated syntax to the local
469
+ # convention.
470
+ self.convert_paths(
471
+ 'lib',
472
+ 'purelib',
473
+ 'platlib',
474
+ 'scripts',
475
+ 'data',
476
+ 'headers',
477
+ 'userbase',
478
+ 'usersite',
479
+ )
480
+
481
+ # Deprecated
482
+ # Well, we're not actually fully completely finalized yet: we still
483
+ # have to deal with 'extra_path', which is the hack for allowing
484
+ # non-packagized module distributions (hello, Numerical Python!) to
485
+ # get their own directories.
486
+ self.handle_extra_path()
487
+ self.install_libbase = self.install_lib # needed for .pth file
488
+ self.install_lib = os.path.join(self.install_lib, self.extra_dirs)
489
+
490
+ # If a new root directory was supplied, make all the installation
491
+ # dirs relative to it.
492
+ if self.root is not None:
493
+ self.change_roots(
494
+ 'libbase', 'lib', 'purelib', 'platlib', 'scripts', 'data', 'headers'
495
+ )
496
+
497
+ self.dump_dirs("after prepending root")
498
+
499
+ # Find out the build directories, ie. where to install from.
500
+ self.set_undefined_options(
501
+ 'build', ('build_base', 'build_base'), ('build_lib', 'build_lib')
502
+ )
503
+
504
+ # Punt on doc directories for now -- after all, we're punting on
505
+ # documentation completely!
506
+
507
+ def dump_dirs(self, msg) -> None:
508
+ """Dumps the list of user options."""
509
+ if not DEBUG:
510
+ return
511
+ from ..fancy_getopt import longopt_xlate
512
+
513
+ log.debug(msg + ":")
514
+ for opt in self.user_options:
515
+ opt_name = opt[0]
516
+ if opt_name[-1] == "=":
517
+ opt_name = opt_name[0:-1]
518
+ if opt_name in self.negative_opt:
519
+ opt_name = self.negative_opt[opt_name]
520
+ opt_name = opt_name.translate(longopt_xlate)
521
+ val = not getattr(self, opt_name)
522
+ else:
523
+ opt_name = opt_name.translate(longopt_xlate)
524
+ val = getattr(self, opt_name)
525
+ log.debug(" %s: %s", opt_name, val)
526
+
527
+ def finalize_unix(self) -> None:
528
+ """Finalizes options for posix platforms."""
529
+ if self.install_base is not None or self.install_platbase is not None:
530
+ incomplete_scheme = (
531
+ (
532
+ self.install_lib is None
533
+ and self.install_purelib is None
534
+ and self.install_platlib is None
535
+ )
536
+ or self.install_headers is None
537
+ or self.install_scripts is None
538
+ or self.install_data is None
539
+ )
540
+ if incomplete_scheme:
541
+ raise DistutilsOptionError(
542
+ "install-base or install-platbase supplied, but "
543
+ "installation scheme is incomplete"
544
+ )
545
+ return
546
+
547
+ if self.user:
548
+ if self.install_userbase is None:
549
+ raise DistutilsPlatformError("User base directory is not specified")
550
+ self.install_base = self.install_platbase = self.install_userbase
551
+ self.select_scheme("posix_user")
552
+ elif self.home is not None:
553
+ self.install_base = self.install_platbase = self.home
554
+ self.select_scheme("posix_home")
555
+ else:
556
+ if self.prefix is None:
557
+ if self.exec_prefix is not None:
558
+ raise DistutilsOptionError(
559
+ "must not supply exec-prefix without prefix"
560
+ )
561
+
562
+ # Allow Fedora to add components to the prefix
563
+ _prefix_addition = getattr(sysconfig, '_prefix_addition', "")
564
+
565
+ self.prefix = os.path.normpath(sys.prefix) + _prefix_addition
566
+ self.exec_prefix = os.path.normpath(sys.exec_prefix) + _prefix_addition
567
+
568
+ else:
569
+ if self.exec_prefix is None:
570
+ self.exec_prefix = self.prefix
571
+
572
+ self.install_base = self.prefix
573
+ self.install_platbase = self.exec_prefix
574
+ self.select_scheme("posix_prefix")
575
+
576
+ def finalize_other(self) -> None:
577
+ """Finalizes options for non-posix platforms"""
578
+ if self.user:
579
+ if self.install_userbase is None:
580
+ raise DistutilsPlatformError("User base directory is not specified")
581
+ self.install_base = self.install_platbase = self.install_userbase
582
+ self.select_scheme(os.name + "_user")
583
+ elif self.home is not None:
584
+ self.install_base = self.install_platbase = self.home
585
+ self.select_scheme("posix_home")
586
+ else:
587
+ if self.prefix is None:
588
+ self.prefix = os.path.normpath(sys.prefix)
589
+
590
+ self.install_base = self.install_platbase = self.prefix
591
+ try:
592
+ self.select_scheme(os.name)
593
+ except KeyError:
594
+ raise DistutilsPlatformError(
595
+ f"I don't know how to install stuff on '{os.name}'"
596
+ )
597
+
598
+ def select_scheme(self, name) -> None:
599
+ _select_scheme(self, name)
600
+
601
+ def _expand_attrs(self, attrs):
602
+ for attr in attrs:
603
+ val = getattr(self, attr)
604
+ if val is not None:
605
+ if os.name in ('posix', 'nt'):
606
+ val = os.path.expanduser(val)
607
+ val = subst_vars(val, self.config_vars)
608
+ setattr(self, attr, val)
609
+
610
+ def expand_basedirs(self) -> None:
611
+ """Calls `os.path.expanduser` on install_base, install_platbase and
612
+ root."""
613
+ self._expand_attrs(['install_base', 'install_platbase', 'root'])
614
+
615
+ def expand_dirs(self) -> None:
616
+ """Calls `os.path.expanduser` on install dirs."""
617
+ self._expand_attrs([
618
+ 'install_purelib',
619
+ 'install_platlib',
620
+ 'install_lib',
621
+ 'install_headers',
622
+ 'install_scripts',
623
+ 'install_data',
624
+ ])
625
+
626
+ def convert_paths(self, *names) -> None:
627
+ """Call `convert_path` over `names`."""
628
+ for name in names:
629
+ attr = "install_" + name
630
+ setattr(self, attr, convert_path(getattr(self, attr)))
631
+
632
+ def handle_extra_path(self) -> None:
633
+ """Set `path_file` and `extra_dirs` using `extra_path`."""
634
+ if self.extra_path is None:
635
+ self.extra_path = self.distribution.extra_path
636
+
637
+ if self.extra_path is not None:
638
+ log.warning(
639
+ "Distribution option extra_path is deprecated. "
640
+ "See issue27919 for details."
641
+ )
642
+ if isinstance(self.extra_path, str):
643
+ self.extra_path = self.extra_path.split(',')
644
+
645
+ if len(self.extra_path) == 1:
646
+ path_file = extra_dirs = self.extra_path[0]
647
+ elif len(self.extra_path) == 2:
648
+ path_file, extra_dirs = self.extra_path
649
+ else:
650
+ raise DistutilsOptionError(
651
+ "'extra_path' option must be a list, tuple, or "
652
+ "comma-separated string with 1 or 2 elements"
653
+ )
654
+
655
+ # convert to local form in case Unix notation used (as it
656
+ # should be in setup scripts)
657
+ extra_dirs = convert_path(extra_dirs)
658
+ else:
659
+ path_file = None
660
+ extra_dirs = ''
661
+
662
+ # XXX should we warn if path_file and not extra_dirs? (in which
663
+ # case the path file would be harmless but pointless)
664
+ self.path_file = path_file
665
+ self.extra_dirs = extra_dirs
666
+
667
+ def change_roots(self, *names) -> None:
668
+ """Change the install directories pointed by name using root."""
669
+ for name in names:
670
+ attr = "install_" + name
671
+ setattr(self, attr, change_root(self.root, getattr(self, attr)))
672
+
673
+ def create_home_path(self) -> None:
674
+ """Create directories under ~."""
675
+ if not self.user:
676
+ return
677
+ home = convert_path(os.path.expanduser("~"))
678
+ for path in self.config_vars.values():
679
+ if str(path).startswith(home) and not os.path.isdir(path):
680
+ self.debug_print(f"os.makedirs('{path}', 0o700)")
681
+ os.makedirs(path, 0o700)
682
+
683
+ # -- Command execution methods -------------------------------------
684
+
685
+ def run(self):
686
+ """Runs the command."""
687
+ # Obviously have to build before we can install
688
+ if not self.skip_build:
689
+ self.run_command('build')
690
+ # If we built for any other platform, we can't install.
691
+ build_plat = self.distribution.get_command_obj('build').plat_name
692
+ # check warn_dir - it is a clue that the 'install' is happening
693
+ # internally, and not to sys.path, so we don't check the platform
694
+ # matches what we are running.
695
+ if self.warn_dir and build_plat != get_platform():
696
+ raise DistutilsPlatformError("Can't install when cross-compiling")
697
+
698
+ # Run all sub-commands (at least those that need to be run)
699
+ for cmd_name in self.get_sub_commands():
700
+ self.run_command(cmd_name)
701
+
702
+ if self.path_file:
703
+ self.create_path_file()
704
+
705
+ # write list of installed files, if requested.
706
+ if self.record:
707
+ outputs = self.get_outputs()
708
+ if self.root: # strip any package prefix
709
+ root_len = len(self.root)
710
+ for counter in range(len(outputs)):
711
+ outputs[counter] = outputs[counter][root_len:]
712
+ self.execute(
713
+ write_file,
714
+ (self.record, outputs),
715
+ f"writing list of installed files to '{self.record}'",
716
+ )
717
+
718
+ sys_path = map(os.path.normpath, sys.path)
719
+ sys_path = map(os.path.normcase, sys_path)
720
+ install_lib = os.path.normcase(os.path.normpath(self.install_lib))
721
+ if (
722
+ self.warn_dir
723
+ and not (self.path_file and self.install_path_file)
724
+ and install_lib not in sys_path
725
+ ):
726
+ log.debug(
727
+ (
728
+ "modules installed to '%s', which is not in "
729
+ "Python's module search path (sys.path) -- "
730
+ "you'll have to change the search path yourself"
731
+ ),
732
+ self.install_lib,
733
+ )
734
+
735
+ def create_path_file(self):
736
+ """Creates the .pth file"""
737
+ filename = os.path.join(self.install_libbase, self.path_file + ".pth")
738
+ if self.install_path_file:
739
+ self.execute(
740
+ write_file, (filename, [self.extra_dirs]), f"creating {filename}"
741
+ )
742
+ else:
743
+ self.warn(f"path file '{filename}' not created")
744
+
745
+ # -- Reporting methods ---------------------------------------------
746
+
747
+ def get_outputs(self):
748
+ """Assembles the outputs of all the sub-commands."""
749
+ outputs = []
750
+ for cmd_name in self.get_sub_commands():
751
+ cmd = self.get_finalized_command(cmd_name)
752
+ # Add the contents of cmd.get_outputs(), ensuring
753
+ # that outputs doesn't contain duplicate entries
754
+ for filename in cmd.get_outputs():
755
+ if filename not in outputs:
756
+ outputs.append(filename)
757
+
758
+ if self.path_file and self.install_path_file:
759
+ outputs.append(os.path.join(self.install_libbase, self.path_file + ".pth"))
760
+
761
+ return outputs
762
+
763
+ def get_inputs(self):
764
+ """Returns the inputs of all the sub-commands"""
765
+ # XXX gee, this looks familiar ;-(
766
+ inputs = []
767
+ for cmd_name in self.get_sub_commands():
768
+ cmd = self.get_finalized_command(cmd_name)
769
+ inputs.extend(cmd.get_inputs())
770
+
771
+ return inputs
772
+
773
+ # -- Predicates for sub-command list -------------------------------
774
+
775
+ def has_lib(self):
776
+ """Returns true if the current distribution has any Python
777
+ modules to install."""
778
+ return (
779
+ self.distribution.has_pure_modules() or self.distribution.has_ext_modules()
780
+ )
781
+
782
+ def has_headers(self):
783
+ """Returns true if the current distribution has any headers to
784
+ install."""
785
+ return self.distribution.has_headers()
786
+
787
+ def has_scripts(self):
788
+ """Returns true if the current distribution has any scripts to.
789
+ install."""
790
+ return self.distribution.has_scripts()
791
+
792
+ def has_data(self):
793
+ """Returns true if the current distribution has any data to.
794
+ install."""
795
+ return self.distribution.has_data_files()
796
+
797
+ # 'sub_commands': a list of commands this command might have to run to
798
+ # get its work done. See cmd.py for more info.
799
+ sub_commands = [
800
+ ('install_lib', has_lib),
801
+ ('install_headers', has_headers),
802
+ ('install_scripts', has_scripts),
803
+ ('install_data', has_data),
804
+ ('install_egg_info', lambda self: True),
805
+ ]
python/Lib/site-packages/setuptools/_distutils/command/install_data.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install_data
2
+
3
+ Implements the Distutils 'install_data' command, for installing
4
+ platform-independent data files."""
5
+
6
+ # contributed by Bastian Kleineidam
7
+
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ import os
12
+ from collections.abc import Iterable
13
+ from typing import ClassVar
14
+
15
+ from ..core import Command
16
+ from ..util import change_root, convert_path
17
+
18
+
19
+ class install_data(Command):
20
+ description = "install data files"
21
+
22
+ user_options = [
23
+ (
24
+ 'install-dir=',
25
+ 'd',
26
+ "base directory for installing data files [default: installation base dir]",
27
+ ),
28
+ ('root=', None, "install everything relative to this alternate root directory"),
29
+ ('force', 'f', "force installation (overwrite existing files)"),
30
+ ]
31
+
32
+ boolean_options: ClassVar[list[str]] = ['force']
33
+
34
+ def initialize_options(self):
35
+ self.install_dir = None
36
+ self.outfiles = []
37
+ self.root = None
38
+ self.force = False
39
+ self.data_files = self.distribution.data_files
40
+ self.warn_dir = True
41
+
42
+ def finalize_options(self) -> None:
43
+ self.set_undefined_options(
44
+ 'install',
45
+ ('install_data', 'install_dir'),
46
+ ('root', 'root'),
47
+ ('force', 'force'),
48
+ )
49
+
50
+ def run(self) -> None:
51
+ self.mkpath(self.install_dir)
52
+ for f in self.data_files:
53
+ self._copy(f)
54
+
55
+ @functools.singledispatchmethod
56
+ def _copy(self, f: tuple[str | os.PathLike, Iterable[str | os.PathLike]]):
57
+ # it's a tuple with path to install to and a list of files
58
+ dir = convert_path(f[0])
59
+ if not os.path.isabs(dir):
60
+ dir = os.path.join(self.install_dir, dir)
61
+ elif self.root:
62
+ dir = change_root(self.root, dir)
63
+ self.mkpath(dir)
64
+
65
+ if f[1] == []:
66
+ # If there are no files listed, the user must be
67
+ # trying to create an empty directory, so add the
68
+ # directory to the list of output files.
69
+ self.outfiles.append(dir)
70
+ else:
71
+ # Copy files, adding them to the list of output files.
72
+ for data in f[1]:
73
+ data = convert_path(data)
74
+ (out, _) = self.copy_file(data, dir)
75
+ self.outfiles.append(out)
76
+
77
+ @_copy.register(str)
78
+ @_copy.register(os.PathLike)
79
+ def _(self, f: str | os.PathLike):
80
+ # it's a simple file, so copy it
81
+ f = convert_path(f)
82
+ if self.warn_dir:
83
+ self.warn(
84
+ "setup script did not provide a directory for "
85
+ f"'{f}' -- installing right in '{self.install_dir}'"
86
+ )
87
+ (out, _) = self.copy_file(f, self.install_dir)
88
+ self.outfiles.append(out)
89
+
90
+ def get_inputs(self):
91
+ return self.data_files or []
92
+
93
+ def get_outputs(self):
94
+ return self.outfiles
python/Lib/site-packages/setuptools/_distutils/command/install_egg_info.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ distutils.command.install_egg_info
3
+
4
+ Implements the Distutils 'install_egg_info' command, for installing
5
+ a package's PKG-INFO metadata.
6
+ """
7
+
8
+ import os
9
+ import re
10
+ import sys
11
+ from typing import ClassVar
12
+
13
+ from .. import dir_util
14
+ from .._log import log
15
+ from ..cmd import Command
16
+
17
+
18
+ class install_egg_info(Command):
19
+ """Install an .egg-info file for the package"""
20
+
21
+ description = "Install package's PKG-INFO metadata as an .egg-info file"
22
+ user_options: ClassVar[list[tuple[str, str, str]]] = [
23
+ ('install-dir=', 'd', "directory to install to"),
24
+ ]
25
+
26
+ def initialize_options(self):
27
+ self.install_dir = None
28
+
29
+ @property
30
+ def basename(self):
31
+ """
32
+ Allow basename to be overridden by child class.
33
+ Ref pypa/distutils#2.
34
+ """
35
+ name = to_filename(safe_name(self.distribution.get_name()))
36
+ version = to_filename(safe_version(self.distribution.get_version()))
37
+ return f"{name}-{version}-py{sys.version_info.major}.{sys.version_info.minor}.egg-info"
38
+
39
+ def finalize_options(self):
40
+ self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
41
+ self.target = os.path.join(self.install_dir, self.basename)
42
+ self.outputs = [self.target]
43
+
44
+ def run(self):
45
+ target = self.target
46
+ if os.path.isdir(target) and not os.path.islink(target):
47
+ dir_util.remove_tree(target)
48
+ elif os.path.exists(target):
49
+ self.execute(os.unlink, (self.target,), "Removing " + target)
50
+ elif not os.path.isdir(self.install_dir):
51
+ self.execute(
52
+ os.makedirs, (self.install_dir,), "Creating " + self.install_dir
53
+ )
54
+ log.info("Writing %s", target)
55
+ with open(target, 'w', encoding='UTF-8') as f:
56
+ self.distribution.metadata.write_pkg_file(f)
57
+
58
+ def get_outputs(self):
59
+ return self.outputs
60
+
61
+
62
+ # The following routines are taken from setuptools' pkg_resources module and
63
+ # can be replaced by importing them from pkg_resources once it is included
64
+ # in the stdlib.
65
+
66
+
67
+ def safe_name(name):
68
+ """Convert an arbitrary string to a standard distribution name
69
+
70
+ Any runs of non-alphanumeric/. characters are replaced with a single '-'.
71
+ """
72
+ return re.sub('[^A-Za-z0-9.]+', '-', name)
73
+
74
+
75
+ def safe_version(version):
76
+ """Convert an arbitrary string to a standard version string
77
+
78
+ Spaces become dots, and all other non-alphanumeric characters become
79
+ dashes, with runs of multiple dashes condensed to a single dash.
80
+ """
81
+ version = version.replace(' ', '.')
82
+ return re.sub('[^A-Za-z0-9.]+', '-', version)
83
+
84
+
85
+ def to_filename(name):
86
+ """Convert a project or version name to its filename-escaped form
87
+
88
+ Any '-' characters are currently replaced with '_'.
89
+ """
90
+ return name.replace('-', '_')
python/Lib/site-packages/setuptools/_distutils/command/install_headers.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install_headers
2
+
3
+ Implements the Distutils 'install_headers' command, to install C/C++ header
4
+ files to the Python include directory."""
5
+
6
+ from typing import ClassVar
7
+
8
+ from ..core import Command
9
+
10
+
11
+ # XXX force is never used
12
+ class install_headers(Command):
13
+ description = "install C/C++ header files"
14
+
15
+ user_options: ClassVar[list[tuple[str, str, str]]] = [
16
+ ('install-dir=', 'd', "directory to install header files to"),
17
+ ('force', 'f', "force installation (overwrite existing files)"),
18
+ ]
19
+
20
+ boolean_options: ClassVar[list[str]] = ['force']
21
+
22
+ def initialize_options(self):
23
+ self.install_dir = None
24
+ self.force = False
25
+ self.outfiles = []
26
+
27
+ def finalize_options(self):
28
+ self.set_undefined_options(
29
+ 'install', ('install_headers', 'install_dir'), ('force', 'force')
30
+ )
31
+
32
+ def run(self):
33
+ headers = self.distribution.headers
34
+ if not headers:
35
+ return
36
+
37
+ self.mkpath(self.install_dir)
38
+ for header in headers:
39
+ (out, _) = self.copy_file(header, self.install_dir)
40
+ self.outfiles.append(out)
41
+
42
+ def get_inputs(self):
43
+ return self.distribution.headers or []
44
+
45
+ def get_outputs(self):
46
+ return self.outfiles
python/Lib/site-packages/setuptools/_distutils/command/install_lib.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install_lib
2
+
3
+ Implements the Distutils 'install_lib' command
4
+ (install all Python modules)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib.util
9
+ import os
10
+ import sys
11
+ from typing import Any, ClassVar
12
+
13
+ from ..core import Command
14
+ from ..errors import DistutilsOptionError
15
+
16
+ # Extension for Python source files.
17
+ PYTHON_SOURCE_EXTENSION = ".py"
18
+
19
+
20
+ class install_lib(Command):
21
+ description = "install all Python modules (extensions and pure Python)"
22
+
23
+ # The byte-compilation options are a tad confusing. Here are the
24
+ # possible scenarios:
25
+ # 1) no compilation at all (--no-compile --no-optimize)
26
+ # 2) compile .pyc only (--compile --no-optimize; default)
27
+ # 3) compile .pyc and "opt-1" .pyc (--compile --optimize)
28
+ # 4) compile "opt-1" .pyc only (--no-compile --optimize)
29
+ # 5) compile .pyc and "opt-2" .pyc (--compile --optimize-more)
30
+ # 6) compile "opt-2" .pyc only (--no-compile --optimize-more)
31
+ #
32
+ # The UI for this is two options, 'compile' and 'optimize'.
33
+ # 'compile' is strictly boolean, and only decides whether to
34
+ # generate .pyc files. 'optimize' is three-way (0, 1, or 2), and
35
+ # decides both whether to generate .pyc files and what level of
36
+ # optimization to use.
37
+
38
+ user_options = [
39
+ ('install-dir=', 'd', "directory to install to"),
40
+ ('build-dir=', 'b', "build directory (where to install from)"),
41
+ ('force', 'f', "force installation (overwrite existing files)"),
42
+ ('compile', 'c', "compile .py to .pyc [default]"),
43
+ ('no-compile', None, "don't compile .py files"),
44
+ (
45
+ 'optimize=',
46
+ 'O',
47
+ "also compile with optimization: -O1 for \"python -O\", "
48
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
49
+ ),
50
+ ('skip-build', None, "skip the build steps"),
51
+ ]
52
+
53
+ boolean_options: ClassVar[list[str]] = ['force', 'compile', 'skip-build']
54
+ negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
55
+
56
+ def initialize_options(self):
57
+ # let the 'install' command dictate our installation directory
58
+ self.install_dir = None
59
+ self.build_dir = None
60
+ self.force = False
61
+ self.compile = None
62
+ self.optimize = None
63
+ self.skip_build = None
64
+
65
+ def finalize_options(self) -> None:
66
+ # Get all the information we need to install pure Python modules
67
+ # from the umbrella 'install' command -- build (source) directory,
68
+ # install (target) directory, and whether to compile .py files.
69
+ self.set_undefined_options(
70
+ 'install',
71
+ ('build_lib', 'build_dir'),
72
+ ('install_lib', 'install_dir'),
73
+ ('force', 'force'),
74
+ ('compile', 'compile'),
75
+ ('optimize', 'optimize'),
76
+ ('skip_build', 'skip_build'),
77
+ )
78
+
79
+ if self.compile is None:
80
+ self.compile = True
81
+ if self.optimize is None:
82
+ self.optimize = False
83
+
84
+ if not isinstance(self.optimize, int):
85
+ try:
86
+ self.optimize = int(self.optimize)
87
+ except ValueError:
88
+ pass
89
+ if self.optimize not in (0, 1, 2):
90
+ raise DistutilsOptionError("optimize must be 0, 1, or 2")
91
+
92
+ def run(self) -> None:
93
+ # Make sure we have built everything we need first
94
+ self.build()
95
+
96
+ # Install everything: simply dump the entire contents of the build
97
+ # directory to the installation directory (that's the beauty of
98
+ # having a build directory!)
99
+ outfiles = self.install()
100
+
101
+ # (Optionally) compile .py to .pyc
102
+ if outfiles is not None and self.distribution.has_pure_modules():
103
+ self.byte_compile(outfiles)
104
+
105
+ # -- Top-level worker functions ------------------------------------
106
+ # (called from 'run()')
107
+
108
+ def build(self) -> None:
109
+ if not self.skip_build:
110
+ if self.distribution.has_pure_modules():
111
+ self.run_command('build_py')
112
+ if self.distribution.has_ext_modules():
113
+ self.run_command('build_ext')
114
+
115
+ # Any: https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#the-any-trick
116
+ def install(self) -> list[str] | Any:
117
+ if os.path.isdir(self.build_dir):
118
+ outfiles = self.copy_tree(self.build_dir, self.install_dir)
119
+ else:
120
+ self.warn(
121
+ f"'{self.build_dir}' does not exist -- no Python modules to install"
122
+ )
123
+ return
124
+ return outfiles
125
+
126
+ def byte_compile(self, files) -> None:
127
+ if sys.dont_write_bytecode:
128
+ self.warn('byte-compiling is disabled, skipping.')
129
+ return
130
+
131
+ from ..util import byte_compile
132
+
133
+ # Get the "--root" directory supplied to the "install" command,
134
+ # and use it as a prefix to strip off the purported filename
135
+ # encoded in bytecode files. This is far from complete, but it
136
+ # should at least generate usable bytecode in RPM distributions.
137
+ install_root = self.get_finalized_command('install').root
138
+
139
+ if self.compile:
140
+ byte_compile(
141
+ files,
142
+ optimize=0,
143
+ force=self.force,
144
+ prefix=install_root,
145
+ )
146
+ if self.optimize > 0:
147
+ byte_compile(
148
+ files,
149
+ optimize=self.optimize,
150
+ force=self.force,
151
+ prefix=install_root,
152
+ verbose=self.verbose,
153
+ )
154
+
155
+ # -- Utility methods -----------------------------------------------
156
+
157
+ def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir):
158
+ if not has_any:
159
+ return []
160
+
161
+ build_cmd = self.get_finalized_command(build_cmd)
162
+ build_files = build_cmd.get_outputs()
163
+ build_dir = getattr(build_cmd, cmd_option)
164
+
165
+ prefix_len = len(build_dir) + len(os.sep)
166
+ outputs = [os.path.join(output_dir, file[prefix_len:]) for file in build_files]
167
+
168
+ return outputs
169
+
170
+ def _bytecode_filenames(self, py_filenames):
171
+ bytecode_files = []
172
+ for py_file in py_filenames:
173
+ # Since build_py handles package data installation, the
174
+ # list of outputs can contain more than just .py files.
175
+ # Make sure we only report bytecode for the .py files.
176
+ ext = os.path.splitext(os.path.normcase(py_file))[1]
177
+ if ext != PYTHON_SOURCE_EXTENSION:
178
+ continue
179
+ if self.compile:
180
+ bytecode_files.append(
181
+ importlib.util.cache_from_source(py_file, optimization='')
182
+ )
183
+ if self.optimize > 0:
184
+ bytecode_files.append(
185
+ importlib.util.cache_from_source(
186
+ py_file, optimization=self.optimize
187
+ )
188
+ )
189
+
190
+ return bytecode_files
191
+
192
+ # -- External interface --------------------------------------------
193
+ # (called by outsiders)
194
+
195
+ def get_outputs(self):
196
+ """Return the list of files that would be installed if this command
197
+ were actually run. Not affected by the "dry-run" flag or whether
198
+ modules have actually been built yet.
199
+ """
200
+ pure_outputs = self._mutate_outputs(
201
+ self.distribution.has_pure_modules(),
202
+ 'build_py',
203
+ 'build_lib',
204
+ self.install_dir,
205
+ )
206
+ if self.compile:
207
+ bytecode_outputs = self._bytecode_filenames(pure_outputs)
208
+ else:
209
+ bytecode_outputs = []
210
+
211
+ ext_outputs = self._mutate_outputs(
212
+ self.distribution.has_ext_modules(),
213
+ 'build_ext',
214
+ 'build_lib',
215
+ self.install_dir,
216
+ )
217
+
218
+ return pure_outputs + bytecode_outputs + ext_outputs
219
+
220
+ def get_inputs(self):
221
+ """Get the list of files that are input to this command, ie. the
222
+ files that get installed as they are named in the build tree.
223
+ The files in this list correspond one-to-one to the output
224
+ filenames returned by 'get_outputs()'.
225
+ """
226
+ inputs = []
227
+
228
+ if self.distribution.has_pure_modules():
229
+ build_py = self.get_finalized_command('build_py')
230
+ inputs.extend(build_py.get_outputs())
231
+
232
+ if self.distribution.has_ext_modules():
233
+ build_ext = self.get_finalized_command('build_ext')
234
+ inputs.extend(build_ext.get_outputs())
235
+
236
+ return inputs
python/Lib/site-packages/setuptools/_distutils/command/install_scripts.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install_scripts
2
+
3
+ Implements the Distutils 'install_scripts' command, for installing
4
+ Python scripts."""
5
+
6
+ # contributed by Bastian Kleineidam
7
+
8
+ import os
9
+ from distutils._log import log
10
+ from stat import ST_MODE
11
+ from typing import ClassVar
12
+
13
+ from ..core import Command
14
+
15
+
16
+ class install_scripts(Command):
17
+ description = "install scripts (Python or otherwise)"
18
+
19
+ user_options = [
20
+ ('install-dir=', 'd', "directory to install scripts to"),
21
+ ('build-dir=', 'b', "build directory (where to install from)"),
22
+ ('force', 'f', "force installation (overwrite existing files)"),
23
+ ('skip-build', None, "skip the build steps"),
24
+ ]
25
+
26
+ boolean_options: ClassVar[list[str]] = ['force', 'skip-build']
27
+
28
+ def initialize_options(self):
29
+ self.install_dir = None
30
+ self.force = False
31
+ self.build_dir = None
32
+ self.skip_build = None
33
+
34
+ def finalize_options(self) -> None:
35
+ self.set_undefined_options('build', ('build_scripts', 'build_dir'))
36
+ self.set_undefined_options(
37
+ 'install',
38
+ ('install_scripts', 'install_dir'),
39
+ ('force', 'force'),
40
+ ('skip_build', 'skip_build'),
41
+ )
42
+
43
+ def run(self) -> None:
44
+ if not self.skip_build:
45
+ self.run_command('build_scripts')
46
+ self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
47
+ if os.name == 'posix':
48
+ # Set the executable bits (owner, group, and world) on
49
+ # all the scripts we just installed.
50
+ for file in self.get_outputs():
51
+ mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777
52
+ log.info("changing mode of %s to %o", file, mode)
53
+ os.chmod(file, mode)
54
+
55
+ def get_inputs(self):
56
+ return self.distribution.scripts or []
57
+
58
+ def get_outputs(self):
59
+ return self.outfiles or []
python/Lib/site-packages/setuptools/_distutils/command/sdist.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.sdist
2
+
3
+ Implements the Distutils 'sdist' command (create a source distribution)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import sys
9
+ from collections.abc import Callable
10
+ from distutils import archive_util, dir_util, file_util
11
+ from distutils._log import log
12
+ from glob import glob
13
+ from itertools import filterfalse
14
+ from typing import ClassVar
15
+
16
+ from ..core import Command
17
+ from ..errors import DistutilsOptionError, DistutilsTemplateError
18
+ from ..filelist import FileList
19
+ from ..text_file import TextFile
20
+ from ..util import convert_path
21
+
22
+
23
+ def show_formats():
24
+ """Print all possible values for the 'formats' option (used by
25
+ the "--help-formats" command-line option).
26
+ """
27
+ from ..archive_util import ARCHIVE_FORMATS
28
+ from ..fancy_getopt import FancyGetopt
29
+
30
+ formats = sorted(
31
+ ("formats=" + format, None, ARCHIVE_FORMATS[format][2])
32
+ for format in ARCHIVE_FORMATS.keys()
33
+ )
34
+ FancyGetopt(formats).print_help("List of available source distribution formats:")
35
+
36
+
37
+ class sdist(Command):
38
+ description = "create a source distribution (tarball, zip file, etc.)"
39
+
40
+ def checking_metadata(self) -> bool:
41
+ """Callable used for the check sub-command.
42
+
43
+ Placed here so user_options can view it"""
44
+ return self.metadata_check
45
+
46
+ user_options = [
47
+ ('template=', 't', "name of manifest template file [default: MANIFEST.in]"),
48
+ ('manifest=', 'm', "name of manifest file [default: MANIFEST]"),
49
+ (
50
+ 'use-defaults',
51
+ None,
52
+ "include the default file set in the manifest "
53
+ "[default; disable with --no-defaults]",
54
+ ),
55
+ ('no-defaults', None, "don't include the default file set"),
56
+ (
57
+ 'prune',
58
+ None,
59
+ "specifically exclude files/directories that should not be "
60
+ "distributed (build tree, RCS/CVS dirs, etc.) "
61
+ "[default; disable with --no-prune]",
62
+ ),
63
+ ('no-prune', None, "don't automatically exclude anything"),
64
+ (
65
+ 'manifest-only',
66
+ 'o',
67
+ "just regenerate the manifest and then stop (implies --force-manifest)",
68
+ ),
69
+ (
70
+ 'force-manifest',
71
+ 'f',
72
+ "forcibly regenerate the manifest and carry on as usual. "
73
+ "Deprecated: now the manifest is always regenerated.",
74
+ ),
75
+ ('formats=', None, "formats for source distribution (comma-separated list)"),
76
+ (
77
+ 'keep-temp',
78
+ 'k',
79
+ "keep the distribution tree around after creating " + "archive file(s)",
80
+ ),
81
+ (
82
+ 'dist-dir=',
83
+ 'd',
84
+ "directory to put the source distribution archive(s) in [default: dist]",
85
+ ),
86
+ (
87
+ 'metadata-check',
88
+ None,
89
+ "Ensure that all required elements of meta-data "
90
+ "are supplied. Warn if any missing. [default]",
91
+ ),
92
+ (
93
+ 'owner=',
94
+ 'u',
95
+ "Owner name used when creating a tar file [default: current user]",
96
+ ),
97
+ (
98
+ 'group=',
99
+ 'g',
100
+ "Group name used when creating a tar file [default: current group]",
101
+ ),
102
+ ]
103
+
104
+ boolean_options: ClassVar[list[str]] = [
105
+ 'use-defaults',
106
+ 'prune',
107
+ 'manifest-only',
108
+ 'force-manifest',
109
+ 'keep-temp',
110
+ 'metadata-check',
111
+ ]
112
+
113
+ help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [
114
+ ('help-formats', None, "list available distribution formats", show_formats),
115
+ ]
116
+
117
+ negative_opt: ClassVar[dict[str, str]] = {
118
+ 'no-defaults': 'use-defaults',
119
+ 'no-prune': 'prune',
120
+ }
121
+
122
+ sub_commands = [('check', checking_metadata)]
123
+
124
+ READMES: ClassVar[tuple[str, ...]] = ('README', 'README.txt', 'README.rst')
125
+
126
+ def initialize_options(self):
127
+ # 'template' and 'manifest' are, respectively, the names of
128
+ # the manifest template and manifest file.
129
+ self.template = None
130
+ self.manifest = None
131
+
132
+ # 'use_defaults': if true, we will include the default file set
133
+ # in the manifest
134
+ self.use_defaults = True
135
+ self.prune = True
136
+
137
+ self.manifest_only = False
138
+ self.force_manifest = False
139
+
140
+ self.formats = ['gztar']
141
+ self.keep_temp = False
142
+ self.dist_dir = None
143
+
144
+ self.archive_files = None
145
+ self.metadata_check = True
146
+ self.owner = None
147
+ self.group = None
148
+
149
+ def finalize_options(self) -> None:
150
+ if self.manifest is None:
151
+ self.manifest = "MANIFEST"
152
+ if self.template is None:
153
+ self.template = "MANIFEST.in"
154
+
155
+ self.ensure_string_list('formats')
156
+
157
+ bad_format = archive_util.check_archive_formats(self.formats)
158
+ if bad_format:
159
+ raise DistutilsOptionError(f"unknown archive format '{bad_format}'")
160
+
161
+ if self.dist_dir is None:
162
+ self.dist_dir = "dist"
163
+
164
+ def run(self) -> None:
165
+ # 'filelist' contains the list of files that will make up the
166
+ # manifest
167
+ self.filelist = FileList()
168
+
169
+ # Run sub commands
170
+ for cmd_name in self.get_sub_commands():
171
+ self.run_command(cmd_name)
172
+
173
+ # Do whatever it takes to get the list of files to process
174
+ # (process the manifest template, read an existing manifest,
175
+ # whatever). File list is accumulated in 'self.filelist'.
176
+ self.get_file_list()
177
+
178
+ # If user just wanted us to regenerate the manifest, stop now.
179
+ if self.manifest_only:
180
+ return
181
+
182
+ # Otherwise, go ahead and create the source distribution tarball,
183
+ # or zipfile, or whatever.
184
+ self.make_distribution()
185
+
186
+ def get_file_list(self) -> None:
187
+ """Figure out the list of files to include in the source
188
+ distribution, and put it in 'self.filelist'. This might involve
189
+ reading the manifest template (and writing the manifest), or just
190
+ reading the manifest, or just using the default file set -- it all
191
+ depends on the user's options.
192
+ """
193
+ # new behavior when using a template:
194
+ # the file list is recalculated every time because
195
+ # even if MANIFEST.in or setup.py are not changed
196
+ # the user might have added some files in the tree that
197
+ # need to be included.
198
+ #
199
+ # This makes --force the default and only behavior with templates.
200
+ template_exists = os.path.isfile(self.template)
201
+ if not template_exists and self._manifest_is_not_generated():
202
+ self.read_manifest()
203
+ self.filelist.sort()
204
+ self.filelist.remove_duplicates()
205
+ return
206
+
207
+ if not template_exists:
208
+ self.warn(
209
+ ("manifest template '%s' does not exist " + "(using default file list)")
210
+ % self.template
211
+ )
212
+ self.filelist.findall()
213
+
214
+ if self.use_defaults:
215
+ self.add_defaults()
216
+
217
+ if template_exists:
218
+ self.read_template()
219
+
220
+ if self.prune:
221
+ self.prune_file_list()
222
+
223
+ self.filelist.sort()
224
+ self.filelist.remove_duplicates()
225
+ self.write_manifest()
226
+
227
+ def add_defaults(self) -> None:
228
+ """Add all the default files to self.filelist:
229
+ - README or README.txt
230
+ - setup.py
231
+ - tests/test*.py and test/test*.py
232
+ - all pure Python modules mentioned in setup script
233
+ - all files pointed by package_data (build_py)
234
+ - all files defined in data_files.
235
+ - all files defined as scripts.
236
+ - all C sources listed as part of extensions or C libraries
237
+ in the setup script (doesn't catch C headers!)
238
+ Warns if (README or README.txt) or setup.py are missing; everything
239
+ else is optional.
240
+ """
241
+ self._add_defaults_standards()
242
+ self._add_defaults_optional()
243
+ self._add_defaults_python()
244
+ self._add_defaults_data_files()
245
+ self._add_defaults_ext()
246
+ self._add_defaults_c_libs()
247
+ self._add_defaults_scripts()
248
+
249
+ @staticmethod
250
+ def _cs_path_exists(fspath):
251
+ """
252
+ Case-sensitive path existence check
253
+
254
+ >>> sdist._cs_path_exists(__file__)
255
+ True
256
+ >>> sdist._cs_path_exists(__file__.upper())
257
+ False
258
+ """
259
+ if not os.path.exists(fspath):
260
+ return False
261
+ # make absolute so we always have a directory
262
+ abspath = os.path.abspath(fspath)
263
+ directory, filename = os.path.split(abspath)
264
+ return filename in os.listdir(directory)
265
+
266
+ def _add_defaults_standards(self):
267
+ standards = [self.READMES, self.distribution.script_name]
268
+ for fn in standards:
269
+ if isinstance(fn, tuple):
270
+ alts = fn
271
+ got_it = False
272
+ for fn in alts:
273
+ if self._cs_path_exists(fn):
274
+ got_it = True
275
+ self.filelist.append(fn)
276
+ break
277
+
278
+ if not got_it:
279
+ self.warn(
280
+ "standard file not found: should have one of " + ', '.join(alts)
281
+ )
282
+ else:
283
+ if self._cs_path_exists(fn):
284
+ self.filelist.append(fn)
285
+ else:
286
+ self.warn(f"standard file '{fn}' not found")
287
+
288
+ def _add_defaults_optional(self):
289
+ optional = ['tests/test*.py', 'test/test*.py', 'setup.cfg']
290
+ for pattern in optional:
291
+ files = filter(os.path.isfile, glob(pattern))
292
+ self.filelist.extend(files)
293
+
294
+ def _add_defaults_python(self):
295
+ # build_py is used to get:
296
+ # - python modules
297
+ # - files defined in package_data
298
+ build_py = self.get_finalized_command('build_py')
299
+
300
+ # getting python files
301
+ if self.distribution.has_pure_modules():
302
+ self.filelist.extend(build_py.get_source_files())
303
+
304
+ # getting package_data files
305
+ # (computed in build_py.data_files by build_py.finalize_options)
306
+ for _pkg, src_dir, _build_dir, filenames in build_py.data_files:
307
+ for filename in filenames:
308
+ self.filelist.append(os.path.join(src_dir, filename))
309
+
310
+ def _add_defaults_data_files(self):
311
+ # getting distribution.data_files
312
+ if self.distribution.has_data_files():
313
+ for item in self.distribution.data_files:
314
+ if isinstance(item, str):
315
+ # plain file
316
+ item = convert_path(item)
317
+ if os.path.isfile(item):
318
+ self.filelist.append(item)
319
+ else:
320
+ # a (dirname, filenames) tuple
321
+ dirname, filenames = item
322
+ for f in filenames:
323
+ f = convert_path(f)
324
+ if os.path.isfile(f):
325
+ self.filelist.append(f)
326
+
327
+ def _add_defaults_ext(self):
328
+ if self.distribution.has_ext_modules():
329
+ build_ext = self.get_finalized_command('build_ext')
330
+ self.filelist.extend(build_ext.get_source_files())
331
+
332
+ def _add_defaults_c_libs(self):
333
+ if self.distribution.has_c_libraries():
334
+ build_clib = self.get_finalized_command('build_clib')
335
+ self.filelist.extend(build_clib.get_source_files())
336
+
337
+ def _add_defaults_scripts(self):
338
+ if self.distribution.has_scripts():
339
+ build_scripts = self.get_finalized_command('build_scripts')
340
+ self.filelist.extend(build_scripts.get_source_files())
341
+
342
+ def read_template(self) -> None:
343
+ """Read and parse manifest template file named by self.template.
344
+
345
+ (usually "MANIFEST.in") The parsing and processing is done by
346
+ 'self.filelist', which updates itself accordingly.
347
+ """
348
+ log.info("reading manifest template '%s'", self.template)
349
+ template = TextFile(
350
+ self.template,
351
+ strip_comments=True,
352
+ skip_blanks=True,
353
+ join_lines=True,
354
+ lstrip_ws=True,
355
+ rstrip_ws=True,
356
+ collapse_join=True,
357
+ )
358
+
359
+ try:
360
+ while True:
361
+ line = template.readline()
362
+ if line is None: # end of file
363
+ break
364
+
365
+ try:
366
+ self.filelist.process_template_line(line)
367
+ # the call above can raise a DistutilsTemplateError for
368
+ # malformed lines, or a ValueError from the lower-level
369
+ # convert_path function
370
+ except (DistutilsTemplateError, ValueError) as msg:
371
+ self.warn(
372
+ f"{template.filename}, line {int(template.current_line)}: {msg}"
373
+ )
374
+ finally:
375
+ template.close()
376
+
377
+ def prune_file_list(self) -> None:
378
+ """Prune off branches that might slip into the file list as created
379
+ by 'read_template()', but really don't belong there:
380
+ * the build tree (typically "build")
381
+ * the release tree itself (only an issue if we ran "sdist"
382
+ previously with --keep-temp, or it aborted)
383
+ * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
384
+ """
385
+ build = self.get_finalized_command('build')
386
+ base_dir = self.distribution.get_fullname()
387
+
388
+ self.filelist.exclude_pattern(None, prefix=os.fspath(build.build_base))
389
+ self.filelist.exclude_pattern(None, prefix=base_dir)
390
+
391
+ if sys.platform == 'win32':
392
+ seps = r'/|\\'
393
+ else:
394
+ seps = '/'
395
+
396
+ vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs']
397
+ vcs_ptrn = r'(^|{})({})({}).*'.format(seps, '|'.join(vcs_dirs), seps)
398
+ self.filelist.exclude_pattern(vcs_ptrn, is_regex=True)
399
+
400
+ def write_manifest(self) -> None:
401
+ """Write the file list in 'self.filelist' (presumably as filled in
402
+ by 'add_defaults()' and 'read_template()') to the manifest file
403
+ named by 'self.manifest'.
404
+ """
405
+ if self._manifest_is_not_generated():
406
+ log.info(
407
+ f"not writing to manually maintained manifest file '{self.manifest}'"
408
+ )
409
+ return
410
+
411
+ content = self.filelist.files[:]
412
+ content.insert(0, '# file GENERATED by distutils, do NOT edit')
413
+ self.execute(
414
+ file_util.write_file,
415
+ (self.manifest, content),
416
+ f"writing manifest file '{self.manifest}'",
417
+ )
418
+
419
+ def _manifest_is_not_generated(self):
420
+ # check for special comment used in 3.1.3 and higher
421
+ if not os.path.isfile(self.manifest):
422
+ return False
423
+
424
+ with open(self.manifest, encoding='utf-8') as fp:
425
+ first_line = next(fp)
426
+ return first_line != '# file GENERATED by distutils, do NOT edit\n'
427
+
428
+ def read_manifest(self) -> None:
429
+ """Read the manifest file (named by 'self.manifest') and use it to
430
+ fill in 'self.filelist', the list of files to include in the source
431
+ distribution.
432
+ """
433
+ log.info("reading manifest file '%s'", self.manifest)
434
+ with open(self.manifest, encoding='utf-8') as lines:
435
+ self.filelist.extend(
436
+ # ignore comments and blank lines
437
+ filter(None, filterfalse(is_comment, map(str.strip, lines)))
438
+ )
439
+
440
+ def make_release_tree(self, base_dir, files) -> None:
441
+ """Create the directory tree that will become the source
442
+ distribution archive. All directories implied by the filenames in
443
+ 'files' are created under 'base_dir', and then we hard link or copy
444
+ (if hard linking is unavailable) those files into place.
445
+ Essentially, this duplicates the developer's source tree, but in a
446
+ directory named after the distribution, containing only the files
447
+ to be distributed.
448
+ """
449
+ # Create all the directories under 'base_dir' necessary to
450
+ # put 'files' there; the 'mkpath()' is just so we don't die
451
+ # if the manifest happens to be empty.
452
+ self.mkpath(base_dir)
453
+ dir_util.create_tree(base_dir, files)
454
+
455
+ # And walk over the list of files, either making a hard link (if
456
+ # os.link exists) to each one that doesn't already exist in its
457
+ # corresponding location under 'base_dir', or copying each file
458
+ # that's out-of-date in 'base_dir'. (Usually, all files will be
459
+ # out-of-date, because by default we blow away 'base_dir' when
460
+ # we're done making the distribution archives.)
461
+
462
+ if hasattr(os, 'link'): # can make hard links on this system
463
+ link = 'hard'
464
+ msg = f"making hard links in {base_dir}..."
465
+ else: # nope, have to copy
466
+ link = None
467
+ msg = f"copying files to {base_dir}..."
468
+
469
+ if not files:
470
+ log.warning("no files to distribute -- empty manifest?")
471
+ else:
472
+ log.info(msg)
473
+ for file in files:
474
+ if not os.path.isfile(file):
475
+ log.warning("'%s' not a regular file -- skipping", file)
476
+ else:
477
+ dest = os.path.join(base_dir, file)
478
+ self.copy_file(file, dest, link=link)
479
+
480
+ self.distribution.metadata.write_pkg_info(base_dir)
481
+
482
+ def make_distribution(self) -> None:
483
+ """Create the source distribution(s). First, we create the release
484
+ tree with 'make_release_tree()'; then, we create all required
485
+ archive files (according to 'self.formats') from the release tree.
486
+ Finally, we clean up by blowing away the release tree (unless
487
+ 'self.keep_temp' is true). The list of archive files created is
488
+ stored so it can be retrieved later by 'get_archive_files()'.
489
+ """
490
+ # Don't warn about missing meta-data here -- should be (and is!)
491
+ # done elsewhere.
492
+ base_dir = self.distribution.get_fullname()
493
+ base_name = os.path.join(self.dist_dir, base_dir)
494
+
495
+ self.make_release_tree(base_dir, self.filelist.files)
496
+ archive_files = [] # remember names of files we create
497
+ # tar archive must be created last to avoid overwrite and remove
498
+ if 'tar' in self.formats:
499
+ self.formats.append(self.formats.pop(self.formats.index('tar')))
500
+
501
+ for fmt in self.formats:
502
+ file = self.make_archive(
503
+ base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group
504
+ )
505
+ archive_files.append(file)
506
+ self.distribution.dist_files.append(('sdist', '', file))
507
+
508
+ self.archive_files = archive_files
509
+
510
+ if not self.keep_temp:
511
+ dir_util.remove_tree(base_dir)
512
+
513
+ def get_archive_files(self):
514
+ """Return the list of archive files created when the command
515
+ was run, or None if the command hasn't run yet.
516
+ """
517
+ return self.archive_files
518
+
519
+
520
+ def is_comment(line: str) -> bool:
521
+ return line.startswith('#')
python/Lib/site-packages/setuptools/_distutils/compat/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+ from typing import TypeVar
5
+
6
+ _IterableT = TypeVar("_IterableT", bound="Iterable[str]")
7
+
8
+
9
+ def consolidate_linker_args(args: _IterableT) -> _IterableT | str:
10
+ """
11
+ Ensure the return value is a string for backward compatibility.
12
+
13
+ Retain until at least 2025-04-31. See pypa/distutils#246
14
+ """
15
+
16
+ if not all(arg.startswith('-Wl,') for arg in args):
17
+ return args
18
+ return '-Wl,' + ','.join(arg.removeprefix('-Wl,') for arg in args)
python/Lib/site-packages/setuptools/_distutils/compat/numpy.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # required for older numpy versions on Pythons prior to 3.12; see pypa/setuptools#4876
2
+ from ..compilers.C.base import _default_compilers, compiler_class # noqa: F401
python/Lib/site-packages/setuptools/_distutils/compat/py39.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import itertools
3
+ import platform
4
+ import sys
5
+
6
+
7
+ def add_ext_suffix_39(vars):
8
+ """
9
+ Ensure vars contains 'EXT_SUFFIX'. pypa/distutils#130
10
+ """
11
+ import _imp
12
+
13
+ ext_suffix = _imp.extension_suffixes()[0]
14
+ vars.update(
15
+ EXT_SUFFIX=ext_suffix,
16
+ # sysconfig sets SO to match EXT_SUFFIX, so maintain
17
+ # that expectation.
18
+ # https://github.com/python/cpython/blob/785cc6770588de087d09e89a69110af2542be208/Lib/sysconfig.py#L671-L673
19
+ SO=ext_suffix,
20
+ )
21
+
22
+
23
+ needs_ext_suffix = sys.version_info < (3, 10) and platform.system() == 'Windows'
24
+ add_ext_suffix = add_ext_suffix_39 if needs_ext_suffix else lambda vars: None
25
+
26
+
27
+ # from more_itertools
28
+ class UnequalIterablesError(ValueError):
29
+ def __init__(self, details=None):
30
+ msg = 'Iterables have different lengths'
31
+ if details is not None:
32
+ msg += (': index 0 has length {}; index {} has length {}').format(*details)
33
+
34
+ super().__init__(msg)
35
+
36
+
37
+ # from more_itertools
38
+ def _zip_equal_generator(iterables):
39
+ _marker = object()
40
+ for combo in itertools.zip_longest(*iterables, fillvalue=_marker):
41
+ for val in combo:
42
+ if val is _marker:
43
+ raise UnequalIterablesError()
44
+ yield combo
45
+
46
+
47
+ # from more_itertools
48
+ def _zip_equal(*iterables):
49
+ # Check whether the iterables are all the same size.
50
+ try:
51
+ first_size = len(iterables[0])
52
+ for i, it in enumerate(iterables[1:], 1):
53
+ size = len(it)
54
+ if size != first_size:
55
+ raise UnequalIterablesError(details=(first_size, i, size))
56
+ # All sizes are equal, we can use the built-in zip.
57
+ return zip(*iterables)
58
+ # If any one of the iterables didn't have a length, start reading
59
+ # them until one runs out.
60
+ except TypeError:
61
+ return _zip_equal_generator(iterables)
62
+
63
+
64
+ zip_strict = (
65
+ _zip_equal if sys.version_info < (3, 10) else functools.partial(zip, strict=True)
66
+ )
python/Lib/site-packages/setuptools/_distutils/tests/support.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support code for distutils test cases."""
2
+
3
+ import itertools
4
+ import os
5
+ import pathlib
6
+ import shutil
7
+ import sys
8
+ import sysconfig
9
+ import tempfile
10
+ from distutils.core import Distribution
11
+
12
+ import pytest
13
+ from more_itertools import always_iterable
14
+
15
+
16
+ @pytest.mark.usefixtures('distutils_managed_tempdir')
17
+ class TempdirManager:
18
+ """
19
+ Mix-in class that handles temporary directories for test cases.
20
+ """
21
+
22
+ def mkdtemp(self):
23
+ """Create a temporary directory that will be cleaned up.
24
+
25
+ Returns the path of the directory.
26
+ """
27
+ d = tempfile.mkdtemp()
28
+ self.tempdirs.append(d)
29
+ return d
30
+
31
+ def write_file(self, path, content='xxx'):
32
+ """Writes a file in the given path.
33
+
34
+ path can be a string or a sequence.
35
+ """
36
+ pathlib.Path(*always_iterable(path)).write_text(content, encoding='utf-8')
37
+
38
+ def create_dist(self, pkg_name='foo', **kw):
39
+ """Will generate a test environment.
40
+
41
+ This function creates:
42
+ - a Distribution instance using keywords
43
+ - a temporary directory with a package structure
44
+
45
+ It returns the package directory and the distribution
46
+ instance.
47
+ """
48
+ tmp_dir = self.mkdtemp()
49
+ pkg_dir = os.path.join(tmp_dir, pkg_name)
50
+ os.mkdir(pkg_dir)
51
+ dist = Distribution(attrs=kw)
52
+
53
+ return pkg_dir, dist
54
+
55
+
56
+ class DummyCommand:
57
+ """Class to store options for retrieval via set_undefined_options()."""
58
+
59
+ def __init__(self, **kwargs):
60
+ vars(self).update(kwargs)
61
+
62
+ def ensure_finalized(self):
63
+ pass
64
+
65
+
66
+ def copy_xxmodule_c(directory):
67
+ """Helper for tests that need the xxmodule.c source file.
68
+
69
+ Example use:
70
+
71
+ def test_compile(self):
72
+ copy_xxmodule_c(self.tmpdir)
73
+ self.assertIn('xxmodule.c', os.listdir(self.tmpdir))
74
+
75
+ If the source file can be found, it will be copied to *directory*. If not,
76
+ the test will be skipped. Errors during copy are not caught.
77
+ """
78
+ shutil.copy(_get_xxmodule_path(), os.path.join(directory, 'xxmodule.c'))
79
+
80
+
81
+ def _get_xxmodule_path():
82
+ source_name = 'xxmodule.c' if sys.version_info > (3, 9) else 'xxmodule-3.8.c'
83
+ return os.path.join(os.path.dirname(__file__), source_name)
84
+
85
+
86
+ def fixup_build_ext(cmd):
87
+ """Function needed to make build_ext tests pass.
88
+
89
+ When Python was built with --enable-shared on Unix, -L. is not enough to
90
+ find libpython<blah>.so, because regrtest runs in a tempdir, not in the
91
+ source directory where the .so lives.
92
+
93
+ When Python was built with in debug mode on Windows, build_ext commands
94
+ need their debug attribute set, and it is not done automatically for
95
+ some reason.
96
+
97
+ This function handles both of these things. Example use:
98
+
99
+ cmd = build_ext(dist)
100
+ support.fixup_build_ext(cmd)
101
+ cmd.ensure_finalized()
102
+
103
+ Unlike most other Unix platforms, Mac OS X embeds absolute paths
104
+ to shared libraries into executables, so the fixup is not needed there.
105
+ """
106
+ if os.name == 'nt':
107
+ cmd.debug = sys.executable.endswith('_d.exe')
108
+ elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
109
+ # To further add to the shared builds fun on Unix, we can't just add
110
+ # library_dirs to the Extension() instance because that doesn't get
111
+ # plumbed through to the final compiler command.
112
+ runshared = sysconfig.get_config_var('RUNSHARED')
113
+ if runshared is None:
114
+ cmd.library_dirs = ['.']
115
+ else:
116
+ if sys.platform == 'darwin':
117
+ cmd.library_dirs = []
118
+ else:
119
+ name, equals, value = runshared.partition('=')
120
+ cmd.library_dirs = [d for d in value.split(os.pathsep) if d]
121
+
122
+
123
+ def combine_markers(cls):
124
+ """
125
+ pytest will honor markers as found on the class, but when
126
+ markers are on multiple subclasses, only one appears. Use
127
+ this decorator to combine those markers.
128
+ """
129
+ cls.pytestmark = [
130
+ mark
131
+ for base in itertools.chain([cls], cls.__bases__)
132
+ for mark in getattr(base, 'pytestmark', [])
133
+ ]
134
+ return cls
python/Lib/site-packages/setuptools/_distutils/tests/test_archive_util.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.archive_util."""
2
+
3
+ import functools
4
+ import operator
5
+ import os
6
+ import pathlib
7
+ import sys
8
+ import tarfile
9
+ from distutils import archive_util
10
+ from distutils.archive_util import (
11
+ ARCHIVE_FORMATS,
12
+ check_archive_formats,
13
+ make_archive,
14
+ make_tarball,
15
+ make_zipfile,
16
+ )
17
+ from distutils.spawn import spawn
18
+ from distutils.tests import support
19
+ from os.path import splitdrive
20
+
21
+ import path
22
+ import pytest
23
+ from test.support import patch
24
+
25
+ from .unix_compat import UID_0_SUPPORT, grp, pwd, require_uid_0, require_unix_id
26
+
27
+
28
+ def can_fs_encode(filename):
29
+ """
30
+ Return True if the filename can be saved in the file system.
31
+ """
32
+ if os.path.supports_unicode_filenames:
33
+ return True
34
+ try:
35
+ filename.encode(sys.getfilesystemencoding())
36
+ except UnicodeEncodeError:
37
+ return False
38
+ return True
39
+
40
+
41
+ def all_equal(values):
42
+ return functools.reduce(operator.eq, values)
43
+
44
+
45
+ def same_drive(*paths):
46
+ return all_equal(pathlib.Path(path).drive for path in paths)
47
+
48
+
49
+ class ArchiveUtilTestCase(support.TempdirManager):
50
+ @pytest.mark.usefixtures('needs_zlib')
51
+ def test_make_tarball(self, name='archive'):
52
+ # creating something to tar
53
+ tmpdir = self._create_files()
54
+ self._make_tarball(tmpdir, name, '.tar.gz')
55
+ # trying an uncompressed one
56
+ self._make_tarball(tmpdir, name, '.tar', compress=None)
57
+
58
+ @pytest.mark.usefixtures('needs_zlib')
59
+ def test_make_tarball_gzip(self):
60
+ tmpdir = self._create_files()
61
+ self._make_tarball(tmpdir, 'archive', '.tar.gz', compress='gzip')
62
+
63
+ def test_make_tarball_bzip2(self):
64
+ pytest.importorskip('bz2')
65
+ tmpdir = self._create_files()
66
+ self._make_tarball(tmpdir, 'archive', '.tar.bz2', compress='bzip2')
67
+
68
+ def test_make_tarball_xz(self):
69
+ pytest.importorskip('lzma')
70
+ tmpdir = self._create_files()
71
+ self._make_tarball(tmpdir, 'archive', '.tar.xz', compress='xz')
72
+
73
+ @pytest.mark.skipif("not can_fs_encode('årchiv')")
74
+ def test_make_tarball_latin1(self):
75
+ """
76
+ Mirror test_make_tarball, except filename contains latin characters.
77
+ """
78
+ self.test_make_tarball('årchiv') # note this isn't a real word
79
+
80
+ @pytest.mark.skipif("not can_fs_encode('のアーカイブ')")
81
+ def test_make_tarball_extended(self):
82
+ """
83
+ Mirror test_make_tarball, except filename contains extended
84
+ characters outside the latin charset.
85
+ """
86
+ self.test_make_tarball('のアーカイブ') # japanese for archive
87
+
88
+ def _make_tarball(self, tmpdir, target_name, suffix, **kwargs):
89
+ tmpdir2 = self.mkdtemp()
90
+ if same_drive(tmpdir, tmpdir2):
91
+ pytest.skip("source and target should be on same drive")
92
+
93
+ base_name = os.path.join(tmpdir2, target_name)
94
+
95
+ # working with relative paths to avoid tar warnings
96
+ with path.Path(tmpdir):
97
+ make_tarball(splitdrive(base_name)[1], 'dist', **kwargs)
98
+
99
+ # check if the compressed tarball was created
100
+ tarball = base_name + suffix
101
+ assert os.path.exists(tarball)
102
+ assert self._tarinfo(tarball) == self._created_files
103
+
104
+ def _tarinfo(self, path):
105
+ tar = tarfile.open(path)
106
+ try:
107
+ names = tar.getnames()
108
+ names.sort()
109
+ return names
110
+ finally:
111
+ tar.close()
112
+
113
+ _zip_created_files = [
114
+ 'dist/',
115
+ 'dist/file1',
116
+ 'dist/file2',
117
+ 'dist/sub/',
118
+ 'dist/sub/file3',
119
+ 'dist/sub2/',
120
+ ]
121
+ _created_files = [p.rstrip('/') for p in _zip_created_files]
122
+
123
+ def _create_files(self):
124
+ # creating something to tar
125
+ tmpdir = self.mkdtemp()
126
+ dist = os.path.join(tmpdir, 'dist')
127
+ os.mkdir(dist)
128
+ self.write_file([dist, 'file1'], 'xxx')
129
+ self.write_file([dist, 'file2'], 'xxx')
130
+ os.mkdir(os.path.join(dist, 'sub'))
131
+ self.write_file([dist, 'sub', 'file3'], 'xxx')
132
+ os.mkdir(os.path.join(dist, 'sub2'))
133
+ return tmpdir
134
+
135
+ @pytest.mark.usefixtures('needs_zlib')
136
+ @pytest.mark.skipif("not (shutil.which('tar') and shutil.which('gzip'))")
137
+ def test_tarfile_vs_tar(self):
138
+ tmpdir = self._create_files()
139
+ tmpdir2 = self.mkdtemp()
140
+ base_name = os.path.join(tmpdir2, 'archive')
141
+ old_dir = os.getcwd()
142
+ os.chdir(tmpdir)
143
+ try:
144
+ make_tarball(base_name, 'dist')
145
+ finally:
146
+ os.chdir(old_dir)
147
+
148
+ # check if the compressed tarball was created
149
+ tarball = base_name + '.tar.gz'
150
+ assert os.path.exists(tarball)
151
+
152
+ # now create another tarball using `tar`
153
+ tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
154
+ tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
155
+ gzip_cmd = ['gzip', '-f', '-9', 'archive2.tar']
156
+ old_dir = os.getcwd()
157
+ os.chdir(tmpdir)
158
+ try:
159
+ spawn(tar_cmd)
160
+ spawn(gzip_cmd)
161
+ finally:
162
+ os.chdir(old_dir)
163
+
164
+ assert os.path.exists(tarball2)
165
+ # let's compare both tarballs
166
+ assert self._tarinfo(tarball) == self._created_files
167
+ assert self._tarinfo(tarball2) == self._created_files
168
+
169
+ # trying an uncompressed one
170
+ base_name = os.path.join(tmpdir2, 'archive')
171
+ old_dir = os.getcwd()
172
+ os.chdir(tmpdir)
173
+ try:
174
+ make_tarball(base_name, 'dist', compress=None)
175
+ finally:
176
+ os.chdir(old_dir)
177
+ tarball = base_name + '.tar'
178
+ assert os.path.exists(tarball)
179
+
180
+ @pytest.mark.usefixtures('needs_zlib')
181
+ def test_make_zipfile(self):
182
+ zipfile = pytest.importorskip('zipfile')
183
+ # creating something to tar
184
+ tmpdir = self._create_files()
185
+ base_name = os.path.join(self.mkdtemp(), 'archive')
186
+ with path.Path(tmpdir):
187
+ make_zipfile(base_name, 'dist')
188
+
189
+ # check if the compressed tarball was created
190
+ tarball = base_name + '.zip'
191
+ assert os.path.exists(tarball)
192
+ with zipfile.ZipFile(tarball) as zf:
193
+ assert sorted(zf.namelist()) == self._zip_created_files
194
+
195
+ def test_make_zipfile_no_zlib(self):
196
+ zipfile = pytest.importorskip('zipfile')
197
+ patch(self, archive_util.zipfile, 'zlib', None) # force zlib ImportError
198
+
199
+ called = []
200
+ zipfile_class = zipfile.ZipFile
201
+
202
+ def fake_zipfile(*a, **kw):
203
+ if kw.get('compression', None) == zipfile.ZIP_STORED:
204
+ called.append((a, kw))
205
+ return zipfile_class(*a, **kw)
206
+
207
+ patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile)
208
+
209
+ # create something to tar and compress
210
+ tmpdir = self._create_files()
211
+ base_name = os.path.join(self.mkdtemp(), 'archive')
212
+ with path.Path(tmpdir):
213
+ make_zipfile(base_name, 'dist')
214
+
215
+ tarball = base_name + '.zip'
216
+ assert called == [((tarball, "w"), {'compression': zipfile.ZIP_STORED})]
217
+ assert os.path.exists(tarball)
218
+ with zipfile.ZipFile(tarball) as zf:
219
+ assert sorted(zf.namelist()) == self._zip_created_files
220
+
221
+ def test_check_archive_formats(self):
222
+ assert check_archive_formats(['gztar', 'xxx', 'zip']) == 'xxx'
223
+ assert (
224
+ check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip'])
225
+ is None
226
+ )
227
+
228
+ def test_make_archive(self):
229
+ tmpdir = self.mkdtemp()
230
+ base_name = os.path.join(tmpdir, 'archive')
231
+ with pytest.raises(ValueError):
232
+ make_archive(base_name, 'xxx')
233
+
234
+ def test_make_archive_cwd(self):
235
+ current_dir = os.getcwd()
236
+
237
+ def _breaks(*args, **kw):
238
+ raise RuntimeError()
239
+
240
+ ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file')
241
+ try:
242
+ try:
243
+ make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
244
+ except Exception:
245
+ pass
246
+ assert os.getcwd() == current_dir
247
+ finally:
248
+ ARCHIVE_FORMATS.pop('xxx')
249
+
250
+ def test_make_archive_tar(self):
251
+ base_dir = self._create_files()
252
+ base_name = os.path.join(self.mkdtemp(), 'archive')
253
+ res = make_archive(base_name, 'tar', base_dir, 'dist')
254
+ assert os.path.exists(res)
255
+ assert os.path.basename(res) == 'archive.tar'
256
+ assert self._tarinfo(res) == self._created_files
257
+
258
+ @pytest.mark.usefixtures('needs_zlib')
259
+ def test_make_archive_gztar(self):
260
+ base_dir = self._create_files()
261
+ base_name = os.path.join(self.mkdtemp(), 'archive')
262
+ res = make_archive(base_name, 'gztar', base_dir, 'dist')
263
+ assert os.path.exists(res)
264
+ assert os.path.basename(res) == 'archive.tar.gz'
265
+ assert self._tarinfo(res) == self._created_files
266
+
267
+ def test_make_archive_bztar(self):
268
+ pytest.importorskip('bz2')
269
+ base_dir = self._create_files()
270
+ base_name = os.path.join(self.mkdtemp(), 'archive')
271
+ res = make_archive(base_name, 'bztar', base_dir, 'dist')
272
+ assert os.path.exists(res)
273
+ assert os.path.basename(res) == 'archive.tar.bz2'
274
+ assert self._tarinfo(res) == self._created_files
275
+
276
+ def test_make_archive_xztar(self):
277
+ pytest.importorskip('lzma')
278
+ base_dir = self._create_files()
279
+ base_name = os.path.join(self.mkdtemp(), 'archive')
280
+ res = make_archive(base_name, 'xztar', base_dir, 'dist')
281
+ assert os.path.exists(res)
282
+ assert os.path.basename(res) == 'archive.tar.xz'
283
+ assert self._tarinfo(res) == self._created_files
284
+
285
+ def test_make_archive_owner_group(self):
286
+ # testing make_archive with owner and group, with various combinations
287
+ # this works even if there's not gid/uid support
288
+ if UID_0_SUPPORT:
289
+ group = grp.getgrgid(0)[0]
290
+ owner = pwd.getpwuid(0)[0]
291
+ else:
292
+ group = owner = 'root'
293
+
294
+ base_dir = self._create_files()
295
+ root_dir = self.mkdtemp()
296
+ base_name = os.path.join(self.mkdtemp(), 'archive')
297
+ res = make_archive(
298
+ base_name, 'zip', root_dir, base_dir, owner=owner, group=group
299
+ )
300
+ assert os.path.exists(res)
301
+
302
+ res = make_archive(base_name, 'zip', root_dir, base_dir)
303
+ assert os.path.exists(res)
304
+
305
+ res = make_archive(
306
+ base_name, 'tar', root_dir, base_dir, owner=owner, group=group
307
+ )
308
+ assert os.path.exists(res)
309
+
310
+ res = make_archive(
311
+ base_name, 'tar', root_dir, base_dir, owner='kjhkjhkjg', group='oihohoh'
312
+ )
313
+ assert os.path.exists(res)
314
+
315
+ @pytest.mark.usefixtures('needs_zlib')
316
+ @require_unix_id
317
+ @require_uid_0
318
+ def test_tarfile_root_owner(self):
319
+ tmpdir = self._create_files()
320
+ base_name = os.path.join(self.mkdtemp(), 'archive')
321
+ old_dir = os.getcwd()
322
+ os.chdir(tmpdir)
323
+ group = grp.getgrgid(0)[0]
324
+ owner = pwd.getpwuid(0)[0]
325
+ try:
326
+ archive_name = make_tarball(
327
+ base_name, 'dist', compress=None, owner=owner, group=group
328
+ )
329
+ finally:
330
+ os.chdir(old_dir)
331
+
332
+ # check if the compressed tarball was created
333
+ assert os.path.exists(archive_name)
334
+
335
+ # now checks the rights
336
+ archive = tarfile.open(archive_name)
337
+ try:
338
+ for member in archive.getmembers():
339
+ assert member.uid == 0
340
+ assert member.gid == 0
341
+ finally:
342
+ archive.close()
python/Lib/site-packages/setuptools/_distutils/tests/test_bdist.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.bdist."""
2
+
3
+ from distutils.command.bdist import bdist
4
+ from distutils.tests import support
5
+
6
+
7
+ class TestBuild(support.TempdirManager):
8
+ def test_formats(self):
9
+ # let's create a command and make sure
10
+ # we can set the format
11
+ dist = self.create_dist()[1]
12
+ cmd = bdist(dist)
13
+ cmd.formats = ['gztar']
14
+ cmd.ensure_finalized()
15
+ assert cmd.formats == ['gztar']
16
+
17
+ # what formats does bdist offer?
18
+ formats = [
19
+ 'bztar',
20
+ 'gztar',
21
+ 'rpm',
22
+ 'tar',
23
+ 'xztar',
24
+ 'zip',
25
+ 'ztar',
26
+ ]
27
+ found = sorted(cmd.format_commands)
28
+ assert found == formats
29
+
30
+ def test_skip_build(self):
31
+ # bug #10946: bdist --skip-build should trickle down to subcommands
32
+ dist = self.create_dist()[1]
33
+ cmd = bdist(dist)
34
+ cmd.skip_build = True
35
+ cmd.ensure_finalized()
36
+ dist.command_obj['bdist'] = cmd
37
+
38
+ names = [
39
+ 'bdist_dumb',
40
+ ] # bdist_rpm does not support --skip-build
41
+
42
+ for name in names:
43
+ subcmd = cmd.get_finalized_command(name)
44
+ if getattr(subcmd, '_unsupported', False):
45
+ # command is not supported on this build
46
+ continue
47
+ assert subcmd.skip_build, f'{name} should take --skip-build from bdist'
python/Lib/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.bdist_dumb."""
2
+
3
+ import os
4
+ import sys
5
+ import zipfile
6
+ from distutils.command.bdist_dumb import bdist_dumb
7
+ from distutils.core import Distribution
8
+ from distutils.tests import support
9
+
10
+ import pytest
11
+
12
+ SETUP_PY = """\
13
+ from distutils.core import setup
14
+ import foo
15
+
16
+ setup(name='foo', version='0.1', py_modules=['foo'],
17
+ url='xxx', author='xxx', author_email='xxx')
18
+
19
+ """
20
+
21
+
22
+ @support.combine_markers
23
+ @pytest.mark.usefixtures('save_env')
24
+ @pytest.mark.usefixtures('save_argv')
25
+ @pytest.mark.usefixtures('save_cwd')
26
+ class TestBuildDumb(
27
+ support.TempdirManager,
28
+ ):
29
+ @pytest.mark.usefixtures('needs_zlib')
30
+ def test_simple_built(self):
31
+ # let's create a simple package
32
+ tmp_dir = self.mkdtemp()
33
+ pkg_dir = os.path.join(tmp_dir, 'foo')
34
+ os.mkdir(pkg_dir)
35
+ self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
36
+ self.write_file((pkg_dir, 'foo.py'), '#')
37
+ self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
38
+ self.write_file((pkg_dir, 'README'), '')
39
+
40
+ dist = Distribution({
41
+ 'name': 'foo',
42
+ 'version': '0.1',
43
+ 'py_modules': ['foo'],
44
+ 'url': 'xxx',
45
+ 'author': 'xxx',
46
+ 'author_email': 'xxx',
47
+ })
48
+ dist.script_name = 'setup.py'
49
+ os.chdir(pkg_dir)
50
+
51
+ sys.argv = ['setup.py']
52
+ cmd = bdist_dumb(dist)
53
+
54
+ # so the output is the same no matter
55
+ # what is the platform
56
+ cmd.format = 'zip'
57
+
58
+ cmd.ensure_finalized()
59
+ cmd.run()
60
+
61
+ # see what we have
62
+ dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
63
+ base = f"{dist.get_fullname()}.{cmd.plat_name}.zip"
64
+
65
+ assert dist_created == [base]
66
+
67
+ # now let's check what we have in the zip file
68
+ fp = zipfile.ZipFile(os.path.join('dist', base))
69
+ try:
70
+ contents = fp.namelist()
71
+ finally:
72
+ fp.close()
73
+
74
+ contents = sorted(filter(None, map(os.path.basename, contents)))
75
+ wanted = ['foo-0.1-py{}.{}.egg-info'.format(*sys.version_info[:2]), 'foo.py']
76
+ if not sys.dont_write_bytecode:
77
+ wanted.append(f'foo.{sys.implementation.cache_tag}.pyc')
78
+ assert contents == sorted(wanted)
python/Lib/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.bdist_rpm."""
2
+
3
+ import os
4
+ import shutil # noqa: F401
5
+ import sys
6
+ from distutils.command.bdist_rpm import bdist_rpm
7
+ from distutils.core import Distribution
8
+ from distutils.tests import support
9
+
10
+ import pytest
11
+ from test.support import requires_zlib
12
+
13
+ SETUP_PY = """\
14
+ from distutils.core import setup
15
+ import foo
16
+
17
+ setup(name='foo', version='0.1', py_modules=['foo'],
18
+ url='xxx', author='xxx', author_email='xxx')
19
+
20
+ """
21
+
22
+
23
+ @pytest.fixture(autouse=True)
24
+ def sys_executable_encodable():
25
+ try:
26
+ sys.executable.encode('UTF-8')
27
+ except UnicodeEncodeError:
28
+ pytest.skip("sys.executable is not encodable to UTF-8")
29
+
30
+
31
+ mac_woes = pytest.mark.skipif(
32
+ "not sys.platform.startswith('linux')",
33
+ reason='spurious sdtout/stderr output under macOS',
34
+ )
35
+
36
+
37
+ @pytest.mark.usefixtures('save_env')
38
+ @pytest.mark.usefixtures('save_argv')
39
+ @pytest.mark.usefixtures('save_cwd')
40
+ class TestBuildRpm(
41
+ support.TempdirManager,
42
+ ):
43
+ @mac_woes
44
+ @requires_zlib()
45
+ @pytest.mark.skipif("not shutil.which('rpm')")
46
+ @pytest.mark.skipif("not shutil.which('rpmbuild')")
47
+ def test_quiet(self):
48
+ # let's create a package
49
+ tmp_dir = self.mkdtemp()
50
+ os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation
51
+ pkg_dir = os.path.join(tmp_dir, 'foo')
52
+ os.mkdir(pkg_dir)
53
+ self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
54
+ self.write_file((pkg_dir, 'foo.py'), '#')
55
+ self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
56
+ self.write_file((pkg_dir, 'README'), '')
57
+
58
+ dist = Distribution({
59
+ 'name': 'foo',
60
+ 'version': '0.1',
61
+ 'py_modules': ['foo'],
62
+ 'url': 'xxx',
63
+ 'author': 'xxx',
64
+ 'author_email': 'xxx',
65
+ })
66
+ dist.script_name = 'setup.py'
67
+ os.chdir(pkg_dir)
68
+
69
+ sys.argv = ['setup.py']
70
+ cmd = bdist_rpm(dist)
71
+ cmd.fix_python = True
72
+
73
+ # running in quiet mode
74
+ cmd.quiet = True
75
+ cmd.ensure_finalized()
76
+ cmd.run()
77
+
78
+ dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
79
+ assert 'foo-0.1-1.noarch.rpm' in dist_created
80
+
81
+ # bug #2945: upload ignores bdist_rpm files
82
+ assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files
83
+ assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files
84
+
85
+ @mac_woes
86
+ @requires_zlib()
87
+ # https://bugs.python.org/issue1533164
88
+ @pytest.mark.skipif("not shutil.which('rpm')")
89
+ @pytest.mark.skipif("not shutil.which('rpmbuild')")
90
+ def test_no_optimize_flag(self):
91
+ # let's create a package that breaks bdist_rpm
92
+ tmp_dir = self.mkdtemp()
93
+ os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation
94
+ pkg_dir = os.path.join(tmp_dir, 'foo')
95
+ os.mkdir(pkg_dir)
96
+ self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
97
+ self.write_file((pkg_dir, 'foo.py'), '#')
98
+ self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
99
+ self.write_file((pkg_dir, 'README'), '')
100
+
101
+ dist = Distribution({
102
+ 'name': 'foo',
103
+ 'version': '0.1',
104
+ 'py_modules': ['foo'],
105
+ 'url': 'xxx',
106
+ 'author': 'xxx',
107
+ 'author_email': 'xxx',
108
+ })
109
+ dist.script_name = 'setup.py'
110
+ os.chdir(pkg_dir)
111
+
112
+ sys.argv = ['setup.py']
113
+ cmd = bdist_rpm(dist)
114
+ cmd.fix_python = True
115
+
116
+ cmd.quiet = True
117
+ cmd.ensure_finalized()
118
+ cmd.run()
119
+
120
+ dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
121
+ assert 'foo-0.1-1.noarch.rpm' in dist_created
122
+
123
+ # bug #2945: upload ignores bdist_rpm files
124
+ assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files
125
+ assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files
126
+
127
+ os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm'))
python/Lib/site-packages/setuptools/_distutils/tests/test_build.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.build."""
2
+
3
+ import os
4
+ import sys
5
+ from distutils.command.build import build
6
+ from distutils.tests import support
7
+ from sysconfig import get_config_var, get_platform
8
+
9
+
10
+ class TestBuild(support.TempdirManager):
11
+ def test_finalize_options(self):
12
+ pkg_dir, dist = self.create_dist()
13
+ cmd = build(dist)
14
+ cmd.finalize_options()
15
+
16
+ # if not specified, plat_name gets the current platform
17
+ assert cmd.plat_name == get_platform()
18
+
19
+ # build_purelib is build + lib
20
+ wanted = os.path.join(cmd.build_base, 'lib')
21
+ assert cmd.build_purelib == wanted
22
+
23
+ # build_platlib is 'build/lib.platform-cache_tag[-pydebug]'
24
+ # examples:
25
+ # build/lib.macosx-10.3-i386-cpython39
26
+ plat_spec = f'.{cmd.plat_name}-{sys.implementation.cache_tag}'
27
+ if get_config_var('Py_GIL_DISABLED'):
28
+ plat_spec += 't'
29
+ if hasattr(sys, 'gettotalrefcount'):
30
+ assert cmd.build_platlib.endswith('-pydebug')
31
+ plat_spec += '-pydebug'
32
+ wanted = os.path.join(cmd.build_base, 'lib' + plat_spec)
33
+ assert cmd.build_platlib == wanted
34
+
35
+ # by default, build_lib = build_purelib
36
+ assert cmd.build_lib == cmd.build_purelib
37
+
38
+ # build_temp is build/temp.<plat>
39
+ wanted = os.path.join(cmd.build_base, 'temp' + plat_spec)
40
+ assert cmd.build_temp == wanted
41
+
42
+ # build_scripts is build/scripts-x.x
43
+ wanted = os.path.join(
44
+ cmd.build_base, f'scripts-{sys.version_info.major}.{sys.version_info.minor}'
45
+ )
46
+ assert cmd.build_scripts == wanted
47
+
48
+ # executable is os.path.normpath(sys.executable)
49
+ assert cmd.executable == os.path.normpath(sys.executable)
python/Lib/site-packages/setuptools/_distutils/tests/test_build_clib.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.build_clib."""
2
+
3
+ import os
4
+ from distutils.command.build_clib import build_clib
5
+ from distutils.errors import DistutilsSetupError
6
+ from distutils.tests import missing_compiler_executable, support
7
+
8
+ import pytest
9
+
10
+
11
+ class TestBuildCLib(support.TempdirManager):
12
+ def test_check_library_dist(self):
13
+ pkg_dir, dist = self.create_dist()
14
+ cmd = build_clib(dist)
15
+
16
+ # 'libraries' option must be a list
17
+ with pytest.raises(DistutilsSetupError):
18
+ cmd.check_library_list('foo')
19
+
20
+ # each element of 'libraries' must a 2-tuple
21
+ with pytest.raises(DistutilsSetupError):
22
+ cmd.check_library_list(['foo1', 'foo2'])
23
+
24
+ # first element of each tuple in 'libraries'
25
+ # must be a string (the library name)
26
+ with pytest.raises(DistutilsSetupError):
27
+ cmd.check_library_list([(1, 'foo1'), ('name', 'foo2')])
28
+
29
+ # library name may not contain directory separators
30
+ with pytest.raises(DistutilsSetupError):
31
+ cmd.check_library_list(
32
+ [('name', 'foo1'), ('another/name', 'foo2')],
33
+ )
34
+
35
+ # second element of each tuple must be a dictionary (build info)
36
+ with pytest.raises(DistutilsSetupError):
37
+ cmd.check_library_list(
38
+ [('name', {}), ('another', 'foo2')],
39
+ )
40
+
41
+ # those work
42
+ libs = [('name', {}), ('name', {'ok': 'good'})]
43
+ cmd.check_library_list(libs)
44
+
45
+ def test_get_source_files(self):
46
+ pkg_dir, dist = self.create_dist()
47
+ cmd = build_clib(dist)
48
+
49
+ # "in 'libraries' option 'sources' must be present and must be
50
+ # a list of source filenames
51
+ cmd.libraries = [('name', {})]
52
+ with pytest.raises(DistutilsSetupError):
53
+ cmd.get_source_files()
54
+
55
+ cmd.libraries = [('name', {'sources': 1})]
56
+ with pytest.raises(DistutilsSetupError):
57
+ cmd.get_source_files()
58
+
59
+ cmd.libraries = [('name', {'sources': ['a', 'b']})]
60
+ assert cmd.get_source_files() == ['a', 'b']
61
+
62
+ cmd.libraries = [('name', {'sources': ('a', 'b')})]
63
+ assert cmd.get_source_files() == ['a', 'b']
64
+
65
+ cmd.libraries = [
66
+ ('name', {'sources': ('a', 'b')}),
67
+ ('name2', {'sources': ['c', 'd']}),
68
+ ]
69
+ assert cmd.get_source_files() == ['a', 'b', 'c', 'd']
70
+
71
+ def test_build_libraries(self):
72
+ pkg_dir, dist = self.create_dist()
73
+ cmd = build_clib(dist)
74
+
75
+ class FakeCompiler:
76
+ def compile(*args, **kw):
77
+ pass
78
+
79
+ create_static_lib = compile
80
+
81
+ cmd.compiler = FakeCompiler()
82
+
83
+ # build_libraries is also doing a bit of typo checking
84
+ lib = [('name', {'sources': 'notvalid'})]
85
+ with pytest.raises(DistutilsSetupError):
86
+ cmd.build_libraries(lib)
87
+
88
+ lib = [('name', {'sources': list()})]
89
+ cmd.build_libraries(lib)
90
+
91
+ lib = [('name', {'sources': tuple()})]
92
+ cmd.build_libraries(lib)
93
+
94
+ def test_finalize_options(self):
95
+ pkg_dir, dist = self.create_dist()
96
+ cmd = build_clib(dist)
97
+
98
+ cmd.include_dirs = 'one-dir'
99
+ cmd.finalize_options()
100
+ assert cmd.include_dirs == ['one-dir']
101
+
102
+ cmd.include_dirs = None
103
+ cmd.finalize_options()
104
+ assert cmd.include_dirs == []
105
+
106
+ cmd.distribution.libraries = 'WONTWORK'
107
+ with pytest.raises(DistutilsSetupError):
108
+ cmd.finalize_options()
109
+
110
+ @pytest.mark.skipif('platform.system() == "Windows"')
111
+ def test_run(self):
112
+ pkg_dir, dist = self.create_dist()
113
+ cmd = build_clib(dist)
114
+
115
+ foo_c = os.path.join(pkg_dir, 'foo.c')
116
+ self.write_file(foo_c, 'int main(void) { return 1;}\n')
117
+ cmd.libraries = [('foo', {'sources': [foo_c]})]
118
+
119
+ build_temp = os.path.join(pkg_dir, 'build')
120
+ os.mkdir(build_temp)
121
+ cmd.build_temp = build_temp
122
+ cmd.build_clib = build_temp
123
+
124
+ # Before we run the command, we want to make sure
125
+ # all commands are present on the system.
126
+ ccmd = missing_compiler_executable()
127
+ if ccmd is not None:
128
+ self.skipTest(f'The {ccmd!r} command is not found')
129
+
130
+ # this should work
131
+ cmd.run()
132
+
133
+ # let's check the result
134
+ assert 'libfoo.a' in os.listdir(build_temp)
python/Lib/site-packages/setuptools/_distutils/tests/test_build_ext.py ADDED
@@ -0,0 +1,628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import glob
3
+ import importlib
4
+ import os.path
5
+ import platform
6
+ import re
7
+ import shutil
8
+ import site
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import textwrap
13
+ import time
14
+ from distutils import sysconfig
15
+ from distutils.command.build_ext import build_ext
16
+ from distutils.core import Distribution
17
+ from distutils.errors import (
18
+ CompileError,
19
+ DistutilsPlatformError,
20
+ DistutilsSetupError,
21
+ UnknownFileError,
22
+ )
23
+ from distutils.extension import Extension
24
+ from distutils.tests import missing_compiler_executable
25
+ from distutils.tests.support import TempdirManager, copy_xxmodule_c, fixup_build_ext
26
+ from io import StringIO
27
+
28
+ import jaraco.path
29
+ import path
30
+ import pytest
31
+ from test import support
32
+
33
+ from .compat import py39 as import_helper
34
+
35
+
36
+ @pytest.fixture()
37
+ def user_site_dir(request):
38
+ self = request.instance
39
+ self.tmp_dir = self.mkdtemp()
40
+ self.tmp_path = path.Path(self.tmp_dir)
41
+ from distutils.command import build_ext
42
+
43
+ orig_user_base = site.USER_BASE
44
+
45
+ site.USER_BASE = self.mkdtemp()
46
+ build_ext.USER_BASE = site.USER_BASE
47
+
48
+ # bpo-30132: On Windows, a .pdb file may be created in the current
49
+ # working directory. Create a temporary working directory to cleanup
50
+ # everything at the end of the test.
51
+ with self.tmp_path:
52
+ yield
53
+
54
+ site.USER_BASE = orig_user_base
55
+ build_ext.USER_BASE = orig_user_base
56
+
57
+ if sys.platform == 'cygwin':
58
+ time.sleep(1)
59
+
60
+
61
+ @contextlib.contextmanager
62
+ def safe_extension_import(name, path):
63
+ with import_helper.CleanImport(name):
64
+ with extension_redirect(name, path) as new_path:
65
+ with import_helper.DirsOnSysPath(new_path):
66
+ yield
67
+
68
+
69
+ @contextlib.contextmanager
70
+ def extension_redirect(mod, path):
71
+ """
72
+ Tests will fail to tear down an extension module if it's been imported.
73
+
74
+ Before importing, copy the file to a temporary directory that won't
75
+ be cleaned up. Yield the new path.
76
+ """
77
+ if platform.system() != "Windows" and sys.platform != "cygwin":
78
+ yield path
79
+ return
80
+ with import_helper.DirsOnSysPath(path):
81
+ spec = importlib.util.find_spec(mod)
82
+ filename = os.path.basename(spec.origin)
83
+ trash_dir = tempfile.mkdtemp(prefix='deleteme')
84
+ dest = os.path.join(trash_dir, os.path.basename(filename))
85
+ shutil.copy(spec.origin, dest)
86
+ yield trash_dir
87
+ # TODO: can the file be scheduled for deletion?
88
+
89
+
90
+ @pytest.mark.usefixtures('user_site_dir')
91
+ class TestBuildExt(TempdirManager):
92
+ def build_ext(self, *args, **kwargs):
93
+ return build_ext(*args, **kwargs)
94
+
95
+ @pytest.mark.parametrize("copy_so", [False])
96
+ def test_build_ext(self, copy_so):
97
+ missing_compiler_executable()
98
+ copy_xxmodule_c(self.tmp_dir)
99
+ xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
100
+ xx_ext = Extension('xx', [xx_c])
101
+ if sys.platform != "win32":
102
+ if not copy_so:
103
+ xx_ext = Extension(
104
+ 'xx',
105
+ [xx_c],
106
+ library_dirs=['/usr/lib'],
107
+ libraries=['z'],
108
+ runtime_library_dirs=['/usr/lib'],
109
+ )
110
+ elif sys.platform == 'linux':
111
+ libz_so = {
112
+ os.path.realpath(name) for name in glob.iglob('/usr/lib*/libz.so*')
113
+ }
114
+ libz_so = sorted(libz_so, key=lambda lib_path: len(lib_path))
115
+ shutil.copyfile(libz_so[-1], '/tmp/libxx_z.so')
116
+
117
+ xx_ext = Extension(
118
+ 'xx',
119
+ [xx_c],
120
+ library_dirs=['/tmp'],
121
+ libraries=['xx_z'],
122
+ runtime_library_dirs=['/tmp'],
123
+ )
124
+ dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]})
125
+ dist.package_dir = self.tmp_dir
126
+ cmd = self.build_ext(dist)
127
+ fixup_build_ext(cmd)
128
+ cmd.build_lib = self.tmp_dir
129
+ cmd.build_temp = self.tmp_dir
130
+
131
+ old_stdout = sys.stdout
132
+ if not support.verbose:
133
+ # silence compiler output
134
+ sys.stdout = StringIO()
135
+ try:
136
+ cmd.ensure_finalized()
137
+ cmd.run()
138
+ finally:
139
+ sys.stdout = old_stdout
140
+
141
+ with safe_extension_import('xx', self.tmp_dir):
142
+ self._test_xx(copy_so)
143
+
144
+ if sys.platform == 'linux' and copy_so:
145
+ os.unlink('/tmp/libxx_z.so')
146
+
147
+ @staticmethod
148
+ def _test_xx(copy_so):
149
+ import xx # type: ignore[import-not-found] # Module generated for tests
150
+
151
+ for attr in ('error', 'foo', 'new', 'roj'):
152
+ assert hasattr(xx, attr)
153
+
154
+ assert xx.foo(2, 5) == 7
155
+ assert xx.foo(13, 15) == 28
156
+ assert xx.new().demo() is None
157
+ if support.HAVE_DOCSTRINGS:
158
+ doc = 'This is a template module just for instruction.'
159
+ assert xx.__doc__ == doc
160
+ assert isinstance(xx.Null(), xx.Null)
161
+ assert isinstance(xx.Str(), xx.Str)
162
+
163
+ if sys.platform == 'linux':
164
+ so_headers = subprocess.check_output(
165
+ ["readelf", "-d", xx.__file__], universal_newlines=True
166
+ )
167
+ import pprint
168
+
169
+ pprint.pprint(so_headers)
170
+ rpaths = [
171
+ rpath
172
+ for line in so_headers.split("\n")
173
+ if "RPATH" in line or "RUNPATH" in line
174
+ for rpath in line.split()[2][1:-1].split(":")
175
+ ]
176
+ if not copy_so:
177
+ pprint.pprint(rpaths)
178
+ # Linked against a library in /usr/lib{,64}
179
+ assert "/usr/lib" not in rpaths and "/usr/lib64" not in rpaths
180
+ else:
181
+ # Linked against a library in /tmp
182
+ assert "/tmp" in rpaths
183
+ # The import is the real test here
184
+
185
+ def test_solaris_enable_shared(self):
186
+ dist = Distribution({'name': 'xx'})
187
+ cmd = self.build_ext(dist)
188
+ old = sys.platform
189
+
190
+ sys.platform = 'sunos' # fooling finalize_options
191
+ from distutils.sysconfig import _config_vars
192
+
193
+ old_var = _config_vars.get('Py_ENABLE_SHARED')
194
+ _config_vars['Py_ENABLE_SHARED'] = True
195
+ try:
196
+ cmd.ensure_finalized()
197
+ finally:
198
+ sys.platform = old
199
+ if old_var is None:
200
+ del _config_vars['Py_ENABLE_SHARED']
201
+ else:
202
+ _config_vars['Py_ENABLE_SHARED'] = old_var
203
+
204
+ # make sure we get some library dirs under solaris
205
+ assert len(cmd.library_dirs) > 0
206
+
207
+ def test_user_site(self):
208
+ import site
209
+
210
+ dist = Distribution({'name': 'xx'})
211
+ cmd = self.build_ext(dist)
212
+
213
+ # making sure the user option is there
214
+ options = [name for name, short, label in cmd.user_options]
215
+ assert 'user' in options
216
+
217
+ # setting a value
218
+ cmd.user = True
219
+
220
+ # setting user based lib and include
221
+ lib = os.path.join(site.USER_BASE, 'lib')
222
+ incl = os.path.join(site.USER_BASE, 'include')
223
+ os.mkdir(lib)
224
+ os.mkdir(incl)
225
+
226
+ # let's run finalize
227
+ cmd.ensure_finalized()
228
+
229
+ # see if include_dirs and library_dirs
230
+ # were set
231
+ assert lib in cmd.library_dirs
232
+ assert lib in cmd.rpath
233
+ assert incl in cmd.include_dirs
234
+
235
+ def test_optional_extension(self):
236
+ # this extension will fail, but let's ignore this failure
237
+ # with the optional argument.
238
+ modules = [Extension('foo', ['xxx'], optional=False)]
239
+ dist = Distribution({'name': 'xx', 'ext_modules': modules})
240
+ cmd = self.build_ext(dist)
241
+ cmd.ensure_finalized()
242
+ with pytest.raises((UnknownFileError, CompileError)):
243
+ cmd.run() # should raise an error
244
+
245
+ modules = [Extension('foo', ['xxx'], optional=True)]
246
+ dist = Distribution({'name': 'xx', 'ext_modules': modules})
247
+ cmd = self.build_ext(dist)
248
+ cmd.ensure_finalized()
249
+ cmd.run() # should pass
250
+
251
+ def test_finalize_options(self):
252
+ # Make sure Python's include directories (for Python.h, pyconfig.h,
253
+ # etc.) are in the include search path.
254
+ modules = [Extension('foo', ['xxx'], optional=False)]
255
+ dist = Distribution({'name': 'xx', 'ext_modules': modules})
256
+ cmd = self.build_ext(dist)
257
+ cmd.finalize_options()
258
+
259
+ py_include = sysconfig.get_python_inc()
260
+ for p in py_include.split(os.path.pathsep):
261
+ assert p in cmd.include_dirs
262
+
263
+ plat_py_include = sysconfig.get_python_inc(plat_specific=True)
264
+ for p in plat_py_include.split(os.path.pathsep):
265
+ assert p in cmd.include_dirs
266
+
267
+ # make sure cmd.libraries is turned into a list
268
+ # if it's a string
269
+ cmd = self.build_ext(dist)
270
+ cmd.libraries = 'my_lib, other_lib lastlib'
271
+ cmd.finalize_options()
272
+ assert cmd.libraries == ['my_lib', 'other_lib', 'lastlib']
273
+
274
+ # make sure cmd.library_dirs is turned into a list
275
+ # if it's a string
276
+ cmd = self.build_ext(dist)
277
+ cmd.library_dirs = f'my_lib_dir{os.pathsep}other_lib_dir'
278
+ cmd.finalize_options()
279
+ assert 'my_lib_dir' in cmd.library_dirs
280
+ assert 'other_lib_dir' in cmd.library_dirs
281
+
282
+ # make sure rpath is turned into a list
283
+ # if it's a string
284
+ cmd = self.build_ext(dist)
285
+ cmd.rpath = f'one{os.pathsep}two'
286
+ cmd.finalize_options()
287
+ assert cmd.rpath == ['one', 'two']
288
+
289
+ # make sure cmd.link_objects is turned into a list
290
+ # if it's a string
291
+ cmd = build_ext(dist)
292
+ cmd.link_objects = 'one two,three'
293
+ cmd.finalize_options()
294
+ assert cmd.link_objects == ['one', 'two', 'three']
295
+
296
+ # XXX more tests to perform for win32
297
+
298
+ # make sure define is turned into 2-tuples
299
+ # strings if they are ','-separated strings
300
+ cmd = self.build_ext(dist)
301
+ cmd.define = 'one,two'
302
+ cmd.finalize_options()
303
+ assert cmd.define == [('one', '1'), ('two', '1')]
304
+
305
+ # make sure undef is turned into a list of
306
+ # strings if they are ','-separated strings
307
+ cmd = self.build_ext(dist)
308
+ cmd.undef = 'one,two'
309
+ cmd.finalize_options()
310
+ assert cmd.undef == ['one', 'two']
311
+
312
+ # make sure swig_opts is turned into a list
313
+ cmd = self.build_ext(dist)
314
+ cmd.swig_opts = None
315
+ cmd.finalize_options()
316
+ assert cmd.swig_opts == []
317
+
318
+ cmd = self.build_ext(dist)
319
+ cmd.swig_opts = '1 2'
320
+ cmd.finalize_options()
321
+ assert cmd.swig_opts == ['1', '2']
322
+
323
+ def test_check_extensions_list(self):
324
+ dist = Distribution()
325
+ cmd = self.build_ext(dist)
326
+ cmd.finalize_options()
327
+
328
+ # 'extensions' option must be a list of Extension instances
329
+ with pytest.raises(DistutilsSetupError):
330
+ cmd.check_extensions_list('foo')
331
+
332
+ # each element of 'ext_modules' option must be an
333
+ # Extension instance or 2-tuple
334
+ exts = [('bar', 'foo', 'bar'), 'foo']
335
+ with pytest.raises(DistutilsSetupError):
336
+ cmd.check_extensions_list(exts)
337
+
338
+ # first element of each tuple in 'ext_modules'
339
+ # must be the extension name (a string) and match
340
+ # a python dotted-separated name
341
+ exts = [('foo-bar', '')]
342
+ with pytest.raises(DistutilsSetupError):
343
+ cmd.check_extensions_list(exts)
344
+
345
+ # second element of each tuple in 'ext_modules'
346
+ # must be a dictionary (build info)
347
+ exts = [('foo.bar', '')]
348
+ with pytest.raises(DistutilsSetupError):
349
+ cmd.check_extensions_list(exts)
350
+
351
+ # ok this one should pass
352
+ exts = [('foo.bar', {'sources': [''], 'libraries': 'foo', 'some': 'bar'})]
353
+ cmd.check_extensions_list(exts)
354
+ ext = exts[0]
355
+ assert isinstance(ext, Extension)
356
+
357
+ # check_extensions_list adds in ext the values passed
358
+ # when they are in ('include_dirs', 'library_dirs', 'libraries'
359
+ # 'extra_objects', 'extra_compile_args', 'extra_link_args')
360
+ assert ext.libraries == 'foo'
361
+ assert not hasattr(ext, 'some')
362
+
363
+ # 'macros' element of build info dict must be 1- or 2-tuple
364
+ exts = [
365
+ (
366
+ 'foo.bar',
367
+ {
368
+ 'sources': [''],
369
+ 'libraries': 'foo',
370
+ 'some': 'bar',
371
+ 'macros': [('1', '2', '3'), 'foo'],
372
+ },
373
+ )
374
+ ]
375
+ with pytest.raises(DistutilsSetupError):
376
+ cmd.check_extensions_list(exts)
377
+
378
+ exts[0][1]['macros'] = [('1', '2'), ('3',)]
379
+ cmd.check_extensions_list(exts)
380
+ assert exts[0].undef_macros == ['3']
381
+ assert exts[0].define_macros == [('1', '2')]
382
+
383
+ def test_get_source_files(self):
384
+ modules = [Extension('foo', ['xxx'], optional=False)]
385
+ dist = Distribution({'name': 'xx', 'ext_modules': modules})
386
+ cmd = self.build_ext(dist)
387
+ cmd.ensure_finalized()
388
+ assert cmd.get_source_files() == ['xxx']
389
+
390
+ def test_unicode_module_names(self):
391
+ modules = [
392
+ Extension('foo', ['aaa'], optional=False),
393
+ Extension('föö', ['uuu'], optional=False),
394
+ ]
395
+ dist = Distribution({'name': 'xx', 'ext_modules': modules})
396
+ cmd = self.build_ext(dist)
397
+ cmd.ensure_finalized()
398
+ assert re.search(r'foo(_d)?\..*', cmd.get_ext_filename(modules[0].name))
399
+ assert re.search(r'föö(_d)?\..*', cmd.get_ext_filename(modules[1].name))
400
+ assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo']
401
+ assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa']
402
+
403
+ def test_export_symbols__init__(self):
404
+ # https://github.com/python/cpython/issues/80074
405
+ # https://github.com/pypa/setuptools/issues/4826
406
+ modules = [
407
+ Extension('foo.__init__', ['aaa']),
408
+ Extension('föö.__init__', ['uuu']),
409
+ ]
410
+ dist = Distribution({'name': 'xx', 'ext_modules': modules})
411
+ cmd = self.build_ext(dist)
412
+ cmd.ensure_finalized()
413
+ assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo']
414
+ assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa']
415
+
416
+ def test_compiler_option(self):
417
+ # cmd.compiler is an option and
418
+ # should not be overridden by a compiler instance
419
+ # when the command is run
420
+ dist = Distribution()
421
+ cmd = self.build_ext(dist)
422
+ cmd.compiler = 'unix'
423
+ cmd.ensure_finalized()
424
+ cmd.run()
425
+ assert cmd.compiler == 'unix'
426
+
427
+ def test_get_outputs(self):
428
+ missing_compiler_executable()
429
+ tmp_dir = self.mkdtemp()
430
+ c_file = os.path.join(tmp_dir, 'foo.c')
431
+ self.write_file(c_file, 'void PyInit_foo(void) {}\n')
432
+ ext = Extension('foo', [c_file], optional=False)
433
+ dist = Distribution({'name': 'xx', 'ext_modules': [ext]})
434
+ cmd = self.build_ext(dist)
435
+ fixup_build_ext(cmd)
436
+ cmd.ensure_finalized()
437
+ assert len(cmd.get_outputs()) == 1
438
+
439
+ cmd.build_lib = os.path.join(self.tmp_dir, 'build')
440
+ cmd.build_temp = os.path.join(self.tmp_dir, 'tempt')
441
+
442
+ # issue #5977 : distutils build_ext.get_outputs
443
+ # returns wrong result with --inplace
444
+ other_tmp_dir = os.path.realpath(self.mkdtemp())
445
+ old_wd = os.getcwd()
446
+ os.chdir(other_tmp_dir)
447
+ try:
448
+ cmd.inplace = True
449
+ cmd.run()
450
+ so_file = cmd.get_outputs()[0]
451
+ finally:
452
+ os.chdir(old_wd)
453
+ assert os.path.exists(so_file)
454
+ ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
455
+ assert so_file.endswith(ext_suffix)
456
+ so_dir = os.path.dirname(so_file)
457
+ assert so_dir == other_tmp_dir
458
+
459
+ cmd.inplace = False
460
+ cmd.compiler = None
461
+ cmd.run()
462
+ so_file = cmd.get_outputs()[0]
463
+ assert os.path.exists(so_file)
464
+ assert so_file.endswith(ext_suffix)
465
+ so_dir = os.path.dirname(so_file)
466
+ assert so_dir == cmd.build_lib
467
+
468
+ # inplace = False, cmd.package = 'bar'
469
+ build_py = cmd.get_finalized_command('build_py')
470
+ build_py.package_dir = {'': 'bar'}
471
+ path = cmd.get_ext_fullpath('foo')
472
+ # checking that the last directory is the build_dir
473
+ path = os.path.split(path)[0]
474
+ assert path == cmd.build_lib
475
+
476
+ # inplace = True, cmd.package = 'bar'
477
+ cmd.inplace = True
478
+ other_tmp_dir = os.path.realpath(self.mkdtemp())
479
+ old_wd = os.getcwd()
480
+ os.chdir(other_tmp_dir)
481
+ try:
482
+ path = cmd.get_ext_fullpath('foo')
483
+ finally:
484
+ os.chdir(old_wd)
485
+ # checking that the last directory is bar
486
+ path = os.path.split(path)[0]
487
+ lastdir = os.path.split(path)[-1]
488
+ assert lastdir == 'bar'
489
+
490
+ def test_ext_fullpath(self):
491
+ ext = sysconfig.get_config_var('EXT_SUFFIX')
492
+ # building lxml.etree inplace
493
+ # etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
494
+ # etree_ext = Extension('lxml.etree', [etree_c])
495
+ # dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
496
+ dist = Distribution()
497
+ cmd = self.build_ext(dist)
498
+ cmd.inplace = True
499
+ cmd.distribution.package_dir = {'': 'src'}
500
+ cmd.distribution.packages = ['lxml', 'lxml.html']
501
+ curdir = os.getcwd()
502
+ wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
503
+ path = cmd.get_ext_fullpath('lxml.etree')
504
+ assert wanted == path
505
+
506
+ # building lxml.etree not inplace
507
+ cmd.inplace = False
508
+ cmd.build_lib = os.path.join(curdir, 'tmpdir')
509
+ wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
510
+ path = cmd.get_ext_fullpath('lxml.etree')
511
+ assert wanted == path
512
+
513
+ # building twisted.runner.portmap not inplace
514
+ build_py = cmd.get_finalized_command('build_py')
515
+ build_py.package_dir = {}
516
+ cmd.distribution.packages = ['twisted', 'twisted.runner.portmap']
517
+ path = cmd.get_ext_fullpath('twisted.runner.portmap')
518
+ wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', 'portmap' + ext)
519
+ assert wanted == path
520
+
521
+ # building twisted.runner.portmap inplace
522
+ cmd.inplace = True
523
+ path = cmd.get_ext_fullpath('twisted.runner.portmap')
524
+ wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
525
+ assert wanted == path
526
+
527
+ @pytest.mark.skipif('platform.system() != "Darwin"')
528
+ @pytest.mark.usefixtures('save_env')
529
+ def test_deployment_target_default(self):
530
+ # Issue 9516: Test that, in the absence of the environment variable,
531
+ # an extension module is compiled with the same deployment target as
532
+ # the interpreter.
533
+ self._try_compile_deployment_target('==', None)
534
+
535
+ @pytest.mark.skipif('platform.system() != "Darwin"')
536
+ @pytest.mark.usefixtures('save_env')
537
+ def test_deployment_target_too_low(self):
538
+ # Issue 9516: Test that an extension module is not allowed to be
539
+ # compiled with a deployment target less than that of the interpreter.
540
+ with pytest.raises(DistutilsPlatformError):
541
+ self._try_compile_deployment_target('>', '10.1')
542
+
543
+ @pytest.mark.skipif('platform.system() != "Darwin"')
544
+ @pytest.mark.usefixtures('save_env')
545
+ def test_deployment_target_higher_ok(self): # pragma: no cover
546
+ # Issue 9516: Test that an extension module can be compiled with a
547
+ # deployment target higher than that of the interpreter: the ext
548
+ # module may depend on some newer OS feature.
549
+ deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
550
+ if deptarget:
551
+ # increment the minor version number (i.e. 10.6 -> 10.7)
552
+ deptarget = [int(x) for x in deptarget.split('.')]
553
+ deptarget[-1] += 1
554
+ deptarget = '.'.join(str(i) for i in deptarget)
555
+ self._try_compile_deployment_target('<', deptarget)
556
+
557
+ def _try_compile_deployment_target(self, operator, target): # pragma: no cover
558
+ if target is None:
559
+ if os.environ.get('MACOSX_DEPLOYMENT_TARGET'):
560
+ del os.environ['MACOSX_DEPLOYMENT_TARGET']
561
+ else:
562
+ os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
563
+
564
+ jaraco.path.build(
565
+ {
566
+ 'deptargetmodule.c': textwrap.dedent(f"""\
567
+ #include <AvailabilityMacros.h>
568
+
569
+ int dummy;
570
+
571
+ #if TARGET {operator} MAC_OS_X_VERSION_MIN_REQUIRED
572
+ #else
573
+ #error "Unexpected target"
574
+ #endif
575
+
576
+ """),
577
+ },
578
+ self.tmp_path,
579
+ )
580
+
581
+ # get the deployment target that the interpreter was built with
582
+ target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
583
+ target = tuple(map(int, target.split('.')[0:2]))
584
+ # format the target value as defined in the Apple
585
+ # Availability Macros. We can't use the macro names since
586
+ # at least one value we test with will not exist yet.
587
+ if target[:2] < (10, 10):
588
+ # for 10.1 through 10.9.x -> "10n0"
589
+ tmpl = '{:02}{:01}0'
590
+ else:
591
+ # for 10.10 and beyond -> "10nn00"
592
+ if len(target) >= 2:
593
+ tmpl = '{:02}{:02}00'
594
+ else:
595
+ # 11 and later can have no minor version (11 instead of 11.0)
596
+ tmpl = '{:02}0000'
597
+ target = tmpl.format(*target)
598
+ deptarget_ext = Extension(
599
+ 'deptarget',
600
+ [self.tmp_path / 'deptargetmodule.c'],
601
+ extra_compile_args=[f'-DTARGET={target}'],
602
+ )
603
+ dist = Distribution({'name': 'deptarget', 'ext_modules': [deptarget_ext]})
604
+ dist.package_dir = self.tmp_dir
605
+ cmd = self.build_ext(dist)
606
+ cmd.build_lib = self.tmp_dir
607
+ cmd.build_temp = self.tmp_dir
608
+
609
+ try:
610
+ old_stdout = sys.stdout
611
+ if not support.verbose:
612
+ # silence compiler output
613
+ sys.stdout = StringIO()
614
+ try:
615
+ cmd.ensure_finalized()
616
+ cmd.run()
617
+ finally:
618
+ sys.stdout = old_stdout
619
+
620
+ except CompileError:
621
+ self.fail("Wrong deployment target during compilation")
622
+
623
+
624
+ class TestParallelBuildExt(TestBuildExt):
625
+ def build_ext(self, *args, **kwargs):
626
+ build_ext = super().build_ext(*args, **kwargs)
627
+ build_ext.parallel = True
628
+ return build_ext
python/Lib/site-packages/setuptools/_distutils/tests/test_build_py.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.build_py."""
2
+
3
+ import os
4
+ import sys
5
+ from distutils.command.build_py import build_py
6
+ from distutils.core import Distribution
7
+ from distutils.errors import DistutilsFileError
8
+ from distutils.tests import support
9
+
10
+ import jaraco.path
11
+ import pytest
12
+
13
+
14
+ @support.combine_markers
15
+ class TestBuildPy(support.TempdirManager):
16
+ def test_package_data(self):
17
+ sources = self.mkdtemp()
18
+ jaraco.path.build(
19
+ {
20
+ '__init__.py': "# Pretend this is a package.",
21
+ 'README.txt': 'Info about this package',
22
+ },
23
+ sources,
24
+ )
25
+
26
+ destination = self.mkdtemp()
27
+
28
+ dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": sources}})
29
+ # script_name need not exist, it just need to be initialized
30
+ dist.script_name = os.path.join(sources, "setup.py")
31
+ dist.command_obj["build"] = support.DummyCommand(
32
+ force=False, build_lib=destination
33
+ )
34
+ dist.packages = ["pkg"]
35
+ dist.package_data = {"pkg": ["README.txt"]}
36
+ dist.package_dir = {"pkg": sources}
37
+
38
+ cmd = build_py(dist)
39
+ cmd.compile = True
40
+ cmd.ensure_finalized()
41
+ assert cmd.package_data == dist.package_data
42
+
43
+ cmd.run()
44
+
45
+ # This makes sure the list of outputs includes byte-compiled
46
+ # files for Python modules but not for package data files
47
+ # (there shouldn't *be* byte-code files for those!).
48
+ assert len(cmd.get_outputs()) == 3
49
+ pkgdest = os.path.join(destination, "pkg")
50
+ files = os.listdir(pkgdest)
51
+ pycache_dir = os.path.join(pkgdest, "__pycache__")
52
+ assert "__init__.py" in files
53
+ assert "README.txt" in files
54
+ if sys.dont_write_bytecode:
55
+ assert not os.path.exists(pycache_dir)
56
+ else:
57
+ pyc_files = os.listdir(pycache_dir)
58
+ assert f"__init__.{sys.implementation.cache_tag}.pyc" in pyc_files
59
+
60
+ def test_empty_package_dir(self):
61
+ # See bugs #1668596/#1720897
62
+ sources = self.mkdtemp()
63
+ jaraco.path.build({'__init__.py': '', 'doc': {'testfile': ''}}, sources)
64
+
65
+ os.chdir(sources)
66
+ dist = Distribution({
67
+ "packages": ["pkg"],
68
+ "package_dir": {"pkg": ""},
69
+ "package_data": {"pkg": ["doc/*"]},
70
+ })
71
+ # script_name need not exist, it just need to be initialized
72
+ dist.script_name = os.path.join(sources, "setup.py")
73
+ dist.script_args = ["build"]
74
+ dist.parse_command_line()
75
+
76
+ try:
77
+ dist.run_commands()
78
+ except DistutilsFileError:
79
+ self.fail("failed package_data test when package_dir is ''")
80
+
81
+ @pytest.mark.skipif('sys.dont_write_bytecode')
82
+ def test_byte_compile(self):
83
+ project_dir, dist = self.create_dist(py_modules=['boiledeggs'])
84
+ os.chdir(project_dir)
85
+ self.write_file('boiledeggs.py', 'import antigravity')
86
+ cmd = build_py(dist)
87
+ cmd.compile = True
88
+ cmd.build_lib = 'here'
89
+ cmd.finalize_options()
90
+ cmd.run()
91
+
92
+ found = os.listdir(cmd.build_lib)
93
+ assert sorted(found) == ['__pycache__', 'boiledeggs.py']
94
+ found = os.listdir(os.path.join(cmd.build_lib, '__pycache__'))
95
+ assert found == [f'boiledeggs.{sys.implementation.cache_tag}.pyc']
96
+
97
+ @pytest.mark.skipif('sys.dont_write_bytecode')
98
+ def test_byte_compile_optimized(self):
99
+ project_dir, dist = self.create_dist(py_modules=['boiledeggs'])
100
+ os.chdir(project_dir)
101
+ self.write_file('boiledeggs.py', 'import antigravity')
102
+ cmd = build_py(dist)
103
+ cmd.compile = False
104
+ cmd.optimize = 1
105
+ cmd.build_lib = 'here'
106
+ cmd.finalize_options()
107
+ cmd.run()
108
+
109
+ found = os.listdir(cmd.build_lib)
110
+ assert sorted(found) == ['__pycache__', 'boiledeggs.py']
111
+ found = os.listdir(os.path.join(cmd.build_lib, '__pycache__'))
112
+ expect = f'boiledeggs.{sys.implementation.cache_tag}.opt-1.pyc'
113
+ assert sorted(found) == [expect]
114
+
115
+ def test_dir_in_package_data(self):
116
+ """
117
+ A directory in package_data should not be added to the filelist.
118
+ """
119
+ # See bug 19286
120
+ sources = self.mkdtemp()
121
+ jaraco.path.build(
122
+ {
123
+ 'pkg': {
124
+ '__init__.py': '',
125
+ 'doc': {
126
+ 'testfile': '',
127
+ # create a directory that could be incorrectly detected as a file
128
+ 'otherdir': {},
129
+ },
130
+ }
131
+ },
132
+ sources,
133
+ )
134
+
135
+ os.chdir(sources)
136
+ dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}})
137
+ # script_name need not exist, it just need to be initialized
138
+ dist.script_name = os.path.join(sources, "setup.py")
139
+ dist.script_args = ["build"]
140
+ dist.parse_command_line()
141
+
142
+ try:
143
+ dist.run_commands()
144
+ except DistutilsFileError:
145
+ self.fail("failed package_data when data dir includes a dir")
146
+
147
+ def test_dont_write_bytecode(self, caplog):
148
+ # makes sure byte_compile is not used
149
+ dist = self.create_dist()[1]
150
+ cmd = build_py(dist)
151
+ cmd.compile = True
152
+ cmd.optimize = 1
153
+
154
+ old_dont_write_bytecode = sys.dont_write_bytecode
155
+ sys.dont_write_bytecode = True
156
+ try:
157
+ cmd.byte_compile([])
158
+ finally:
159
+ sys.dont_write_bytecode = old_dont_write_bytecode
160
+
161
+ assert 'byte-compiling is disabled' in caplog.records[0].message
162
+
163
+ def test_namespace_package_does_not_warn(self, caplog):
164
+ """
165
+ Originally distutils implementation did not account for PEP 420
166
+ and included warns for package directories that did not contain
167
+ ``__init__.py`` files.
168
+ After the acceptance of PEP 420, these warnings don't make more sense
169
+ so we want to ensure there are not displayed to not confuse the users.
170
+ """
171
+ # Create a fake project structure with a package namespace:
172
+ tmp = self.mkdtemp()
173
+ jaraco.path.build({'ns': {'pkg': {'module.py': ''}}}, tmp)
174
+ os.chdir(tmp)
175
+
176
+ # Configure the package:
177
+ attrs = {
178
+ "name": "ns.pkg",
179
+ "packages": ["ns", "ns.pkg"],
180
+ "script_name": "setup.py",
181
+ }
182
+ dist = Distribution(attrs)
183
+
184
+ # Run code paths that would trigger the trap:
185
+ cmd = dist.get_command_obj("build_py")
186
+ cmd.finalize_options()
187
+ modules = cmd.find_all_modules()
188
+ assert len(modules) == 1
189
+ module_path = modules[0][-1]
190
+ assert module_path.replace(os.sep, "/") == "ns/pkg/module.py"
191
+
192
+ cmd.run()
193
+
194
+ assert not any(
195
+ "package init file" in msg and "not found" in msg for msg in caplog.messages
196
+ )
python/Lib/site-packages/setuptools/_distutils/tests/test_build_scripts.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.build_scripts."""
2
+
3
+ import os
4
+ import textwrap
5
+ from distutils import sysconfig
6
+ from distutils.command.build_scripts import build_scripts
7
+ from distutils.core import Distribution
8
+ from distutils.tests import support
9
+
10
+ import jaraco.path
11
+
12
+
13
+ class TestBuildScripts(support.TempdirManager):
14
+ def test_default_settings(self):
15
+ cmd = self.get_build_scripts_cmd("/foo/bar", [])
16
+ assert not cmd.force
17
+ assert cmd.build_dir is None
18
+
19
+ cmd.finalize_options()
20
+
21
+ assert cmd.force
22
+ assert cmd.build_dir == "/foo/bar"
23
+
24
+ def test_build(self):
25
+ source = self.mkdtemp()
26
+ target = self.mkdtemp()
27
+ expected = self.write_sample_scripts(source)
28
+
29
+ cmd = self.get_build_scripts_cmd(
30
+ target, [os.path.join(source, fn) for fn in expected]
31
+ )
32
+ cmd.finalize_options()
33
+ cmd.run()
34
+
35
+ built = os.listdir(target)
36
+ for name in expected:
37
+ assert name in built
38
+
39
+ def get_build_scripts_cmd(self, target, scripts):
40
+ import sys
41
+
42
+ dist = Distribution()
43
+ dist.scripts = scripts
44
+ dist.command_obj["build"] = support.DummyCommand(
45
+ build_scripts=target, force=True, executable=sys.executable
46
+ )
47
+ return build_scripts(dist)
48
+
49
+ @staticmethod
50
+ def write_sample_scripts(dir):
51
+ spec = {
52
+ 'script1.py': textwrap.dedent("""
53
+ #! /usr/bin/env python2.3
54
+ # bogus script w/ Python sh-bang
55
+ pass
56
+ """).lstrip(),
57
+ 'script2.py': textwrap.dedent("""
58
+ #!/usr/bin/python
59
+ # bogus script w/ Python sh-bang
60
+ pass
61
+ """).lstrip(),
62
+ 'shell.sh': textwrap.dedent("""
63
+ #!/bin/sh
64
+ # bogus shell script w/ sh-bang
65
+ exit 0
66
+ """).lstrip(),
67
+ }
68
+ jaraco.path.build(spec, dir)
69
+ return list(spec)
70
+
71
+ def test_version_int(self):
72
+ source = self.mkdtemp()
73
+ target = self.mkdtemp()
74
+ expected = self.write_sample_scripts(source)
75
+
76
+ cmd = self.get_build_scripts_cmd(
77
+ target, [os.path.join(source, fn) for fn in expected]
78
+ )
79
+ cmd.finalize_options()
80
+
81
+ # https://bugs.python.org/issue4524
82
+ #
83
+ # On linux-g++-32 with command line `./configure --enable-ipv6
84
+ # --with-suffix=3`, python is compiled okay but the build scripts
85
+ # failed when writing the name of the executable
86
+ old = sysconfig.get_config_vars().get('VERSION')
87
+ sysconfig._config_vars['VERSION'] = 4
88
+ try:
89
+ cmd.run()
90
+ finally:
91
+ if old is not None:
92
+ sysconfig._config_vars['VERSION'] = old
93
+
94
+ built = os.listdir(target)
95
+ for name in expected:
96
+ assert name in built
python/Lib/site-packages/setuptools/_distutils/tests/test_check.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.check."""
2
+
3
+ import os
4
+ import textwrap
5
+ from distutils.command.check import check
6
+ from distutils.errors import DistutilsSetupError
7
+ from distutils.tests import support
8
+
9
+ import pytest
10
+
11
+ try:
12
+ import pygments
13
+ except ImportError:
14
+ pygments = None
15
+
16
+
17
+ HERE = os.path.dirname(__file__)
18
+
19
+
20
+ @support.combine_markers
21
+ class TestCheck(support.TempdirManager):
22
+ def _run(self, metadata=None, cwd=None, **options):
23
+ if metadata is None:
24
+ metadata = {}
25
+ if cwd is not None:
26
+ old_dir = os.getcwd()
27
+ os.chdir(cwd)
28
+ pkg_info, dist = self.create_dist(**metadata)
29
+ cmd = check(dist)
30
+ cmd.initialize_options()
31
+ for name, value in options.items():
32
+ setattr(cmd, name, value)
33
+ cmd.ensure_finalized()
34
+ cmd.run()
35
+ if cwd is not None:
36
+ os.chdir(old_dir)
37
+ return cmd
38
+
39
+ def test_check_metadata(self):
40
+ # let's run the command with no metadata at all
41
+ # by default, check is checking the metadata
42
+ # should have some warnings
43
+ cmd = self._run()
44
+ assert cmd._warnings == 1
45
+
46
+ # now let's add the required fields
47
+ # and run it again, to make sure we don't get
48
+ # any warning anymore
49
+ metadata = {
50
+ 'url': 'xxx',
51
+ 'author': 'xxx',
52
+ 'author_email': 'xxx',
53
+ 'name': 'xxx',
54
+ 'version': 'xxx',
55
+ }
56
+ cmd = self._run(metadata)
57
+ assert cmd._warnings == 0
58
+
59
+ # now with the strict mode, we should
60
+ # get an error if there are missing metadata
61
+ with pytest.raises(DistutilsSetupError):
62
+ self._run({}, **{'strict': 1})
63
+
64
+ # and of course, no error when all metadata are present
65
+ cmd = self._run(metadata, strict=True)
66
+ assert cmd._warnings == 0
67
+
68
+ # now a test with non-ASCII characters
69
+ metadata = {
70
+ 'url': 'xxx',
71
+ 'author': '\u00c9ric',
72
+ 'author_email': 'xxx',
73
+ 'name': 'xxx',
74
+ 'version': 'xxx',
75
+ 'description': 'Something about esszet \u00df',
76
+ 'long_description': 'More things about esszet \u00df',
77
+ }
78
+ cmd = self._run(metadata)
79
+ assert cmd._warnings == 0
80
+
81
+ def test_check_author_maintainer(self):
82
+ for kind in ("author", "maintainer"):
83
+ # ensure no warning when author_email or maintainer_email is given
84
+ # (the spec allows these fields to take the form "Name <email>")
85
+ metadata = {
86
+ 'url': 'xxx',
87
+ kind + '_email': 'Name <name@email.com>',
88
+ 'name': 'xxx',
89
+ 'version': 'xxx',
90
+ }
91
+ cmd = self._run(metadata)
92
+ assert cmd._warnings == 0
93
+
94
+ # the check should not warn if only email is given
95
+ metadata[kind + '_email'] = 'name@email.com'
96
+ cmd = self._run(metadata)
97
+ assert cmd._warnings == 0
98
+
99
+ # the check should not warn if only the name is given
100
+ metadata[kind] = "Name"
101
+ del metadata[kind + '_email']
102
+ cmd = self._run(metadata)
103
+ assert cmd._warnings == 0
104
+
105
+ def test_check_document(self):
106
+ pytest.importorskip('docutils')
107
+ pkg_info, dist = self.create_dist()
108
+ cmd = check(dist)
109
+
110
+ # let's see if it detects broken rest
111
+ broken_rest = 'title\n===\n\ntest'
112
+ msgs = cmd._check_rst_data(broken_rest)
113
+ assert len(msgs) == 1
114
+
115
+ # and non-broken rest
116
+ rest = 'title\n=====\n\ntest'
117
+ msgs = cmd._check_rst_data(rest)
118
+ assert len(msgs) == 0
119
+
120
+ def test_check_restructuredtext(self):
121
+ pytest.importorskip('docutils')
122
+ # let's see if it detects broken rest in long_description
123
+ broken_rest = 'title\n===\n\ntest'
124
+ pkg_info, dist = self.create_dist(long_description=broken_rest)
125
+ cmd = check(dist)
126
+ cmd.check_restructuredtext()
127
+ assert cmd._warnings == 1
128
+
129
+ # let's see if we have an error with strict=True
130
+ metadata = {
131
+ 'url': 'xxx',
132
+ 'author': 'xxx',
133
+ 'author_email': 'xxx',
134
+ 'name': 'xxx',
135
+ 'version': 'xxx',
136
+ 'long_description': broken_rest,
137
+ }
138
+ with pytest.raises(DistutilsSetupError):
139
+ self._run(metadata, **{'strict': 1, 'restructuredtext': 1})
140
+
141
+ # and non-broken rest, including a non-ASCII character to test #12114
142
+ metadata['long_description'] = 'title\n=====\n\ntest \u00df'
143
+ cmd = self._run(metadata, strict=True, restructuredtext=True)
144
+ assert cmd._warnings == 0
145
+
146
+ # check that includes work to test #31292
147
+ metadata['long_description'] = 'title\n=====\n\n.. include:: includetest.rst'
148
+ cmd = self._run(metadata, cwd=HERE, strict=True, restructuredtext=True)
149
+ assert cmd._warnings == 0
150
+
151
+ def test_check_restructuredtext_with_syntax_highlight(self):
152
+ pytest.importorskip('docutils')
153
+ # Don't fail if there is a `code` or `code-block` directive
154
+
155
+ example_rst_docs = [
156
+ textwrap.dedent(
157
+ """\
158
+ Here's some code:
159
+
160
+ .. code:: python
161
+
162
+ def foo():
163
+ pass
164
+ """
165
+ ),
166
+ textwrap.dedent(
167
+ """\
168
+ Here's some code:
169
+
170
+ .. code-block:: python
171
+
172
+ def foo():
173
+ pass
174
+ """
175
+ ),
176
+ ]
177
+
178
+ for rest_with_code in example_rst_docs:
179
+ pkg_info, dist = self.create_dist(long_description=rest_with_code)
180
+ cmd = check(dist)
181
+ cmd.check_restructuredtext()
182
+ msgs = cmd._check_rst_data(rest_with_code)
183
+ if pygments is not None:
184
+ assert len(msgs) == 0
185
+ else:
186
+ assert len(msgs) == 1
187
+ assert (
188
+ str(msgs[0][1])
189
+ == 'Cannot analyze code. Pygments package not found.'
190
+ )
191
+
192
+ def test_check_all(self):
193
+ with pytest.raises(DistutilsSetupError):
194
+ self._run({}, **{'strict': 1, 'restructuredtext': 1})
python/Lib/site-packages/setuptools/_distutils/tests/test_clean.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.clean."""
2
+
3
+ import os
4
+ from distutils.command.clean import clean
5
+ from distutils.tests import support
6
+
7
+
8
+ class TestClean(support.TempdirManager):
9
+ def test_simple_run(self):
10
+ pkg_dir, dist = self.create_dist()
11
+ cmd = clean(dist)
12
+
13
+ # let's add some elements clean should remove
14
+ dirs = [
15
+ (d, os.path.join(pkg_dir, d))
16
+ for d in (
17
+ 'build_temp',
18
+ 'build_lib',
19
+ 'bdist_base',
20
+ 'build_scripts',
21
+ 'build_base',
22
+ )
23
+ ]
24
+
25
+ for name, path in dirs:
26
+ os.mkdir(path)
27
+ setattr(cmd, name, path)
28
+ if name == 'build_base':
29
+ continue
30
+ for f in ('one', 'two', 'three'):
31
+ self.write_file(os.path.join(path, f))
32
+
33
+ # let's run the command
34
+ cmd.all = 1
35
+ cmd.ensure_finalized()
36
+ cmd.run()
37
+
38
+ # make sure the files where removed
39
+ for _name, path in dirs:
40
+ assert not os.path.exists(path), f'{path} was not removed'
41
+
42
+ # let's run the command again (should spit warnings but succeed)
43
+ cmd.all = 1
44
+ cmd.ensure_finalized()
45
+ cmd.run()
python/Lib/site-packages/setuptools/_distutils/tests/test_cmd.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.cmd."""
2
+
3
+ import os
4
+ from distutils import debug
5
+ from distutils.cmd import Command
6
+ from distutils.dist import Distribution
7
+ from distutils.errors import DistutilsOptionError
8
+
9
+ import pytest
10
+
11
+
12
+ class MyCmd(Command):
13
+ def initialize_options(self):
14
+ pass
15
+
16
+
17
+ @pytest.fixture
18
+ def cmd(request):
19
+ return MyCmd(Distribution())
20
+
21
+
22
+ class TestCommand:
23
+ def test_ensure_string_list(self, cmd):
24
+ cmd.not_string_list = ['one', 2, 'three']
25
+ cmd.yes_string_list = ['one', 'two', 'three']
26
+ cmd.not_string_list2 = object()
27
+ cmd.yes_string_list2 = 'ok'
28
+ cmd.ensure_string_list('yes_string_list')
29
+ cmd.ensure_string_list('yes_string_list2')
30
+
31
+ with pytest.raises(DistutilsOptionError):
32
+ cmd.ensure_string_list('not_string_list')
33
+
34
+ with pytest.raises(DistutilsOptionError):
35
+ cmd.ensure_string_list('not_string_list2')
36
+
37
+ cmd.option1 = 'ok,dok'
38
+ cmd.ensure_string_list('option1')
39
+ assert cmd.option1 == ['ok', 'dok']
40
+
41
+ cmd.option2 = ['xxx', 'www']
42
+ cmd.ensure_string_list('option2')
43
+
44
+ cmd.option3 = ['ok', 2]
45
+ with pytest.raises(DistutilsOptionError):
46
+ cmd.ensure_string_list('option3')
47
+
48
+ def test_make_file(self, cmd):
49
+ # making sure it raises when infiles is not a string or a list/tuple
50
+ with pytest.raises(TypeError):
51
+ cmd.make_file(infiles=True, outfile='', func='func', args=())
52
+
53
+ # making sure execute gets called properly
54
+ def _execute(func, args, exec_msg, level):
55
+ assert exec_msg == 'generating out from in'
56
+
57
+ cmd.force = True
58
+ cmd.execute = _execute
59
+ cmd.make_file(infiles='in', outfile='out', func='func', args=())
60
+
61
+ def test_dump_options(self, cmd):
62
+ msgs = []
63
+
64
+ def _announce(msg, level):
65
+ msgs.append(msg)
66
+
67
+ cmd.announce = _announce
68
+ cmd.option1 = 1
69
+ cmd.option2 = 1
70
+ cmd.user_options = [('option1', '', ''), ('option2', '', '')]
71
+ cmd.dump_options()
72
+
73
+ wanted = ["command options for 'MyCmd':", ' option1 = 1', ' option2 = 1']
74
+ assert msgs == wanted
75
+
76
+ def test_ensure_string(self, cmd):
77
+ cmd.option1 = 'ok'
78
+ cmd.ensure_string('option1')
79
+
80
+ cmd.option2 = None
81
+ cmd.ensure_string('option2', 'xxx')
82
+ assert hasattr(cmd, 'option2')
83
+
84
+ cmd.option3 = 1
85
+ with pytest.raises(DistutilsOptionError):
86
+ cmd.ensure_string('option3')
87
+
88
+ def test_ensure_filename(self, cmd):
89
+ cmd.option1 = __file__
90
+ cmd.ensure_filename('option1')
91
+ cmd.option2 = 'xxx'
92
+ with pytest.raises(DistutilsOptionError):
93
+ cmd.ensure_filename('option2')
94
+
95
+ def test_ensure_dirname(self, cmd):
96
+ cmd.option1 = os.path.dirname(__file__) or os.curdir
97
+ cmd.ensure_dirname('option1')
98
+ cmd.option2 = 'xxx'
99
+ with pytest.raises(DistutilsOptionError):
100
+ cmd.ensure_dirname('option2')
101
+
102
+ def test_debug_print(self, cmd, capsys, monkeypatch):
103
+ cmd.debug_print('xxx')
104
+ assert capsys.readouterr().out == ''
105
+ monkeypatch.setattr(debug, 'DEBUG', True)
106
+ cmd.debug_print('xxx')
107
+ assert capsys.readouterr().out == 'xxx\n'
python/Lib/site-packages/setuptools/_distutils/tests/test_config_cmd.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.config."""
2
+
3
+ import os
4
+ import sys
5
+ from distutils._log import log
6
+ from distutils.command.config import config, dump_file
7
+ from distutils.tests import missing_compiler_executable, support
8
+
9
+ import more_itertools
10
+ import path
11
+ import pytest
12
+
13
+
14
+ @pytest.fixture(autouse=True)
15
+ def info_log(request, monkeypatch):
16
+ self = request.instance
17
+ self._logs = []
18
+ monkeypatch.setattr(log, 'info', self._info)
19
+
20
+
21
+ @support.combine_markers
22
+ class TestConfig(support.TempdirManager):
23
+ def _info(self, msg, *args):
24
+ for line in msg.splitlines():
25
+ self._logs.append(line)
26
+
27
+ def test_dump_file(self):
28
+ this_file = path.Path(__file__).with_suffix('.py')
29
+ with this_file.open(encoding='utf-8') as f:
30
+ numlines = more_itertools.ilen(f)
31
+
32
+ dump_file(this_file, 'I am the header')
33
+ assert len(self._logs) == numlines + 1
34
+
35
+ @pytest.mark.skipif('platform.system() == "Windows"')
36
+ def test_search_cpp(self):
37
+ cmd = missing_compiler_executable(['preprocessor'])
38
+ if cmd is not None:
39
+ self.skipTest(f'The {cmd!r} command is not found')
40
+ pkg_dir, dist = self.create_dist()
41
+ cmd = config(dist)
42
+ cmd._check_compiler()
43
+ compiler = cmd.compiler
44
+ if sys.platform[:3] == "aix" and "xlc" in compiler.preprocessor[0].lower():
45
+ self.skipTest(
46
+ 'xlc: The -E option overrides the -P, -o, and -qsyntaxonly options'
47
+ )
48
+
49
+ # simple pattern searches
50
+ match = cmd.search_cpp(pattern='xxx', body='/* xxx */')
51
+ assert match == 0
52
+
53
+ match = cmd.search_cpp(pattern='_configtest', body='/* xxx */')
54
+ assert match == 1
55
+
56
+ def test_finalize_options(self):
57
+ # finalize_options does a bit of transformation
58
+ # on options
59
+ pkg_dir, dist = self.create_dist()
60
+ cmd = config(dist)
61
+ cmd.include_dirs = f'one{os.pathsep}two'
62
+ cmd.libraries = 'one'
63
+ cmd.library_dirs = f'three{os.pathsep}four'
64
+ cmd.ensure_finalized()
65
+
66
+ assert cmd.include_dirs == ['one', 'two']
67
+ assert cmd.libraries == ['one']
68
+ assert cmd.library_dirs == ['three', 'four']
69
+
70
+ def test_clean(self):
71
+ # _clean removes files
72
+ tmp_dir = self.mkdtemp()
73
+ f1 = os.path.join(tmp_dir, 'one')
74
+ f2 = os.path.join(tmp_dir, 'two')
75
+
76
+ self.write_file(f1, 'xxx')
77
+ self.write_file(f2, 'xxx')
78
+
79
+ for f in (f1, f2):
80
+ assert os.path.exists(f)
81
+
82
+ pkg_dir, dist = self.create_dist()
83
+ cmd = config(dist)
84
+ cmd._clean(f1, f2)
85
+
86
+ for f in (f1, f2):
87
+ assert not os.path.exists(f)
python/Lib/site-packages/setuptools/_distutils/tests/test_core.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.core."""
2
+
3
+ import distutils.core
4
+ import io
5
+ import os
6
+ import sys
7
+ from distutils.dist import Distribution
8
+
9
+ import pytest
10
+
11
+ # setup script that uses __file__
12
+ setup_using___file__ = """\
13
+
14
+ __file__
15
+
16
+ from distutils.core import setup
17
+ setup()
18
+ """
19
+
20
+ setup_prints_cwd = """\
21
+
22
+ import os
23
+ print(os.getcwd())
24
+
25
+ from distutils.core import setup
26
+ setup()
27
+ """
28
+
29
+ setup_does_nothing = """\
30
+ from distutils.core import setup
31
+ setup()
32
+ """
33
+
34
+
35
+ setup_defines_subclass = """\
36
+ from distutils.core import setup
37
+ from distutils.command.install import install as _install
38
+
39
+ class install(_install):
40
+ sub_commands = _install.sub_commands + ['cmd']
41
+
42
+ setup(cmdclass={'install': install})
43
+ """
44
+
45
+ setup_within_if_main = """\
46
+ from distutils.core import setup
47
+
48
+ def main():
49
+ return setup(name="setup_within_if_main")
50
+
51
+ if __name__ == "__main__":
52
+ main()
53
+ """
54
+
55
+
56
+ @pytest.fixture(autouse=True)
57
+ def save_stdout(monkeypatch):
58
+ monkeypatch.setattr(sys, 'stdout', sys.stdout)
59
+
60
+
61
+ @pytest.fixture
62
+ def temp_file(tmp_path):
63
+ return tmp_path / 'file'
64
+
65
+
66
+ @pytest.mark.usefixtures('save_env')
67
+ @pytest.mark.usefixtures('save_argv')
68
+ class TestCore:
69
+ def test_run_setup_provides_file(self, temp_file):
70
+ # Make sure the script can use __file__; if that's missing, the test
71
+ # setup.py script will raise NameError.
72
+ temp_file.write_text(setup_using___file__, encoding='utf-8')
73
+ distutils.core.run_setup(temp_file)
74
+
75
+ def test_run_setup_preserves_sys_argv(self, temp_file):
76
+ # Make sure run_setup does not clobber sys.argv
77
+ argv_copy = sys.argv.copy()
78
+ temp_file.write_text(setup_does_nothing, encoding='utf-8')
79
+ distutils.core.run_setup(temp_file)
80
+ assert sys.argv == argv_copy
81
+
82
+ def test_run_setup_defines_subclass(self, temp_file):
83
+ # Make sure the script can use __file__; if that's missing, the test
84
+ # setup.py script will raise NameError.
85
+ temp_file.write_text(setup_defines_subclass, encoding='utf-8')
86
+ dist = distutils.core.run_setup(temp_file)
87
+ install = dist.get_command_obj('install')
88
+ assert 'cmd' in install.sub_commands
89
+
90
+ def test_run_setup_uses_current_dir(self, tmp_path):
91
+ """
92
+ Test that the setup script is run with the current directory
93
+ as its own current directory.
94
+ """
95
+ sys.stdout = io.StringIO()
96
+ cwd = os.getcwd()
97
+
98
+ # Create a directory and write the setup.py file there:
99
+ setup_py = tmp_path / 'setup.py'
100
+ setup_py.write_text(setup_prints_cwd, encoding='utf-8')
101
+ distutils.core.run_setup(setup_py)
102
+
103
+ output = sys.stdout.getvalue()
104
+ if output.endswith("\n"):
105
+ output = output[:-1]
106
+ assert cwd == output
107
+
108
+ def test_run_setup_within_if_main(self, temp_file):
109
+ temp_file.write_text(setup_within_if_main, encoding='utf-8')
110
+ dist = distutils.core.run_setup(temp_file, stop_after="config")
111
+ assert isinstance(dist, Distribution)
112
+ assert dist.get_name() == "setup_within_if_main"
113
+
114
+ def test_run_commands(self, temp_file):
115
+ sys.argv = ['setup.py', 'build']
116
+ temp_file.write_text(setup_within_if_main, encoding='utf-8')
117
+ dist = distutils.core.run_setup(temp_file, stop_after="commandline")
118
+ assert 'build' not in dist.have_run
119
+ distutils.core.run_commands(dist)
120
+ assert 'build' in dist.have_run
121
+
122
+ def test_debug_mode(self, capsys, monkeypatch):
123
+ # this covers the code called when DEBUG is set
124
+ sys.argv = ['setup.py', '--name']
125
+ distutils.core.setup(name='bar')
126
+ assert capsys.readouterr().out == 'bar\n'
127
+ monkeypatch.setattr(distutils.core, 'DEBUG', True)
128
+ distutils.core.setup(name='bar')
129
+ wanted = "options (after parsing config files):\n"
130
+ assert capsys.readouterr().out.startswith(wanted)
python/Lib/site-packages/setuptools/_distutils/tests/test_dir_util.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.dir_util."""
2
+
3
+ import os
4
+ import pathlib
5
+ import stat
6
+ import sys
7
+ import unittest.mock as mock
8
+ from distutils import dir_util, errors
9
+ from distutils.dir_util import (
10
+ copy_tree,
11
+ create_tree,
12
+ ensure_relative,
13
+ mkpath,
14
+ remove_tree,
15
+ )
16
+ from distutils.tests import support
17
+
18
+ import jaraco.path
19
+ import path
20
+ import pytest
21
+
22
+
23
+ @pytest.fixture(autouse=True)
24
+ def stuff(request, monkeypatch, distutils_managed_tempdir):
25
+ self = request.instance
26
+ tmp_dir = self.mkdtemp()
27
+ self.root_target = os.path.join(tmp_dir, 'deep')
28
+ self.target = os.path.join(self.root_target, 'here')
29
+ self.target2 = os.path.join(tmp_dir, 'deep2')
30
+
31
+
32
+ class TestDirUtil(support.TempdirManager):
33
+ def test_mkpath_remove_tree_verbosity(self, caplog):
34
+ mkpath(self.target, verbose=False)
35
+ assert not caplog.records
36
+ remove_tree(self.root_target, verbose=False)
37
+
38
+ mkpath(self.target, verbose=True)
39
+ wanted = [f'creating {self.target}']
40
+ assert caplog.messages == wanted
41
+ caplog.clear()
42
+
43
+ remove_tree(self.root_target, verbose=True)
44
+ wanted = [f"removing '{self.root_target}' (and everything under it)"]
45
+ assert caplog.messages == wanted
46
+
47
+ @pytest.mark.skipif("platform.system() == 'Windows'")
48
+ def test_mkpath_with_custom_mode(self):
49
+ # Get and set the current umask value for testing mode bits.
50
+ umask = os.umask(0o002)
51
+ os.umask(umask)
52
+ mkpath(self.target, 0o700)
53
+ assert stat.S_IMODE(os.stat(self.target).st_mode) == 0o700 & ~umask
54
+ mkpath(self.target2, 0o555)
55
+ assert stat.S_IMODE(os.stat(self.target2).st_mode) == 0o555 & ~umask
56
+
57
+ def test_create_tree_verbosity(self, caplog):
58
+ create_tree(self.root_target, ['one', 'two', 'three'], verbose=False)
59
+ assert caplog.messages == []
60
+ remove_tree(self.root_target, verbose=False)
61
+
62
+ wanted = [f'creating {self.root_target}']
63
+ create_tree(self.root_target, ['one', 'two', 'three'], verbose=True)
64
+ assert caplog.messages == wanted
65
+
66
+ remove_tree(self.root_target, verbose=False)
67
+
68
+ def test_copy_tree_verbosity(self, caplog):
69
+ mkpath(self.target, verbose=False)
70
+
71
+ copy_tree(self.target, self.target2, verbose=False)
72
+ assert caplog.messages == []
73
+
74
+ remove_tree(self.root_target, verbose=False)
75
+
76
+ mkpath(self.target, verbose=False)
77
+ a_file = path.Path(self.target) / 'ok.txt'
78
+ jaraco.path.build({'ok.txt': 'some content'}, self.target)
79
+
80
+ wanted = [f'copying {a_file} -> {self.target2}']
81
+ copy_tree(self.target, self.target2, verbose=True)
82
+ assert caplog.messages == wanted
83
+
84
+ remove_tree(self.root_target, verbose=False)
85
+ remove_tree(self.target2, verbose=False)
86
+
87
+ def test_copy_tree_skips_nfs_temp_files(self):
88
+ mkpath(self.target, verbose=False)
89
+
90
+ jaraco.path.build({'ok.txt': 'some content', '.nfs123abc': ''}, self.target)
91
+
92
+ copy_tree(self.target, self.target2)
93
+ assert os.listdir(self.target2) == ['ok.txt']
94
+
95
+ remove_tree(self.root_target, verbose=False)
96
+ remove_tree(self.target2, verbose=False)
97
+
98
+ def test_ensure_relative(self):
99
+ if os.sep == '/':
100
+ assert ensure_relative('/home/foo') == 'home/foo'
101
+ assert ensure_relative('some/path') == 'some/path'
102
+ else: # \\
103
+ assert ensure_relative('c:\\home\\foo') == 'c:home\\foo'
104
+ assert ensure_relative('home\\foo') == 'home\\foo'
105
+
106
+ def test_copy_tree_exception_in_listdir(self):
107
+ """
108
+ An exception in listdir should raise a DistutilsFileError
109
+ """
110
+ with (
111
+ mock.patch("os.listdir", side_effect=OSError()),
112
+ pytest.raises(errors.DistutilsFileError),
113
+ ):
114
+ src = self.tempdirs[-1]
115
+ dir_util.copy_tree(src, None)
116
+
117
+ def test_mkpath_exception_uncached(self, monkeypatch, tmp_path):
118
+ """
119
+ Caching should not remember failed attempts.
120
+
121
+ pypa/distutils#304
122
+ """
123
+
124
+ class FailPath(pathlib.Path):
125
+ def mkdir(self, *args, **kwargs):
126
+ raise OSError("Failed to create directory")
127
+
128
+ if sys.version_info < (3, 12):
129
+ _flavour = pathlib.Path()._flavour
130
+
131
+ target = tmp_path / 'foodir'
132
+
133
+ with pytest.raises(errors.DistutilsFileError):
134
+ mkpath(FailPath(target))
135
+
136
+ assert not target.exists()
137
+
138
+ mkpath(target)
139
+ assert target.exists()
python/Lib/site-packages/setuptools/_distutils/tests/test_dist.py ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.dist."""
2
+
3
+ import email
4
+ import email.generator
5
+ import email.policy
6
+ import functools
7
+ import io
8
+ import os
9
+ import sys
10
+ import textwrap
11
+ import unittest.mock as mock
12
+ import warnings
13
+ from distutils.cmd import Command
14
+ from distutils.dist import Distribution, fix_help_options
15
+ from distutils.tests import support
16
+ from typing import ClassVar
17
+
18
+ import jaraco.path
19
+ import pytest
20
+
21
+ pydistutils_cfg = '.' * (os.name == 'posix') + 'pydistutils.cfg'
22
+
23
+
24
+ class test_dist(Command):
25
+ """Sample distutils extension command."""
26
+
27
+ user_options: ClassVar[list[tuple[str, str, str]]] = [
28
+ ("sample-option=", "S", "help text"),
29
+ ]
30
+
31
+ def initialize_options(self):
32
+ self.sample_option = None
33
+
34
+
35
+ class TestDistribution(Distribution):
36
+ """Distribution subclasses that avoids the default search for
37
+ configuration files.
38
+
39
+ The ._config_files attribute must be set before
40
+ .parse_config_files() is called.
41
+ """
42
+
43
+ def find_config_files(self):
44
+ return self._config_files
45
+
46
+
47
+ @pytest.fixture
48
+ def clear_argv():
49
+ del sys.argv[1:]
50
+
51
+
52
+ @support.combine_markers
53
+ @pytest.mark.usefixtures('save_env')
54
+ @pytest.mark.usefixtures('save_argv')
55
+ class TestDistributionBehavior(support.TempdirManager):
56
+ def create_distribution(self, configfiles=()):
57
+ d = TestDistribution()
58
+ d._config_files = configfiles
59
+ d.parse_config_files()
60
+ d.parse_command_line()
61
+ return d
62
+
63
+ def test_command_packages_unspecified(self, clear_argv):
64
+ sys.argv.append("build")
65
+ d = self.create_distribution()
66
+ assert d.get_command_packages() == ["distutils.command"]
67
+
68
+ def test_command_packages_cmdline(self, clear_argv):
69
+ from distutils.tests.test_dist import test_dist
70
+
71
+ sys.argv.extend([
72
+ "--command-packages",
73
+ "foo.bar,distutils.tests",
74
+ "test_dist",
75
+ "-Ssometext",
76
+ ])
77
+ d = self.create_distribution()
78
+ # let's actually try to load our test command:
79
+ assert d.get_command_packages() == [
80
+ "distutils.command",
81
+ "foo.bar",
82
+ "distutils.tests",
83
+ ]
84
+ cmd = d.get_command_obj("test_dist")
85
+ assert isinstance(cmd, test_dist)
86
+ assert cmd.sample_option == "sometext"
87
+
88
+ @pytest.mark.skipif(
89
+ 'distutils' not in Distribution.parse_config_files.__module__,
90
+ reason='Cannot test when virtualenv has monkey-patched Distribution',
91
+ )
92
+ def test_venv_install_options(self, tmp_path, clear_argv):
93
+ sys.argv.append("install")
94
+ file = str(tmp_path / 'file')
95
+
96
+ fakepath = '/somedir'
97
+
98
+ jaraco.path.build({
99
+ file: f"""
100
+ [install]
101
+ install-base = {fakepath}
102
+ install-platbase = {fakepath}
103
+ install-lib = {fakepath}
104
+ install-platlib = {fakepath}
105
+ install-purelib = {fakepath}
106
+ install-headers = {fakepath}
107
+ install-scripts = {fakepath}
108
+ install-data = {fakepath}
109
+ prefix = {fakepath}
110
+ exec-prefix = {fakepath}
111
+ home = {fakepath}
112
+ user = {fakepath}
113
+ root = {fakepath}
114
+ """,
115
+ })
116
+
117
+ # Base case: Not in a Virtual Environment
118
+ with mock.patch.multiple(sys, prefix='/a', base_prefix='/a'):
119
+ d = self.create_distribution([file])
120
+
121
+ option_tuple = (file, fakepath)
122
+
123
+ result_dict = {
124
+ 'install_base': option_tuple,
125
+ 'install_platbase': option_tuple,
126
+ 'install_lib': option_tuple,
127
+ 'install_platlib': option_tuple,
128
+ 'install_purelib': option_tuple,
129
+ 'install_headers': option_tuple,
130
+ 'install_scripts': option_tuple,
131
+ 'install_data': option_tuple,
132
+ 'prefix': option_tuple,
133
+ 'exec_prefix': option_tuple,
134
+ 'home': option_tuple,
135
+ 'user': option_tuple,
136
+ 'root': option_tuple,
137
+ }
138
+
139
+ assert sorted(d.command_options.get('install').keys()) == sorted(
140
+ result_dict.keys()
141
+ )
142
+
143
+ for key, value in d.command_options.get('install').items():
144
+ assert value == result_dict[key]
145
+
146
+ # Test case: In a Virtual Environment
147
+ with mock.patch.multiple(sys, prefix='/a', base_prefix='/b'):
148
+ d = self.create_distribution([file])
149
+
150
+ for key in result_dict.keys():
151
+ assert key not in d.command_options.get('install', {})
152
+
153
+ def test_command_packages_configfile(self, tmp_path, clear_argv):
154
+ sys.argv.append("build")
155
+ file = str(tmp_path / "file")
156
+ jaraco.path.build({
157
+ file: """
158
+ [global]
159
+ command_packages = foo.bar, splat
160
+ """,
161
+ })
162
+
163
+ d = self.create_distribution([file])
164
+ assert d.get_command_packages() == ["distutils.command", "foo.bar", "splat"]
165
+
166
+ # ensure command line overrides config:
167
+ sys.argv[1:] = ["--command-packages", "spork", "build"]
168
+ d = self.create_distribution([file])
169
+ assert d.get_command_packages() == ["distutils.command", "spork"]
170
+
171
+ # Setting --command-packages to '' should cause the default to
172
+ # be used even if a config file specified something else:
173
+ sys.argv[1:] = ["--command-packages", "", "build"]
174
+ d = self.create_distribution([file])
175
+ assert d.get_command_packages() == ["distutils.command"]
176
+
177
+ def test_empty_options(self, request):
178
+ # an empty options dictionary should not stay in the
179
+ # list of attributes
180
+
181
+ # catching warnings
182
+ warns = []
183
+
184
+ def _warn(msg):
185
+ warns.append(msg)
186
+
187
+ request.addfinalizer(
188
+ functools.partial(setattr, warnings, 'warn', warnings.warn)
189
+ )
190
+ warnings.warn = _warn
191
+ dist = Distribution(
192
+ attrs={
193
+ 'author': 'xxx',
194
+ 'name': 'xxx',
195
+ 'version': 'xxx',
196
+ 'url': 'xxxx',
197
+ 'options': {},
198
+ }
199
+ )
200
+
201
+ assert len(warns) == 0
202
+ assert 'options' not in dir(dist)
203
+
204
+ def test_finalize_options(self):
205
+ attrs = {'keywords': 'one,two', 'platforms': 'one,two'}
206
+
207
+ dist = Distribution(attrs=attrs)
208
+ dist.finalize_options()
209
+
210
+ # finalize_option splits platforms and keywords
211
+ assert dist.metadata.platforms == ['one', 'two']
212
+ assert dist.metadata.keywords == ['one', 'two']
213
+
214
+ attrs = {'keywords': 'foo bar', 'platforms': 'foo bar'}
215
+ dist = Distribution(attrs=attrs)
216
+ dist.finalize_options()
217
+ assert dist.metadata.platforms == ['foo bar']
218
+ assert dist.metadata.keywords == ['foo bar']
219
+
220
+ def test_get_command_packages(self):
221
+ dist = Distribution()
222
+ assert dist.command_packages is None
223
+ cmds = dist.get_command_packages()
224
+ assert cmds == ['distutils.command']
225
+ assert dist.command_packages == ['distutils.command']
226
+
227
+ dist.command_packages = 'one,two'
228
+ cmds = dist.get_command_packages()
229
+ assert cmds == ['distutils.command', 'one', 'two']
230
+
231
+ def test_announce(self):
232
+ # make sure the level is known
233
+ dist = Distribution()
234
+ with pytest.raises(TypeError):
235
+ dist.announce('ok', level='ok2')
236
+
237
+ def test_find_config_files_disable(self, temp_home):
238
+ # Ticket #1180: Allow user to disable their home config file.
239
+ jaraco.path.build({pydistutils_cfg: '[distutils]\n'}, temp_home)
240
+
241
+ d = Distribution()
242
+ all_files = d.find_config_files()
243
+
244
+ d = Distribution(attrs={'script_args': ['--no-user-cfg']})
245
+ files = d.find_config_files()
246
+
247
+ # make sure --no-user-cfg disables the user cfg file
248
+ assert len(all_files) - 1 == len(files)
249
+
250
+ def test_script_args_list_coercion(self):
251
+ d = Distribution(attrs={'script_args': ('build', '--no-user-cfg')})
252
+
253
+ # make sure script_args is a list even if it started as a different iterable
254
+ assert d.script_args == ['build', '--no-user-cfg']
255
+
256
+ @pytest.mark.skipif(
257
+ 'platform.system() == "Windows"',
258
+ reason='Windows does not honor chmod 000',
259
+ )
260
+ def test_find_config_files_permission_error(self, fake_home):
261
+ """
262
+ Finding config files should not fail when directory is inaccessible.
263
+ """
264
+ fake_home.joinpath(pydistutils_cfg).write_text('', encoding='utf-8')
265
+ fake_home.chmod(0o000)
266
+ Distribution().find_config_files()
267
+
268
+
269
+ @pytest.mark.usefixtures('save_env')
270
+ @pytest.mark.usefixtures('save_argv')
271
+ class TestMetadata(support.TempdirManager):
272
+ def format_metadata(self, dist):
273
+ sio = io.StringIO()
274
+ dist.metadata.write_pkg_file(sio)
275
+ return sio.getvalue()
276
+
277
+ def test_simple_metadata(self):
278
+ attrs = {"name": "package", "version": "1.0"}
279
+ dist = Distribution(attrs)
280
+ meta = self.format_metadata(dist)
281
+ assert "Metadata-Version: 1.0" in meta
282
+ assert "provides:" not in meta.lower()
283
+ assert "requires:" not in meta.lower()
284
+ assert "obsoletes:" not in meta.lower()
285
+
286
+ def test_provides(self):
287
+ attrs = {
288
+ "name": "package",
289
+ "version": "1.0",
290
+ "provides": ["package", "package.sub"],
291
+ }
292
+ dist = Distribution(attrs)
293
+ assert dist.metadata.get_provides() == ["package", "package.sub"]
294
+ assert dist.get_provides() == ["package", "package.sub"]
295
+ meta = self.format_metadata(dist)
296
+ assert "Metadata-Version: 1.1" in meta
297
+ assert "requires:" not in meta.lower()
298
+ assert "obsoletes:" not in meta.lower()
299
+
300
+ def test_provides_illegal(self):
301
+ with pytest.raises(ValueError):
302
+ Distribution(
303
+ {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]},
304
+ )
305
+
306
+ def test_requires(self):
307
+ attrs = {
308
+ "name": "package",
309
+ "version": "1.0",
310
+ "requires": ["other", "another (==1.0)"],
311
+ }
312
+ dist = Distribution(attrs)
313
+ assert dist.metadata.get_requires() == ["other", "another (==1.0)"]
314
+ assert dist.get_requires() == ["other", "another (==1.0)"]
315
+ meta = self.format_metadata(dist)
316
+ assert "Metadata-Version: 1.1" in meta
317
+ assert "provides:" not in meta.lower()
318
+ assert "Requires: other" in meta
319
+ assert "Requires: another (==1.0)" in meta
320
+ assert "obsoletes:" not in meta.lower()
321
+
322
+ def test_requires_illegal(self):
323
+ with pytest.raises(ValueError):
324
+ Distribution(
325
+ {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]},
326
+ )
327
+
328
+ def test_requires_to_list(self):
329
+ attrs = {"name": "package", "requires": iter(["other"])}
330
+ dist = Distribution(attrs)
331
+ assert isinstance(dist.metadata.requires, list)
332
+
333
+ def test_obsoletes(self):
334
+ attrs = {
335
+ "name": "package",
336
+ "version": "1.0",
337
+ "obsoletes": ["other", "another (<1.0)"],
338
+ }
339
+ dist = Distribution(attrs)
340
+ assert dist.metadata.get_obsoletes() == ["other", "another (<1.0)"]
341
+ assert dist.get_obsoletes() == ["other", "another (<1.0)"]
342
+ meta = self.format_metadata(dist)
343
+ assert "Metadata-Version: 1.1" in meta
344
+ assert "provides:" not in meta.lower()
345
+ assert "requires:" not in meta.lower()
346
+ assert "Obsoletes: other" in meta
347
+ assert "Obsoletes: another (<1.0)" in meta
348
+
349
+ def test_obsoletes_illegal(self):
350
+ with pytest.raises(ValueError):
351
+ Distribution(
352
+ {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]},
353
+ )
354
+
355
+ def test_obsoletes_to_list(self):
356
+ attrs = {"name": "package", "obsoletes": iter(["other"])}
357
+ dist = Distribution(attrs)
358
+ assert isinstance(dist.metadata.obsoletes, list)
359
+
360
+ def test_classifier(self):
361
+ attrs = {
362
+ 'name': 'Boa',
363
+ 'version': '3.0',
364
+ 'classifiers': ['Programming Language :: Python :: 3'],
365
+ }
366
+ dist = Distribution(attrs)
367
+ assert dist.get_classifiers() == ['Programming Language :: Python :: 3']
368
+ meta = self.format_metadata(dist)
369
+ assert 'Metadata-Version: 1.1' in meta
370
+
371
+ def test_classifier_invalid_type(self, caplog):
372
+ attrs = {
373
+ 'name': 'Boa',
374
+ 'version': '3.0',
375
+ 'classifiers': ('Programming Language :: Python :: 3',),
376
+ }
377
+ d = Distribution(attrs)
378
+ # should have warning about passing a non-list
379
+ assert 'should be a list' in caplog.messages[0]
380
+ # should be converted to a list
381
+ assert isinstance(d.metadata.classifiers, list)
382
+ assert d.metadata.classifiers == list(attrs['classifiers'])
383
+
384
+ def test_keywords(self):
385
+ attrs = {
386
+ 'name': 'Monty',
387
+ 'version': '1.0',
388
+ 'keywords': ['spam', 'eggs', 'life of brian'],
389
+ }
390
+ dist = Distribution(attrs)
391
+ assert dist.get_keywords() == ['spam', 'eggs', 'life of brian']
392
+
393
+ def test_keywords_invalid_type(self, caplog):
394
+ attrs = {
395
+ 'name': 'Monty',
396
+ 'version': '1.0',
397
+ 'keywords': ('spam', 'eggs', 'life of brian'),
398
+ }
399
+ d = Distribution(attrs)
400
+ # should have warning about passing a non-list
401
+ assert 'should be a list' in caplog.messages[0]
402
+ # should be converted to a list
403
+ assert isinstance(d.metadata.keywords, list)
404
+ assert d.metadata.keywords == list(attrs['keywords'])
405
+
406
+ def test_platforms(self):
407
+ attrs = {
408
+ 'name': 'Monty',
409
+ 'version': '1.0',
410
+ 'platforms': ['GNU/Linux', 'Some Evil Platform'],
411
+ }
412
+ dist = Distribution(attrs)
413
+ assert dist.get_platforms() == ['GNU/Linux', 'Some Evil Platform']
414
+
415
+ def test_platforms_invalid_types(self, caplog):
416
+ attrs = {
417
+ 'name': 'Monty',
418
+ 'version': '1.0',
419
+ 'platforms': ('GNU/Linux', 'Some Evil Platform'),
420
+ }
421
+ d = Distribution(attrs)
422
+ # should have warning about passing a non-list
423
+ assert 'should be a list' in caplog.messages[0]
424
+ # should be converted to a list
425
+ assert isinstance(d.metadata.platforms, list)
426
+ assert d.metadata.platforms == list(attrs['platforms'])
427
+
428
+ def test_download_url(self):
429
+ attrs = {
430
+ 'name': 'Boa',
431
+ 'version': '3.0',
432
+ 'download_url': 'http://example.org/boa',
433
+ }
434
+ dist = Distribution(attrs)
435
+ meta = self.format_metadata(dist)
436
+ assert 'Metadata-Version: 1.1' in meta
437
+
438
+ def test_long_description(self):
439
+ long_desc = textwrap.dedent(
440
+ """\
441
+ example::
442
+ We start here
443
+ and continue here
444
+ and end here."""
445
+ )
446
+ attrs = {"name": "package", "version": "1.0", "long_description": long_desc}
447
+
448
+ dist = Distribution(attrs)
449
+ meta = self.format_metadata(dist)
450
+ meta = meta.replace('\n' + 8 * ' ', '\n')
451
+ assert long_desc in meta
452
+
453
+ def test_custom_pydistutils(self, temp_home):
454
+ """
455
+ pydistutils.cfg is found
456
+ """
457
+ jaraco.path.build({pydistutils_cfg: ''}, temp_home)
458
+ config_path = temp_home / pydistutils_cfg
459
+
460
+ assert str(config_path) in Distribution().find_config_files()
461
+
462
+ def test_extra_pydistutils(self, monkeypatch, tmp_path):
463
+ jaraco.path.build({'overrides.cfg': ''}, tmp_path)
464
+ filename = tmp_path / 'overrides.cfg'
465
+ monkeypatch.setenv('DIST_EXTRA_CONFIG', str(filename))
466
+ assert str(filename) in Distribution().find_config_files()
467
+
468
+ def test_fix_help_options(self):
469
+ help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
470
+ fancy_options = fix_help_options(help_tuples)
471
+ assert fancy_options[0] == ('a', 'b', 'c')
472
+ assert fancy_options[1] == (1, 2, 3)
473
+
474
+ def test_show_help(self, request, capsys):
475
+ # smoke test, just makes sure some help is displayed
476
+ dist = Distribution()
477
+ sys.argv = []
478
+ dist.help = True
479
+ dist.script_name = 'setup.py'
480
+ dist.parse_command_line()
481
+
482
+ output = [
483
+ line for line in capsys.readouterr().out.split('\n') if line.strip() != ''
484
+ ]
485
+ assert output
486
+
487
+ def test_read_metadata(self):
488
+ attrs = {
489
+ "name": "package",
490
+ "version": "1.0",
491
+ "long_description": "desc",
492
+ "description": "xxx",
493
+ "download_url": "http://example.com",
494
+ "keywords": ['one', 'two'],
495
+ "requires": ['foo'],
496
+ }
497
+
498
+ dist = Distribution(attrs)
499
+ metadata = dist.metadata
500
+
501
+ # write it then reloads it
502
+ PKG_INFO = io.StringIO()
503
+ metadata.write_pkg_file(PKG_INFO)
504
+ PKG_INFO.seek(0)
505
+ metadata.read_pkg_file(PKG_INFO)
506
+
507
+ assert metadata.name == "package"
508
+ assert metadata.version == "1.0"
509
+ assert metadata.description == "xxx"
510
+ assert metadata.download_url == 'http://example.com'
511
+ assert metadata.keywords == ['one', 'two']
512
+ assert metadata.platforms is None
513
+ assert metadata.obsoletes is None
514
+ assert metadata.requires == ['foo']
515
+
516
+ def test_round_trip_through_email_generator(self):
517
+ """
518
+ In pypa/setuptools#4033, it was shown that once PKG-INFO is
519
+ re-generated using ``email.generator.Generator``, some control
520
+ characters might cause problems.
521
+ """
522
+ # Given a PKG-INFO file ...
523
+ attrs = {
524
+ "name": "package",
525
+ "version": "1.0",
526
+ "long_description": "hello\x0b\nworld\n",
527
+ }
528
+ dist = Distribution(attrs)
529
+ metadata = dist.metadata
530
+
531
+ with io.StringIO() as buffer:
532
+ metadata.write_pkg_file(buffer)
533
+ msg = buffer.getvalue()
534
+
535
+ # ... when it is read and re-written using stdlib's email library,
536
+ orig = email.message_from_string(msg)
537
+ policy = email.policy.EmailPolicy(
538
+ utf8=True,
539
+ mangle_from_=False,
540
+ max_line_length=0,
541
+ )
542
+ with io.StringIO() as buffer:
543
+ email.generator.Generator(buffer, policy=policy).flatten(orig)
544
+
545
+ buffer.seek(0)
546
+ regen = email.message_from_file(buffer)
547
+
548
+ # ... then it should be the same as the original
549
+ # (except for the specific line break characters)
550
+ orig_desc = set(orig["Description"].splitlines())
551
+ regen_desc = set(regen["Description"].splitlines())
552
+ assert regen_desc == orig_desc
python/Lib/site-packages/setuptools/_distutils/tests/test_extension.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.extension."""
2
+
3
+ import os
4
+ import pathlib
5
+ import warnings
6
+ from distutils.extension import Extension, read_setup_file
7
+
8
+ import pytest
9
+ from test.support.warnings_helper import check_warnings
10
+
11
+
12
+ class TestExtension:
13
+ def test_read_setup_file(self):
14
+ # trying to read a Setup file
15
+ # (sample extracted from the PyGame project)
16
+ setup = os.path.join(os.path.dirname(__file__), 'Setup.sample')
17
+
18
+ exts = read_setup_file(setup)
19
+ names = [ext.name for ext in exts]
20
+ names.sort()
21
+
22
+ # here are the extensions read_setup_file should have created
23
+ # out of the file
24
+ wanted = [
25
+ '_arraysurfarray',
26
+ '_camera',
27
+ '_numericsndarray',
28
+ '_numericsurfarray',
29
+ 'base',
30
+ 'bufferproxy',
31
+ 'cdrom',
32
+ 'color',
33
+ 'constants',
34
+ 'display',
35
+ 'draw',
36
+ 'event',
37
+ 'fastevent',
38
+ 'font',
39
+ 'gfxdraw',
40
+ 'image',
41
+ 'imageext',
42
+ 'joystick',
43
+ 'key',
44
+ 'mask',
45
+ 'mixer',
46
+ 'mixer_music',
47
+ 'mouse',
48
+ 'movie',
49
+ 'overlay',
50
+ 'pixelarray',
51
+ 'pypm',
52
+ 'rect',
53
+ 'rwobject',
54
+ 'scrap',
55
+ 'surface',
56
+ 'surflock',
57
+ 'time',
58
+ 'transform',
59
+ ]
60
+
61
+ assert names == wanted
62
+
63
+ def test_extension_init(self):
64
+ # the first argument, which is the name, must be a string
65
+ with pytest.raises(TypeError):
66
+ Extension(1, [])
67
+ ext = Extension('name', [])
68
+ assert ext.name == 'name'
69
+
70
+ # the second argument, which is the list of files, must
71
+ # be an iterable of strings or PathLike objects, and not a string
72
+ with pytest.raises(TypeError):
73
+ Extension('name', 'file')
74
+ with pytest.raises(TypeError):
75
+ Extension('name', ['file', 1])
76
+ ext = Extension('name', ['file1', 'file2'])
77
+ assert ext.sources == ['file1', 'file2']
78
+ ext = Extension('name', [pathlib.Path('file1'), pathlib.Path('file2')])
79
+ assert ext.sources == ['file1', 'file2']
80
+
81
+ # any non-string iterable of strings or PathLike objects should work
82
+ ext = Extension('name', ('file1', 'file2')) # tuple
83
+ assert ext.sources == ['file1', 'file2']
84
+ ext = Extension('name', {'file1', 'file2'}) # set
85
+ assert sorted(ext.sources) == ['file1', 'file2']
86
+ ext = Extension('name', iter(['file1', 'file2'])) # iterator
87
+ assert ext.sources == ['file1', 'file2']
88
+ ext = Extension('name', [pathlib.Path('file1'), 'file2']) # mixed types
89
+ assert ext.sources == ['file1', 'file2']
90
+
91
+ # others arguments have defaults
92
+ for attr in (
93
+ 'include_dirs',
94
+ 'define_macros',
95
+ 'undef_macros',
96
+ 'library_dirs',
97
+ 'libraries',
98
+ 'runtime_library_dirs',
99
+ 'extra_objects',
100
+ 'extra_compile_args',
101
+ 'extra_link_args',
102
+ 'export_symbols',
103
+ 'swig_opts',
104
+ 'depends',
105
+ ):
106
+ assert getattr(ext, attr) == []
107
+
108
+ assert ext.language is None
109
+ assert ext.optional is None
110
+
111
+ # if there are unknown keyword options, warn about them
112
+ with check_warnings() as w:
113
+ warnings.simplefilter('always')
114
+ ext = Extension('name', ['file1', 'file2'], chic=True)
115
+
116
+ assert len(w.warnings) == 1
117
+ assert str(w.warnings[0].message) == "Unknown Extension options: 'chic'"
python/Lib/site-packages/setuptools/_distutils/tests/test_file_util.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.file_util."""
2
+
3
+ import errno
4
+ import os
5
+ import unittest.mock as mock
6
+ from distutils.errors import DistutilsFileError
7
+ from distutils.file_util import copy_file, move_file
8
+
9
+ import jaraco.path
10
+ import pytest
11
+
12
+
13
+ @pytest.fixture(autouse=True)
14
+ def stuff(request, tmp_path):
15
+ self = request.instance
16
+ self.source = tmp_path / 'f1'
17
+ self.target = tmp_path / 'f2'
18
+ self.target_dir = tmp_path / 'd1'
19
+
20
+
21
+ class TestFileUtil:
22
+ def test_move_file_verbosity(self, caplog):
23
+ jaraco.path.build({self.source: 'some content'})
24
+
25
+ move_file(self.source, self.target, verbose=False)
26
+ assert not caplog.messages
27
+
28
+ # back to original state
29
+ move_file(self.target, self.source, verbose=False)
30
+
31
+ move_file(self.source, self.target, verbose=True)
32
+ wanted = [f'moving {self.source} -> {self.target}']
33
+ assert caplog.messages == wanted
34
+
35
+ # back to original state
36
+ move_file(self.target, self.source, verbose=False)
37
+
38
+ caplog.clear()
39
+ # now the target is a dir
40
+ os.mkdir(self.target_dir)
41
+ move_file(self.source, self.target_dir, verbose=True)
42
+ wanted = [f'moving {self.source} -> {self.target_dir}']
43
+ assert caplog.messages == wanted
44
+
45
+ def test_move_file_exception_unpacking_rename(self):
46
+ # see issue 22182
47
+ with (
48
+ mock.patch("os.rename", side_effect=OSError("wrong", 1)),
49
+ pytest.raises(DistutilsFileError),
50
+ ):
51
+ jaraco.path.build({self.source: 'spam eggs'})
52
+ move_file(self.source, self.target, verbose=False)
53
+
54
+ def test_move_file_exception_unpacking_unlink(self):
55
+ # see issue 22182
56
+ with (
57
+ mock.patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")),
58
+ mock.patch("os.unlink", side_effect=OSError("wrong", 1)),
59
+ pytest.raises(DistutilsFileError),
60
+ ):
61
+ jaraco.path.build({self.source: 'spam eggs'})
62
+ move_file(self.source, self.target, verbose=False)
63
+
64
+ def test_copy_file_hard_link(self):
65
+ jaraco.path.build({self.source: 'some content'})
66
+ # Check first that copy_file() will not fall back on copying the file
67
+ # instead of creating the hard link.
68
+ try:
69
+ os.link(self.source, self.target)
70
+ except OSError as e:
71
+ self.skipTest(f'os.link: {e}')
72
+ else:
73
+ self.target.unlink()
74
+ st = os.stat(self.source)
75
+ copy_file(self.source, self.target, link='hard')
76
+ st2 = os.stat(self.source)
77
+ st3 = os.stat(self.target)
78
+ assert os.path.samestat(st, st2), (st, st2)
79
+ assert os.path.samestat(st2, st3), (st2, st3)
80
+ assert self.source.read_text(encoding='utf-8') == 'some content'
81
+
82
+ def test_copy_file_hard_link_failure(self):
83
+ # If hard linking fails, copy_file() falls back on copying file
84
+ # (some special filesystems don't support hard linking even under
85
+ # Unix, see issue #8876).
86
+ jaraco.path.build({self.source: 'some content'})
87
+ st = os.stat(self.source)
88
+ with mock.patch("os.link", side_effect=OSError(0, "linking unsupported")):
89
+ copy_file(self.source, self.target, link='hard')
90
+ st2 = os.stat(self.source)
91
+ st3 = os.stat(self.target)
92
+ assert os.path.samestat(st, st2), (st, st2)
93
+ assert not os.path.samestat(st2, st3), (st2, st3)
94
+ for fn in (self.source, self.target):
95
+ assert fn.read_text(encoding='utf-8') == 'some content'
python/Lib/site-packages/setuptools/_distutils/tests/test_filelist.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.filelist."""
2
+
3
+ import logging
4
+ import os
5
+ import re
6
+ from distutils import debug, filelist
7
+ from distutils.errors import DistutilsTemplateError
8
+ from distutils.filelist import FileList, glob_to_re, translate_pattern
9
+
10
+ import jaraco.path
11
+ import pytest
12
+
13
+ from .compat import py39 as os_helper
14
+
15
+ MANIFEST_IN = """\
16
+ include ok
17
+ include xo
18
+ exclude xo
19
+ include foo.tmp
20
+ include buildout.cfg
21
+ global-include *.x
22
+ global-include *.txt
23
+ global-exclude *.tmp
24
+ recursive-include f *.oo
25
+ recursive-exclude global *.x
26
+ graft dir
27
+ prune dir3
28
+ """
29
+
30
+
31
+ def make_local_path(s):
32
+ """Converts '/' in a string to os.sep"""
33
+ return s.replace('/', os.sep)
34
+
35
+
36
+ class TestFileList:
37
+ def assertNoWarnings(self, caplog):
38
+ warnings = [rec for rec in caplog.records if rec.levelno == logging.WARNING]
39
+ assert not warnings
40
+ caplog.clear()
41
+
42
+ def assertWarnings(self, caplog):
43
+ warnings = [rec for rec in caplog.records if rec.levelno == logging.WARNING]
44
+ assert warnings
45
+ caplog.clear()
46
+
47
+ def test_glob_to_re(self):
48
+ sep = os.sep
49
+ if os.sep == '\\':
50
+ sep = re.escape(os.sep)
51
+
52
+ for glob, regex in (
53
+ # simple cases
54
+ ('foo*', r'(?s:foo[^%(sep)s]*)\Z'),
55
+ ('foo?', r'(?s:foo[^%(sep)s])\Z'),
56
+ ('foo??', r'(?s:foo[^%(sep)s][^%(sep)s])\Z'),
57
+ # special cases
58
+ (r'foo\\*', r'(?s:foo\\\\[^%(sep)s]*)\Z'),
59
+ (r'foo\\\*', r'(?s:foo\\\\\\[^%(sep)s]*)\Z'),
60
+ ('foo????', r'(?s:foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s])\Z'),
61
+ (r'foo\\??', r'(?s:foo\\\\[^%(sep)s][^%(sep)s])\Z'),
62
+ ):
63
+ regex = regex % {'sep': sep}
64
+ assert glob_to_re(glob) == regex
65
+
66
+ def test_process_template_line(self):
67
+ # testing all MANIFEST.in template patterns
68
+ file_list = FileList()
69
+ mlp = make_local_path
70
+
71
+ # simulated file list
72
+ file_list.allfiles = [
73
+ 'foo.tmp',
74
+ 'ok',
75
+ 'xo',
76
+ 'four.txt',
77
+ 'buildout.cfg',
78
+ # filelist does not filter out VCS directories,
79
+ # it's sdist that does
80
+ mlp('.hg/last-message.txt'),
81
+ mlp('global/one.txt'),
82
+ mlp('global/two.txt'),
83
+ mlp('global/files.x'),
84
+ mlp('global/here.tmp'),
85
+ mlp('f/o/f.oo'),
86
+ mlp('dir/graft-one'),
87
+ mlp('dir/dir2/graft2'),
88
+ mlp('dir3/ok'),
89
+ mlp('dir3/sub/ok.txt'),
90
+ ]
91
+
92
+ for line in MANIFEST_IN.split('\n'):
93
+ if line.strip() == '':
94
+ continue
95
+ file_list.process_template_line(line)
96
+
97
+ wanted = [
98
+ 'ok',
99
+ 'buildout.cfg',
100
+ 'four.txt',
101
+ mlp('.hg/last-message.txt'),
102
+ mlp('global/one.txt'),
103
+ mlp('global/two.txt'),
104
+ mlp('f/o/f.oo'),
105
+ mlp('dir/graft-one'),
106
+ mlp('dir/dir2/graft2'),
107
+ ]
108
+
109
+ assert file_list.files == wanted
110
+
111
+ def test_debug_print(self, capsys, monkeypatch):
112
+ file_list = FileList()
113
+ file_list.debug_print('xxx')
114
+ assert capsys.readouterr().out == ''
115
+
116
+ monkeypatch.setattr(debug, 'DEBUG', True)
117
+ file_list.debug_print('xxx')
118
+ assert capsys.readouterr().out == 'xxx\n'
119
+
120
+ def test_set_allfiles(self):
121
+ file_list = FileList()
122
+ files = ['a', 'b', 'c']
123
+ file_list.set_allfiles(files)
124
+ assert file_list.allfiles == files
125
+
126
+ def test_remove_duplicates(self):
127
+ file_list = FileList()
128
+ file_list.files = ['a', 'b', 'a', 'g', 'c', 'g']
129
+ # files must be sorted beforehand (sdist does it)
130
+ file_list.sort()
131
+ file_list.remove_duplicates()
132
+ assert file_list.files == ['a', 'b', 'c', 'g']
133
+
134
+ def test_translate_pattern(self):
135
+ # not regex
136
+ assert hasattr(translate_pattern('a', anchor=True, is_regex=False), 'search')
137
+
138
+ # is a regex
139
+ regex = re.compile('a')
140
+ assert translate_pattern(regex, anchor=True, is_regex=True) == regex
141
+
142
+ # plain string flagged as regex
143
+ assert hasattr(translate_pattern('a', anchor=True, is_regex=True), 'search')
144
+
145
+ # glob support
146
+ assert translate_pattern('*.py', anchor=True, is_regex=False).search(
147
+ 'filelist.py'
148
+ )
149
+
150
+ def test_exclude_pattern(self):
151
+ # return False if no match
152
+ file_list = FileList()
153
+ assert not file_list.exclude_pattern('*.py')
154
+
155
+ # return True if files match
156
+ file_list = FileList()
157
+ file_list.files = ['a.py', 'b.py']
158
+ assert file_list.exclude_pattern('*.py')
159
+
160
+ # test excludes
161
+ file_list = FileList()
162
+ file_list.files = ['a.py', 'a.txt']
163
+ file_list.exclude_pattern('*.py')
164
+ assert file_list.files == ['a.txt']
165
+
166
+ def test_include_pattern(self):
167
+ # return False if no match
168
+ file_list = FileList()
169
+ file_list.set_allfiles([])
170
+ assert not file_list.include_pattern('*.py')
171
+
172
+ # return True if files match
173
+ file_list = FileList()
174
+ file_list.set_allfiles(['a.py', 'b.txt'])
175
+ assert file_list.include_pattern('*.py')
176
+
177
+ # test * matches all files
178
+ file_list = FileList()
179
+ assert file_list.allfiles is None
180
+ file_list.set_allfiles(['a.py', 'b.txt'])
181
+ file_list.include_pattern('*')
182
+ assert file_list.allfiles == ['a.py', 'b.txt']
183
+
184
+ def test_process_template(self, caplog):
185
+ mlp = make_local_path
186
+ # invalid lines
187
+ file_list = FileList()
188
+ for action in (
189
+ 'include',
190
+ 'exclude',
191
+ 'global-include',
192
+ 'global-exclude',
193
+ 'recursive-include',
194
+ 'recursive-exclude',
195
+ 'graft',
196
+ 'prune',
197
+ 'blarg',
198
+ ):
199
+ with pytest.raises(DistutilsTemplateError):
200
+ file_list.process_template_line(action)
201
+
202
+ # include
203
+ file_list = FileList()
204
+ file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')])
205
+
206
+ file_list.process_template_line('include *.py')
207
+ assert file_list.files == ['a.py']
208
+ self.assertNoWarnings(caplog)
209
+
210
+ file_list.process_template_line('include *.rb')
211
+ assert file_list.files == ['a.py']
212
+ self.assertWarnings(caplog)
213
+
214
+ # exclude
215
+ file_list = FileList()
216
+ file_list.files = ['a.py', 'b.txt', mlp('d/c.py')]
217
+
218
+ file_list.process_template_line('exclude *.py')
219
+ assert file_list.files == ['b.txt', mlp('d/c.py')]
220
+ self.assertNoWarnings(caplog)
221
+
222
+ file_list.process_template_line('exclude *.rb')
223
+ assert file_list.files == ['b.txt', mlp('d/c.py')]
224
+ self.assertWarnings(caplog)
225
+
226
+ # global-include
227
+ file_list = FileList()
228
+ file_list.set_allfiles(['a.py', 'b.txt', mlp('d/c.py')])
229
+
230
+ file_list.process_template_line('global-include *.py')
231
+ assert file_list.files == ['a.py', mlp('d/c.py')]
232
+ self.assertNoWarnings(caplog)
233
+
234
+ file_list.process_template_line('global-include *.rb')
235
+ assert file_list.files == ['a.py', mlp('d/c.py')]
236
+ self.assertWarnings(caplog)
237
+
238
+ # global-exclude
239
+ file_list = FileList()
240
+ file_list.files = ['a.py', 'b.txt', mlp('d/c.py')]
241
+
242
+ file_list.process_template_line('global-exclude *.py')
243
+ assert file_list.files == ['b.txt']
244
+ self.assertNoWarnings(caplog)
245
+
246
+ file_list.process_template_line('global-exclude *.rb')
247
+ assert file_list.files == ['b.txt']
248
+ self.assertWarnings(caplog)
249
+
250
+ # recursive-include
251
+ file_list = FileList()
252
+ file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')])
253
+
254
+ file_list.process_template_line('recursive-include d *.py')
255
+ assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')]
256
+ self.assertNoWarnings(caplog)
257
+
258
+ file_list.process_template_line('recursive-include e *.py')
259
+ assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')]
260
+ self.assertWarnings(caplog)
261
+
262
+ # recursive-exclude
263
+ file_list = FileList()
264
+ file_list.files = ['a.py', mlp('d/b.py'), mlp('d/c.txt'), mlp('d/d/e.py')]
265
+
266
+ file_list.process_template_line('recursive-exclude d *.py')
267
+ assert file_list.files == ['a.py', mlp('d/c.txt')]
268
+ self.assertNoWarnings(caplog)
269
+
270
+ file_list.process_template_line('recursive-exclude e *.py')
271
+ assert file_list.files == ['a.py', mlp('d/c.txt')]
272
+ self.assertWarnings(caplog)
273
+
274
+ # graft
275
+ file_list = FileList()
276
+ file_list.set_allfiles(['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')])
277
+
278
+ file_list.process_template_line('graft d')
279
+ assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')]
280
+ self.assertNoWarnings(caplog)
281
+
282
+ file_list.process_template_line('graft e')
283
+ assert file_list.files == [mlp('d/b.py'), mlp('d/d/e.py')]
284
+ self.assertWarnings(caplog)
285
+
286
+ # prune
287
+ file_list = FileList()
288
+ file_list.files = ['a.py', mlp('d/b.py'), mlp('d/d/e.py'), mlp('f/f.py')]
289
+
290
+ file_list.process_template_line('prune d')
291
+ assert file_list.files == ['a.py', mlp('f/f.py')]
292
+ self.assertNoWarnings(caplog)
293
+
294
+ file_list.process_template_line('prune e')
295
+ assert file_list.files == ['a.py', mlp('f/f.py')]
296
+ self.assertWarnings(caplog)
297
+
298
+
299
+ class TestFindAll:
300
+ @os_helper.skip_unless_symlink
301
+ def test_missing_symlink(self, temp_cwd):
302
+ os.symlink('foo', 'bar')
303
+ assert filelist.findall() == []
304
+
305
+ def test_basic_discovery(self, temp_cwd):
306
+ """
307
+ When findall is called with no parameters or with
308
+ '.' as the parameter, the dot should be omitted from
309
+ the results.
310
+ """
311
+ jaraco.path.build({'foo': {'file1.txt': ''}, 'bar': {'file2.txt': ''}})
312
+ file1 = os.path.join('foo', 'file1.txt')
313
+ file2 = os.path.join('bar', 'file2.txt')
314
+ expected = [file2, file1]
315
+ assert sorted(filelist.findall()) == expected
316
+
317
+ def test_non_local_discovery(self, tmp_path):
318
+ """
319
+ When findall is called with another path, the full
320
+ path name should be returned.
321
+ """
322
+ jaraco.path.build({'file1.txt': ''}, tmp_path)
323
+ expected = [str(tmp_path / 'file1.txt')]
324
+ assert filelist.findall(tmp_path) == expected
325
+
326
+ @os_helper.skip_unless_symlink
327
+ def test_symlink_loop(self, tmp_path):
328
+ jaraco.path.build(
329
+ {
330
+ 'link-to-parent': jaraco.path.Symlink('.'),
331
+ 'somefile': '',
332
+ },
333
+ tmp_path,
334
+ )
335
+ files = filelist.findall(tmp_path)
336
+ assert len(files) == 1
python/Lib/site-packages/setuptools/_distutils/tests/test_install.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.install."""
2
+
3
+ import logging
4
+ import os
5
+ import pathlib
6
+ import site
7
+ import sys
8
+ from distutils import sysconfig
9
+ from distutils.command import install as install_module
10
+ from distutils.command.build_ext import build_ext
11
+ from distutils.command.install import INSTALL_SCHEMES, install
12
+ from distutils.core import Distribution
13
+ from distutils.errors import DistutilsOptionError
14
+ from distutils.extension import Extension
15
+ from distutils.tests import missing_compiler_executable, support
16
+ from distutils.util import is_mingw
17
+
18
+ import pytest
19
+
20
+
21
+ def _make_ext_name(modname):
22
+ return modname + sysconfig.get_config_var('EXT_SUFFIX')
23
+
24
+
25
+ @support.combine_markers
26
+ @pytest.mark.usefixtures('save_env')
27
+ class TestInstall(
28
+ support.TempdirManager,
29
+ ):
30
+ @pytest.mark.xfail(
31
+ 'platform.system() == "Windows" and sys.version_info > (3, 11)',
32
+ reason="pypa/distutils#148",
33
+ )
34
+ def test_home_installation_scheme(self):
35
+ # This ensure two things:
36
+ # - that --home generates the desired set of directory names
37
+ # - test --home is supported on all platforms
38
+ builddir = self.mkdtemp()
39
+ destination = os.path.join(builddir, "installation")
40
+
41
+ dist = Distribution({"name": "foopkg"})
42
+ # script_name need not exist, it just need to be initialized
43
+ dist.script_name = os.path.join(builddir, "setup.py")
44
+ dist.command_obj["build"] = support.DummyCommand(
45
+ build_base=builddir,
46
+ build_lib=os.path.join(builddir, "lib"),
47
+ )
48
+
49
+ cmd = install(dist)
50
+ cmd.home = destination
51
+ cmd.ensure_finalized()
52
+
53
+ assert cmd.install_base == destination
54
+ assert cmd.install_platbase == destination
55
+
56
+ def check_path(got, expected):
57
+ got = os.path.normpath(got)
58
+ expected = os.path.normpath(expected)
59
+ assert got == expected
60
+
61
+ impl_name = sys.implementation.name.replace("cpython", "python")
62
+ libdir = os.path.join(destination, "lib", impl_name)
63
+ check_path(cmd.install_lib, libdir)
64
+ _platlibdir = getattr(sys, "platlibdir", "lib")
65
+ platlibdir = os.path.join(destination, _platlibdir, impl_name)
66
+ check_path(cmd.install_platlib, platlibdir)
67
+ check_path(cmd.install_purelib, libdir)
68
+ check_path(
69
+ cmd.install_headers,
70
+ os.path.join(destination, "include", impl_name, "foopkg"),
71
+ )
72
+ check_path(cmd.install_scripts, os.path.join(destination, "bin"))
73
+ check_path(cmd.install_data, destination)
74
+
75
+ def test_user_site(self, monkeypatch):
76
+ # test install with --user
77
+ # preparing the environment for the test
78
+ self.tmpdir = self.mkdtemp()
79
+ orig_site = site.USER_SITE
80
+ orig_base = site.USER_BASE
81
+ monkeypatch.setattr(site, 'USER_BASE', os.path.join(self.tmpdir, 'B'))
82
+ monkeypatch.setattr(site, 'USER_SITE', os.path.join(self.tmpdir, 'S'))
83
+ monkeypatch.setattr(install_module, 'USER_BASE', site.USER_BASE)
84
+ monkeypatch.setattr(install_module, 'USER_SITE', site.USER_SITE)
85
+
86
+ def _expanduser(path):
87
+ if path.startswith('~'):
88
+ return os.path.normpath(self.tmpdir + path[1:])
89
+ return path
90
+
91
+ monkeypatch.setattr(os.path, 'expanduser', _expanduser)
92
+
93
+ for key in ('nt_user', 'posix_user'):
94
+ assert key in INSTALL_SCHEMES
95
+
96
+ dist = Distribution({'name': 'xx'})
97
+ cmd = install(dist)
98
+
99
+ # making sure the user option is there
100
+ options = [name for name, short, label in cmd.user_options]
101
+ assert 'user' in options
102
+
103
+ # setting a value
104
+ cmd.user = True
105
+
106
+ # user base and site shouldn't be created yet
107
+ assert not os.path.exists(site.USER_BASE)
108
+ assert not os.path.exists(site.USER_SITE)
109
+
110
+ # let's run finalize
111
+ cmd.ensure_finalized()
112
+
113
+ # now they should
114
+ assert os.path.exists(site.USER_BASE)
115
+ assert os.path.exists(site.USER_SITE)
116
+
117
+ assert 'userbase' in cmd.config_vars
118
+ assert 'usersite' in cmd.config_vars
119
+
120
+ actual_headers = os.path.relpath(cmd.install_headers, site.USER_BASE)
121
+ if os.name == 'nt' and not is_mingw():
122
+ site_path = os.path.relpath(os.path.dirname(orig_site), orig_base)
123
+ include = os.path.join(site_path, 'Include')
124
+ else:
125
+ include = sysconfig.get_python_inc(0, '')
126
+ expect_headers = os.path.join(include, 'xx')
127
+
128
+ assert os.path.normcase(actual_headers) == os.path.normcase(expect_headers)
129
+
130
+ def test_handle_extra_path(self):
131
+ dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'})
132
+ cmd = install(dist)
133
+
134
+ # two elements
135
+ cmd.handle_extra_path()
136
+ assert cmd.extra_path == ['path', 'dirs']
137
+ assert cmd.extra_dirs == 'dirs'
138
+ assert cmd.path_file == 'path'
139
+
140
+ # one element
141
+ cmd.extra_path = ['path']
142
+ cmd.handle_extra_path()
143
+ assert cmd.extra_path == ['path']
144
+ assert cmd.extra_dirs == 'path'
145
+ assert cmd.path_file == 'path'
146
+
147
+ # none
148
+ dist.extra_path = cmd.extra_path = None
149
+ cmd.handle_extra_path()
150
+ assert cmd.extra_path is None
151
+ assert cmd.extra_dirs == ''
152
+ assert cmd.path_file is None
153
+
154
+ # three elements (no way !)
155
+ cmd.extra_path = 'path,dirs,again'
156
+ with pytest.raises(DistutilsOptionError):
157
+ cmd.handle_extra_path()
158
+
159
+ def test_finalize_options(self):
160
+ dist = Distribution({'name': 'xx'})
161
+ cmd = install(dist)
162
+
163
+ # must supply either prefix/exec-prefix/home or
164
+ # install-base/install-platbase -- not both
165
+ cmd.prefix = 'prefix'
166
+ cmd.install_base = 'base'
167
+ with pytest.raises(DistutilsOptionError):
168
+ cmd.finalize_options()
169
+
170
+ # must supply either home or prefix/exec-prefix -- not both
171
+ cmd.install_base = None
172
+ cmd.home = 'home'
173
+ with pytest.raises(DistutilsOptionError):
174
+ cmd.finalize_options()
175
+
176
+ # can't combine user with prefix/exec_prefix/home or
177
+ # install_(plat)base
178
+ cmd.prefix = None
179
+ cmd.user = 'user'
180
+ with pytest.raises(DistutilsOptionError):
181
+ cmd.finalize_options()
182
+
183
+ def test_record(self):
184
+ install_dir = self.mkdtemp()
185
+ project_dir, dist = self.create_dist(py_modules=['hello'], scripts=['sayhi'])
186
+ os.chdir(project_dir)
187
+ self.write_file('hello.py', "def main(): print('o hai')")
188
+ self.write_file('sayhi', 'from hello import main; main()')
189
+
190
+ cmd = install(dist)
191
+ dist.command_obj['install'] = cmd
192
+ cmd.root = install_dir
193
+ cmd.record = os.path.join(project_dir, 'filelist')
194
+ cmd.ensure_finalized()
195
+ cmd.run()
196
+
197
+ content = pathlib.Path(cmd.record).read_text(encoding='utf-8')
198
+
199
+ found = [pathlib.Path(line).name for line in content.splitlines()]
200
+ expected = [
201
+ 'hello.py',
202
+ f'hello.{sys.implementation.cache_tag}.pyc',
203
+ 'sayhi',
204
+ 'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]),
205
+ ]
206
+ assert found == expected
207
+
208
+ def test_record_extensions(self):
209
+ cmd = missing_compiler_executable()
210
+ if cmd is not None:
211
+ pytest.skip(f'The {cmd!r} command is not found')
212
+ install_dir = self.mkdtemp()
213
+ project_dir, dist = self.create_dist(
214
+ ext_modules=[Extension('xx', ['xxmodule.c'])]
215
+ )
216
+ os.chdir(project_dir)
217
+ support.copy_xxmodule_c(project_dir)
218
+
219
+ buildextcmd = build_ext(dist)
220
+ support.fixup_build_ext(buildextcmd)
221
+ buildextcmd.ensure_finalized()
222
+
223
+ cmd = install(dist)
224
+ dist.command_obj['install'] = cmd
225
+ dist.command_obj['build_ext'] = buildextcmd
226
+ cmd.root = install_dir
227
+ cmd.record = os.path.join(project_dir, 'filelist')
228
+ cmd.ensure_finalized()
229
+ cmd.run()
230
+
231
+ content = pathlib.Path(cmd.record).read_text(encoding='utf-8')
232
+
233
+ found = [pathlib.Path(line).name for line in content.splitlines()]
234
+ expected = [
235
+ _make_ext_name('xx'),
236
+ 'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]),
237
+ ]
238
+ assert found == expected
239
+
240
+ def test_debug_mode(self, caplog, monkeypatch):
241
+ # this covers the code called when DEBUG is set
242
+ monkeypatch.setattr(install_module, 'DEBUG', True)
243
+ caplog.set_level(logging.DEBUG)
244
+ self.test_record()
245
+ assert any(rec for rec in caplog.records if rec.levelno == logging.DEBUG)
python/Lib/site-packages/setuptools/_distutils/tests/test_install_data.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.install_data."""
2
+
3
+ import os
4
+ import pathlib
5
+ from distutils.command.install_data import install_data
6
+ from distutils.tests import support
7
+
8
+ import pytest
9
+
10
+
11
+ @pytest.mark.usefixtures('save_env')
12
+ class TestInstallData(
13
+ support.TempdirManager,
14
+ ):
15
+ def test_simple_run(self):
16
+ pkg_dir, dist = self.create_dist()
17
+ cmd = install_data(dist)
18
+ cmd.install_dir = inst = os.path.join(pkg_dir, 'inst')
19
+
20
+ # data_files can contain
21
+ # - simple files
22
+ # - a Path object
23
+ # - a tuple with a path, and a list of file
24
+ one = os.path.join(pkg_dir, 'one')
25
+ self.write_file(one, 'xxx')
26
+ inst2 = os.path.join(pkg_dir, 'inst2')
27
+ two = os.path.join(pkg_dir, 'two')
28
+ self.write_file(two, 'xxx')
29
+ three = pathlib.Path(pkg_dir) / 'three'
30
+ self.write_file(three, 'xxx')
31
+
32
+ cmd.data_files = [one, (inst2, [two]), three]
33
+ assert cmd.get_inputs() == [one, (inst2, [two]), three]
34
+
35
+ # let's run the command
36
+ cmd.ensure_finalized()
37
+ cmd.run()
38
+
39
+ # let's check the result
40
+ assert len(cmd.get_outputs()) == 3
41
+ rthree = os.path.split(one)[-1]
42
+ assert os.path.exists(os.path.join(inst, rthree))
43
+ rtwo = os.path.split(two)[-1]
44
+ assert os.path.exists(os.path.join(inst2, rtwo))
45
+ rone = os.path.split(one)[-1]
46
+ assert os.path.exists(os.path.join(inst, rone))
47
+ cmd.outfiles = []
48
+
49
+ # let's try with warn_dir one
50
+ cmd.warn_dir = True
51
+ cmd.ensure_finalized()
52
+ cmd.run()
53
+
54
+ # let's check the result
55
+ assert len(cmd.get_outputs()) == 3
56
+ assert os.path.exists(os.path.join(inst, rthree))
57
+ assert os.path.exists(os.path.join(inst2, rtwo))
58
+ assert os.path.exists(os.path.join(inst, rone))
59
+ cmd.outfiles = []
60
+
61
+ # now using root and empty dir
62
+ cmd.root = os.path.join(pkg_dir, 'root')
63
+ inst5 = os.path.join(pkg_dir, 'inst5')
64
+ four = os.path.join(cmd.install_dir, 'four')
65
+ self.write_file(four, 'xx')
66
+ cmd.data_files = [one, (inst2, [two]), three, ('inst5', [four]), (inst5, [])]
67
+ cmd.ensure_finalized()
68
+ cmd.run()
69
+
70
+ # let's check the result
71
+ assert len(cmd.get_outputs()) == 5
72
+ assert os.path.exists(os.path.join(inst, rthree))
73
+ assert os.path.exists(os.path.join(inst2, rtwo))
74
+ assert os.path.exists(os.path.join(inst, rone))
python/Lib/site-packages/setuptools/_distutils/tests/test_install_headers.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.install_headers."""
2
+
3
+ import os
4
+ from distutils.command.install_headers import install_headers
5
+ from distutils.tests import support
6
+
7
+ import pytest
8
+
9
+
10
+ @pytest.mark.usefixtures('save_env')
11
+ class TestInstallHeaders(
12
+ support.TempdirManager,
13
+ ):
14
+ def test_simple_run(self):
15
+ # we have two headers
16
+ header_list = self.mkdtemp()
17
+ header1 = os.path.join(header_list, 'header1')
18
+ header2 = os.path.join(header_list, 'header2')
19
+ self.write_file(header1)
20
+ self.write_file(header2)
21
+ headers = [header1, header2]
22
+
23
+ pkg_dir, dist = self.create_dist(headers=headers)
24
+ cmd = install_headers(dist)
25
+ assert cmd.get_inputs() == headers
26
+
27
+ # let's run the command
28
+ cmd.install_dir = os.path.join(pkg_dir, 'inst')
29
+ cmd.ensure_finalized()
30
+ cmd.run()
31
+
32
+ # let's check the results
33
+ assert len(cmd.get_outputs()) == 2
python/Lib/site-packages/setuptools/_vendor/autocommand/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (418 Bytes). View file
 
python/Lib/site-packages/setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-313.pyc ADDED
Binary file (4.86 kB). View file
 
python/Lib/site-packages/setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-313.pyc ADDED
Binary file (1.31 kB). View file
 
python/Lib/site-packages/setuptools/_vendor/autocommand/__pycache__/automain.cpython-313.pyc ADDED
Binary file (1.88 kB). View file