Debian Codegraph @

Tools/build/compute-changes.py

raw
1 """Determine which GitHub Actions workflows to run.
2
3 Called by ``.github/workflows/reusable-context.yml``.
4 We only want to run tests on PRs when related files are changed,
5 or when someone triggers a manual workflow run.
6 This improves developer experience by not doing (slow)
7 unnecessary work in GHA, and saves CI resources.
8 """
9
10 from __future__ import annotations
11
12 import os
13 import subprocess
14 from dataclasses import dataclass, fields
15 from pathlib import Path
16
17 TYPE_CHECKING = False
18 if TYPE_CHECKING:
19 from collections.abc import Set
20
21 GITHUB_DEFAULT_BRANCH = os.environ["GITHUB_DEFAULT_BRANCH"]
22 GITHUB_WORKFLOWS_PATH = Path(".github/workflows")
23
24 RUN_TESTS_IGNORE = frozenset({
25 Path("Tools/check-c-api-docs/ignored_c_api.txt"),
26 Path(".github/CODEOWNERS"),
27 Path(".pre-commit-config.yaml"),
28 Path(".ruff.toml"),
29 Path("mypy.ini"),
30 })
31
32 UNIX_BUILD_SYSTEM_FILE_NAMES = frozenset({
33 Path("aclocal.m4"),
34 Path("config.guess"),
35 Path("config.sub"),
36 Path("configure"),
37 Path("configure.ac"),
38 Path("install-sh"),
39 Path("Makefile.pre.in"),
40 Path("Modules/makesetup"),
41 Path("Modules/Setup"),
42 Path("Modules/Setup.bootstrap.in"),
43 Path("Modules/Setup.stdlib.in"),
44 Path("Tools/build/regen-configure.sh"),
45 })
46
47 SUFFIXES_C_OR_CPP = frozenset({".c", ".h", ".cpp"})
48 SUFFIXES_DOCUMENTATION = frozenset({".rst", ".md"})
49
50 ANDROID_DIRS = frozenset({"Android"})
51 MACOS_DIRS = frozenset({"Mac"})
52 WASI_DIRS = frozenset({Path("Tools", "wasm")})
53
54 LIBRARY_FUZZER_PATHS = frozenset({
55 # All C/CPP fuzzers.
56 Path("configure"),
57 Path(".github/workflows/reusable-cifuzz.yml"),
58 # ast
59 Path("Lib/ast.py"),
60 Path("Python/ast.c"),
61 # configparser
62 Path("Lib/configparser.py"),
63 # csv
64 Path("Lib/csv.py"),
65 Path("Modules/_csv.c"),
66 # decode
67 Path("Lib/encodings/"),
68 Path("Modules/_codecsmodule.c"),
69 Path("Modules/cjkcodecs/"),
70 Path("Modules/unicodedata*"),
71 # difflib
72 Path("Lib/difflib.py"),
73 # email
74 Path("Lib/email/"),
75 # html
76 Path("Lib/html/"),
77 Path("Lib/_markupbase.py"),
78 # http.client
79 Path("Lib/http/client.py"),
80 # json
81 Path("Lib/json/"),
82 Path("Modules/_json.c"),
83 # plist
84 Path("Lib/plistlib.py"),
85 # re
86 Path("Lib/re/"),
87 Path("Modules/_sre/"),
88 # tarfile
89 Path("Lib/tarfile.py"),
90 # tomllib
91 Path("Modules/tomllib/"),
92 # xml
93 Path("Lib/xml/"),
94 Path("Lib/_markupbase.py"),
95 Path("Modules/expat/"),
96 Path("Modules/pyexpat.c"),
97 # zipfile
98 Path("Lib/zipfile/"),
99 })
100
101
102 @dataclass(kw_only=True, slots=True)
103 class Outputs:
104 run_android: bool = False
105 run_ci_fuzz: bool = False
106 run_ci_fuzz_stdlib: bool = False
107 run_docs: bool = False
108 run_macos: bool = False
109 run_tests: bool = False
110 run_ubuntu: bool = False
111 run_wasi: bool = False
112 run_windows_msi: bool = False
113 run_windows_tests: bool = False
114
115
116 def compute_changes() -> None:
117 target_branch, head_ref = git_refs()
118 if os.environ.get("GITHUB_EVENT_NAME", "") == "pull_request":
119 # Getting changed files only makes sense on a pull request
120 files = get_changed_files(target_branch, head_ref)
121 outputs = process_changed_files(files)
122 else:
123 # Otherwise, just run the tests
124 outputs = Outputs(
125 run_android=True,
126 run_macos=True,
127 run_tests=True,
128 run_ubuntu=True,
129 run_wasi=True,
130 run_windows_tests=True,
131 )
132 outputs = process_target_branch(outputs, target_branch)
133
134 if outputs.run_tests:
135 print("Run tests")
136 if outputs.run_windows_tests:
137 print("Run Windows tests")
138
139 if outputs.run_ci_fuzz:
140 print("Run CIFuzz tests")
141 else:
142 print("Branch too old for CIFuzz tests; or no C files were changed")
143
144 if outputs.run_ci_fuzz_stdlib:
145 print("Run CIFuzz tests for stdlib")
146 else:
147 print("Branch too old for CIFuzz tests; or no stdlib files were changed")
148
149 if outputs.run_docs:
150 print("Build documentation")
151
152 if outputs.run_windows_msi:
153 print("Build Windows MSI")
154
155 print(outputs)
156
157 write_github_output(outputs)
158
159
160 def git_refs() -> tuple[str, str]:
161 target_ref = os.environ.get("CCF_TARGET_REF", "")
162 target_ref = target_ref.removeprefix("refs/heads/")
163 print(f"target ref: {target_ref!r}")
164
165 head_ref = os.environ.get("CCF_HEAD_REF", "")
166 head_ref = head_ref.removeprefix("refs/heads/")
167 print(f"head ref: {head_ref!r}")
168 return f"origin/{target_ref}", head_ref
169
170
171 def get_changed_files(
172 ref_a: str = GITHUB_DEFAULT_BRANCH, ref_b: str = "HEAD"
173 ) -> Set[Path]:
174 """List the files changed between two Git refs, filtered by change type."""
175 args = ("git", "diff", "--name-only", f"{ref_a}...{ref_b}", "--")
176 print(*args)
177 changed_files_result = subprocess.run(
178 args, stdout=subprocess.PIPE, check=True, encoding="utf-8"
179 )
180 changed_files = changed_files_result.stdout.strip().splitlines()
181 return frozenset(map(Path, filter(None, map(str.strip, changed_files))))
182
183
184 def get_file_platform(file: Path) -> str | None:
185 if not file.parts:
186 return None
187 first_part = file.parts[0]
188 if first_part in MACOS_DIRS:
189 return "macos"
190 if first_part in ANDROID_DIRS:
191 return "android"
192 if len(file.parts) >= 2 and Path(*file.parts[:2]) in WASI_DIRS: # Tools/wasm/
193 return "wasi"
194 return None
195
196
197 def is_fuzzable_library_file(file: Path) -> bool:
198 return any(
199 (file.is_relative_to(needs_fuzz) and needs_fuzz.is_dir())
200 or (file == needs_fuzz and file.is_file())
201 for needs_fuzz in LIBRARY_FUZZER_PATHS
202 )
203
204
205 def process_changed_files(changed_files: Set[Path]) -> Outputs:
206 run_tests = False
207 run_ci_fuzz = False
208 run_ci_fuzz_stdlib = False
209 run_docs = False
210 run_windows_tests = False
211 run_windows_msi = False
212
213 platforms_changed = set()
214 has_platform_specific_change = True
215
216 for file in changed_files:
217 # Documentation files
218 doc_or_misc = file.parts[0] in {"Doc", "Misc"}
219 doc_file = file.suffix in SUFFIXES_DOCUMENTATION or doc_or_misc
220
221 if file.parent == GITHUB_WORKFLOWS_PATH:
222 if file.name in ("build.yml", "reusable-cifuzz.yml"):
223 run_tests = run_ci_fuzz = run_ci_fuzz_stdlib = True
224 has_platform_specific_change = False
225 if file.name == "reusable-docs.yml":
226 run_docs = True
227 if file.name == "reusable-windows-msi.yml":
228 run_windows_msi = True
229 if file.name == "reusable-macos.yml":
230 platforms_changed.add("macos")
231 if file.name == "reusable-wasi.yml":
232 platforms_changed.add("wasi")
233
234 if not doc_file and file not in RUN_TESTS_IGNORE:
235 run_tests = True
236
237 platform = get_file_platform(file)
238 if platform is not None:
239 platforms_changed.add(platform)
240 else:
241 has_platform_specific_change = False
242 if file not in UNIX_BUILD_SYSTEM_FILE_NAMES:
243 run_windows_tests = True
244
245 # The fuzz tests are pretty slow so they are executed only for PRs
246 # changing relevant files.
247 if file.suffix in SUFFIXES_C_OR_CPP:
248 run_ci_fuzz = True
249 if file.parts[:2] in {
250 ("configure",),
251 ("Modules", "_xxtestfuzz"),
252 }:
253 run_ci_fuzz = True
254 if not run_ci_fuzz_stdlib and is_fuzzable_library_file(file):
255 run_ci_fuzz_stdlib = True
256
257 # Check for changed documentation-related files
258 if doc_file:
259 run_docs = True
260
261 # Check for changed MSI installer-related files
262 if file.parts[:2] == ("Tools", "msi"):
263 run_windows_msi = True
264
265 # Check which platform specific tests to run
266 if run_tests:
267 if not has_platform_specific_change or not platforms_changed:
268 run_android = True
269 run_macos = True
270 run_ubuntu = True
271 run_wasi = True
272 else:
273 run_android = "android" in platforms_changed
274 run_macos = "macos" in platforms_changed
275 run_ubuntu = False
276 run_wasi = "wasi" in platforms_changed
277 else:
278 run_android = False
279 run_macos = False
280 run_ubuntu = False
281 run_wasi = False
282
283 return Outputs(
284 run_android=run_android,
285 run_ci_fuzz=run_ci_fuzz,
286 run_ci_fuzz_stdlib=run_ci_fuzz_stdlib,
287 run_docs=run_docs,
288 run_macos=run_macos,
289 run_tests=run_tests,
290 run_ubuntu=run_ubuntu,
291 run_wasi=run_wasi,
292 run_windows_msi=run_windows_msi,
293 run_windows_tests=run_windows_tests,
294 )
295
296
297 def process_target_branch(outputs: Outputs, git_branch: str) -> Outputs:
298 if not git_branch:
299 outputs.run_tests = True
300
301 # CIFuzz / OSS-Fuzz compatibility with older branches may be broken.
302 if git_branch != GITHUB_DEFAULT_BRANCH:
303 outputs.run_ci_fuzz = False
304
305 if os.environ.get("GITHUB_EVENT_NAME", "").lower() == "workflow_dispatch":
306 outputs.run_docs = True
307 outputs.run_windows_msi = True
308
309 return outputs
310
311
312 def write_github_output(outputs: Outputs) -> None:
313 # https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables#default-environment-variables
314 # https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions#setting-an-output-parameter
315 if "GITHUB_OUTPUT" not in os.environ:
316 print("GITHUB_OUTPUT not defined!")
317 return
318
319 with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as f:
320 for field in fields(outputs):
321 name = field.name.replace("_", "-")
322 val = bool_lower(getattr(outputs, field.name))
323 f.write(f"{name}={val}\n")
324
325
326 def bool_lower(value: bool, /) -> str:
327 return "true" if value else "false"
328
329
330 if __name__ == "__main__":
331 compute_changes()