Debian Codegraph @

hacking/update-sanity-requirements.py

raw
1 #!/usr/bin/env python
2 # PYTHON_ARGCOMPLETE_OK
3 """Generate frozen sanity test requirements from source requirements files."""
4
5 from __future__ import annotations
6
7 import argparse
8 import dataclasses
9 import pathlib
10 import re
11 import subprocess
12 import tempfile
13 import typing as t
14 import venv
15
16 import packaging.version
17 import packaging.specifiers
18 import packaging.requirements
19
20 try:
21 import argcomplete
22 except ImportError:
23 argcomplete = None
24
25
26 FILE = pathlib.Path(__file__).resolve()
27 ROOT = FILE.parent.parent
28 SELF = FILE.relative_to(ROOT)
29
30
31 @dataclasses.dataclass(frozen=True)
32 class SanityTest:
33 name: str
34 requirements_path: pathlib.Path
35 source_path: pathlib.Path
36
37 def freeze_requirements(self) -> None:
38 source_requirements = [packaging.requirements.Requirement(re.sub(' #.*$', '', line)) for line in self.source_path.read_text().splitlines()]
39
40 install_packages = {requirement.name for requirement in source_requirements}
41 exclude_packages = {'distribute', 'pip', 'setuptools', 'wheel'} - install_packages
42
43 with tempfile.TemporaryDirectory() as venv_dir:
44 venv.create(venv_dir, with_pip=True)
45
46 python = pathlib.Path(venv_dir, 'bin', 'python')
47 pip = [python, '-m', 'pip', '--disable-pip-version-check']
48 env = dict()
49
50 pip_freeze = subprocess.run(pip + ['freeze'], env=env, check=True, capture_output=True, text=True)
51
52 if pip_freeze.stdout:
53 raise Exception(f'Initial virtual environment is not empty:\n{pip_freeze.stdout}')
54
55 subprocess.run(pip + ['install', '-r', self.source_path], env=env, check=True)
56
57 freeze_options = ['--all']
58
59 for exclude_package in exclude_packages:
60 freeze_options.extend(('--exclude', exclude_package))
61
62 pip_freeze = subprocess.run(pip + ['freeze'] + freeze_options, env=env, check=True, capture_output=True, text=True)
63
64 self.write_requirements(pip_freeze.stdout)
65
66 def update_pre_build(self) -> None:
67 """Update requirements in place with current pre-build instructions."""
68 requirements = pathlib.Path(self.requirements_path).read_text()
69 lines = requirements.splitlines(keepends=True)
70 lines = [line for line in lines if not line.startswith('#')]
71 requirements = ''.join(lines)
72
73 self.write_requirements(requirements)
74
75 def write_requirements(self, requirements: str) -> None:
76 """Write the given test requirements to the requirements file for this test."""
77 pre_build = pre_build_instructions(requirements)
78
79 requirements = f'# edit "{self.source_path.name}" and generate with: {SELF} --test {self.name}\n{pre_build}{requirements}'
80
81 with open(self.requirements_path, 'w') as requirement_file:
82 requirement_file.write(requirements)
83
84 @staticmethod
85 def create(path: pathlib.Path) -> SanityTest:
86 return SanityTest(
87 name=path.stem.replace('sanity.', '').replace('.requirements', ''),
88 requirements_path=path,
89 source_path=path.with_suffix('.in'),
90 )
91
92
93 def pre_build_instructions(requirements: str) -> str:
94 """Parse the given requirements and return any applicable pre-build instructions."""
95 parsed_requirements = requirements.splitlines()
96
97 package_versions = {
98 match.group('package').lower(): match.group('version') for match
99 in (re.search('^(?P<package>.*)==(?P<version>.*)$', requirement) for requirement in parsed_requirements)
100 if match
101 }
102
103 instructions: list[str] = []
104
105 build_constraints = (
106 ('pyyaml', '>= 5.4, <= 6.0', ('Cython < 3.0',)),
107 )
108
109 for package, specifier, constraints in build_constraints:
110 version_string = package_versions.get(package)
111
112 if version_string:
113 version = packaging.version.Version(version_string)
114 specifier_set = packaging.specifiers.SpecifierSet(specifier)
115
116 if specifier_set.contains(version):
117 instructions.append(f'# pre-build requirement: {package} == {version}\n')
118
119 for constraint in constraints:
120 instructions.append(f'# pre-build constraint: {constraint}\n')
121
122 return ''.join(instructions)
123
124
125 def main() -> None:
126 tests = find_tests()
127
128 parser = argparse.ArgumentParser()
129 parser.add_argument(
130 '--test',
131 metavar='TEST',
132 dest='test_names',
133 action='append',
134 choices=[test.name for test in tests],
135 help='test requirements to update'
136 )
137
138 parser.add_argument(
139 '--pre-build-only',
140 action='store_true',
141 help='apply pre-build instructions to existing requirements',
142 )
143
144 if argcomplete:
145 argcomplete.autocomplete(parser)
146
147 args = parser.parse_args()
148 test_names: set[str] = set(args.test_names or [])
149
150 tests = [test for test in tests if test.name in test_names] if test_names else tests
151
152 for test in tests:
153 print(f'===[ {test.name} ]===', flush=True)
154
155 if args.pre_build_only:
156 test.update_pre_build()
157 else:
158 test.freeze_requirements()
159
160
161 def find_tests() -> t.List[SanityTest]:
162 globs = (
163 'test/lib/ansible_test/_data/requirements/sanity.*.txt',
164 'test/sanity/code-smell/*.requirements.txt',
165 )
166
167 tests: t.List[SanityTest] = []
168
169 for glob in globs:
170 tests.extend(get_tests(pathlib.Path(glob)))
171
172 return sorted(tests, key=lambda test: test.name)
173
174
175 def get_tests(glob: pathlib.Path) -> t.List[SanityTest]:
176 path = pathlib.Path(ROOT, glob.parent)
177 pattern = glob.name
178
179 return [SanityTest.create(item) for item in path.glob(pattern)]
180
181
182 if __name__ == '__main__':
183 main()