Debian Codegraph @

test/sanity/code-smell/package-data.py

raw
1 """Verify the contents of the built sdist and wheel."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import fnmatch
7 import os
8 import pathlib
9 import re
10 import shutil
11 import subprocess
12 import sys
13 import tarfile
14 import tempfile
15 import typing as t
16 import zipfile
17
18 from ansible.release import __version__
19
20 fuzzy_match_basenames: set[str] = {'COPYING'}
21 """Account for PEP639 differences in the placement of some files."""
22
23
24 def collect_sdist_files(complete_file_list: list[str]) -> list[str]:
25 """Return a list of files which should be present in the sdist."""
26 ignore_patterns = (
27 '.azure-pipelines/*',
28 '.cherry_picker.toml',
29 '.claude/*',
30 '.git*',
31 '.mailmap',
32 'bin/*',
33 'changelogs/README.md',
34 'changelogs/config.yaml',
35 'changelogs/fragments/*',
36 'AGENTS.md',
37 'CLAUDE.md',
38 'context/*',
39 'hacking/*',
40 )
41
42 sdist_files = [path for path in complete_file_list if not any(fnmatch.fnmatch(path, ignore) for ignore in ignore_patterns)]
43
44 egg_info = (
45 'PKG-INFO',
46 'SOURCES.txt',
47 'dependency_links.txt',
48 'entry_points.txt',
49 'requires.txt',
50 'top_level.txt',
51 )
52
53 sdist_files.append('PKG-INFO')
54 sdist_files.append('setup.cfg')
55 sdist_files.extend(f'ansible_core.egg-info/{name}' for name in egg_info)
56
57 return sdist_files
58
59
60 def collect_wheel_files(complete_file_list: list[str]) -> list[str]:
61 """Return a list of files which should be present in the wheel."""
62 wheel_files = []
63 license_files = []
64
65 for path in complete_file_list:
66 if path.startswith('licenses/'):
67 license_files.append(os.path.relpath(path, 'licenses'))
68 fuzzy_match_basenames.add(os.path.basename(path))
69
70 if path.startswith('lib/ansible/'):
71 prefix = 'lib'
72 elif path.startswith('test/lib/ansible_test/'):
73 prefix = 'test/lib'
74 else:
75 continue
76
77 wheel_files.append(os.path.relpath(path, prefix))
78
79 dist_info = [
80 'COPYING',
81 'METADATA',
82 'RECORD',
83 'WHEEL',
84 'entry_points.txt',
85 'top_level.txt',
86 ] + license_files
87
88 wheel_files.extend(f'ansible_core-{__version__}.dist-info/{name}' for name in dist_info)
89
90 return wheel_files
91
92
93 @contextlib.contextmanager
94 def clean_repository(complete_file_list: list[str]) -> t.Generator[str, None, None]:
95 """Copy the files to a temporary directory and yield the path."""
96 directories = sorted(set(os.path.dirname(path) for path in complete_file_list))
97 directories.remove('')
98
99 with tempfile.TemporaryDirectory() as temp_dir:
100 for directory in directories:
101 os.makedirs(os.path.join(temp_dir, directory))
102
103 for path in complete_file_list:
104 shutil.copy2(path, os.path.join(temp_dir, path), follow_symlinks=False)
105
106 yield temp_dir
107
108
109 def build(source_dir: str, tmp_dir: str) -> tuple[pathlib.Path, pathlib.Path]:
110 """Create a sdist and wheel."""
111 create = subprocess.run( # pylint: disable=subprocess-run-check
112 [sys.executable, '-m', 'build', '--outdir', tmp_dir],
113 stdin=subprocess.DEVNULL,
114 capture_output=True,
115 text=True,
116 cwd=source_dir,
117 )
118
119 if create.returncode != 0:
120 raise RuntimeError(f'build failed:\n{create.stderr}\n{create.stdout}')
121
122 tmp_dir_files = list(pathlib.Path(tmp_dir).iterdir())
123
124 if len(tmp_dir_files) != 2:
125 raise RuntimeError(f'build resulted in {len(tmp_dir_files)} items instead of 2')
126
127 sdist_path = [path for path in tmp_dir_files if path.suffix == '.gz'][0]
128 wheel_path = [path for path in tmp_dir_files if path.suffix == '.whl'][0]
129
130 return sdist_path, wheel_path
131
132
133 def list_sdist(path: pathlib.Path) -> list[str]:
134 """Return a list of the files in the sdist."""
135 item: tarfile.TarInfo
136
137 with tarfile.open(path) as sdist:
138 paths = ['/'.join(pathlib.Path(item.path).parts[1:]) for item in sdist.getmembers() if not item.isdir()]
139
140 return paths
141
142
143 def list_wheel(path: pathlib.Path) -> list[str]:
144 """Return a list of the files in the wheel."""
145 with zipfile.ZipFile(path) as wheel:
146 paths = [item.filename for item in wheel.filelist if not item.is_dir()]
147
148 return paths
149
150
151 def filter_fuzzy_matches(missing: set[str], extra: set[str]) -> None:
152 """
153 Removes entries from `missing` and `extra` that share a common basename that also appears in `fuzzy_match_basenames`.
154 Accounts for variable placement of non-runtime files by different versions of setuptools.
155 """
156 if not (missing or extra):
157 return
158
159 # calculate a set of basenames that appear in both missing and extra that are also marked as possibly needing fuzzy matching
160 corresponding_fuzzy_basenames = {os.path.basename(p) for p in missing}.intersection(os.path.basename(p) for p in extra).intersection(fuzzy_match_basenames)
161
162 # filter successfully fuzzy-matched entries from missing and extra
163 missing.difference_update({p for p in missing if os.path.basename(p) in corresponding_fuzzy_basenames})
164 extra.difference_update({p for p in extra if os.path.basename(p) in corresponding_fuzzy_basenames})
165
166
167 def check_files(source: str, expected: list[str], actual: list[str]) -> list[str]:
168 """Verify the expected files exist and no extra files exist."""
169 missing = set(expected) - set(actual)
170 extra = set(actual) - set(expected)
171
172 filter_fuzzy_matches(missing, extra)
173
174 errors = [f'{path}: missing from {source}' for path in sorted(missing)] + [f'{path}: unexpected in {source}' for path in sorted(extra)]
175
176 return errors
177
178
179 def main() -> None:
180 """Main program entry point."""
181 complete_file_list = sys.argv[1:] or sys.stdin.read().splitlines()
182
183 python_version = '.'.join(map(str, sys.version_info[:2]))
184 python_min = os.environ['ANSIBLE_TEST_MIN_PYTHON']
185 python_max = os.environ['ANSIBLE_TEST_MAX_PYTHON']
186
187 if python_version == python_min:
188 use_upper_setuptools_version = False
189 elif python_version == python_max:
190 use_upper_setuptools_version = True
191 else:
192 raise RuntimeError(f'Python version {python_version} is neither the minimum {python_min} or the maximum {python_max}.')
193
194 errors = check_build(complete_file_list, use_upper_setuptools_version)
195
196 for error in errors:
197 print(error)
198
199
200 def set_setuptools_version(repo_dir: str, use_upper_version: bool) -> str:
201 pyproject_toml = pathlib.Path(repo_dir) / 'pyproject.toml'
202
203 current = pyproject_toml.read_text()
204 pattern = re.compile(r'^(?P<begin>requires = \["setuptools >= )(?P<lower>[^,]+)(?P<middle>, <= )(?P<upper>[^"]+)(?P<end>".*)$', re.MULTILINE)
205 match = pattern.search(current)
206
207 if not match:
208 raise RuntimeError(f"Unable to find the 'requires' entry in: {pyproject_toml}")
209
210 lower_version = match.group('lower')
211 upper_version = match.group('upper')
212
213 requested_version = upper_version if use_upper_version else lower_version
214
215 updated = pattern.sub(fr'\g<begin>{requested_version}\g<middle>{requested_version}\g<end>', current)
216
217 if current == updated:
218 raise RuntimeError("Failed to set the setuptools version.")
219
220 pyproject_toml.write_text(updated)
221
222 return requested_version
223
224
225 def check_build(complete_file_list: list[str], use_upper_setuptools_version: bool) -> list[str]:
226 errors: list[str] = []
227 complete_file_list = list(complete_file_list) # avoid mutation of input
228
229 # Limit visible files to those reported by ansible-test.
230 # This avoids including files which are not committed to git.
231 with clean_repository(complete_file_list) as clean_repo_dir:
232 setuptools_version = set_setuptools_version(clean_repo_dir, use_upper_setuptools_version)
233
234 if __version__.endswith('.dev0'):
235 # Make sure a changelog exists for this version when testing from devel.
236 # When testing from a stable branch the changelog will already exist.
237 major_minor_version = '.'.join(__version__.split('.')[:2])
238 changelog_path = f'changelogs/CHANGELOG-v{major_minor_version}.rst'
239 pathlib.Path(clean_repo_dir, changelog_path).touch()
240 complete_file_list.append(changelog_path)
241
242 expected_sdist_files = collect_sdist_files(complete_file_list)
243 expected_wheel_files = collect_wheel_files(complete_file_list)
244
245 with tempfile.TemporaryDirectory() as tmp_dir:
246 sdist_path, wheel_path = build(clean_repo_dir, tmp_dir)
247
248 actual_sdist_files = list_sdist(sdist_path)
249 actual_wheel_files = list_wheel(wheel_path)
250
251 errors.extend(check_files('sdist', expected_sdist_files, actual_sdist_files))
252 errors.extend(check_files('wheel', expected_wheel_files, actual_wheel_files))
253
254 errors = [f'{msg} (setuptools=={setuptools_version})' for msg in errors]
255
256 return errors
257
258
259 if __name__ == '__main__':
260 main()