Repository navigation
Expand file tree
/
Copy pathmatrix.py
More file actions
781 lines (711 loc) · 26.5 KB
/
Copy pathmatrix.py
File metadata and controls
781 lines (711 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
# Data Parallel Control (dpctl)
#
# Copyright 2026 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The platforms and Python versions this repository builds.
Both are read from the repository's own build files.
Every build system already has a standard place for both, so each is written
once, where the build reads it, and the GitHub Actions matrix follows it:
rattler-build, selected by recipe.yaml
Python versions python: in variants.yaml next to the recipe
platforms build: skip: in the recipe
conda-build, selected by meta.yaml
Python versions python: in conda_build_config.yaml next to the recipe
platforms skip: true # [selector] lines in the recipe
wheel, selected by pyproject.toml
Python versions the Programming Language :: Python :: 3.N classifiers;
any Free Threading classifier adds 3.Nt for each from 3.14
platforms the Operating System :: classifiers
A recipe builds on every platform in PLATFORMS, Linux, Windows and macOS on
Intel, unless a skip that depends on the platform alone rules one out, such as
`skip: [win]` or `skip: true # [osx]`; a skip that also depends on something
else, such as `win and py < 311` or `osx and arm64`, skips some builds, not the
platform. A pyproject.toml without Operating System classifiers, or with OS
Independent, builds on all three. Of the declared platforms, the matrix holds
those GitHub Actions has runners for, BUILT_PLATFORMS.
meson-python, scikit-build-core and every other PEP 517 backend declare these in
pyproject.toml too, so the wheel row covers them. Another convention, such as
pixi.toml, is one more reader in READERS and PLATFORM_READERS and, if it is a
new build system, one more entry in SYSTEMS.
Usage:
python ci/matrix.py [--system SYSTEM] [--event EVENT] [--github-output NAME]
[--newest] [--platform PLATFORM]
Prints the build matrix as JSON for strategy.matrix: {"include": [{"platform":
"linux", "name": "Linux", "python": "3.14"}, ...]}, every platform with every
Python version. For a pull_request event only the oldest and the newest regular
versions and the newest free-threaded one are listed. --github-output also
writes NAME=<matrix> to $GITHUB_OUTPUT, for later jobs. Standard library only;
reading pyproject.toml needs Python 3.11 or newer for tomllib.
"""
import argparse
import ast
import fnmatch
import json
import os
import re
import sys
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
# Only the wheel reader needs it, and only it needs Python 3.11 or newer.
try:
import tomllib as TOMLLIB
except ModuleNotFoundError:
TOMLLIB = None
ROOT = Path(__file__).resolve().parent.parent
# Build system -> files that select it, in the order they are looked for. Where
# a repository still has conda-recipe-cf/ next to conda-recipe/, the conda-forge
# one comes first: the tests use conda-forge alone.
SYSTEMS = {
"rattler-build": ("recipe.yaml", "recipe/recipe.yaml"),
"conda-build": (
"conda-recipe-cf/meta.yaml",
"meta.yaml",
"conda-recipe/meta.yaml",
"recipe/meta.yaml",
),
"wheel": ("pyproject.toml",),
}
# The platforms CI builds and tests, and how artifact names spell them.
PLATFORMS = {"linux": "Linux", "windows": "Windows", "macos": "macOS"}
# cibuildwheel's platform part of a build identifier, which [tool.cibuildwheel]
# skip patterns match
WHEEL_PLATFORMS = {
"linux": "manylinux_x86_64",
"windows": "win_amd64",
"macos": "macosx_x86_64",
}
# The platforms the workflow can build on: GitHub-hosted runners have all
# three. A declared platform missing here is reported and left out.
BUILT_PLATFORMS = ("linux", "windows", "macos")
# What a platform-only selector means on each platform, for both conda-build and
# rattler-build.
SELECTORS = {
"linux": {
"linux": True,
"linux64": True,
"unix": True,
"win": False,
"win64": False,
"win32": False,
"osx": False,
"osx64": False,
"x86_64": True,
"x86": False,
"aarch64": False,
"arm64": False,
"ppc64le": False,
"s390x": False,
},
"windows": {
"linux": False,
"linux64": False,
"unix": False,
"win": True,
"win64": True,
"win32": False,
"osx": False,
"osx64": False,
"x86_64": True,
"x86": False,
"aarch64": False,
"arm64": False,
"ppc64le": False,
"s390x": False,
},
# Intel Macs only, as MKL has no Apple silicon build.
"macos": {
"linux": False,
"linux64": False,
"unix": True,
"win": False,
"win64": False,
"win32": False,
"osx": True,
"osx64": True,
"x86_64": True,
"x86": False,
"aarch64": False,
"arm64": False,
"ppc64le": False,
"s390x": False,
},
}
# conda-build reads x86 as any x86 CPU and has no osx64; None refuses a skip
# that uses it.
CONDA_BUILD_SELECTORS = {"x86": True, "osx64": None}
CONDA_SKIP_RE = re.compile(r"\s*skip\s*:")
# conda-build's own selector pattern, which lets a comment follow the selector
CONDA_SELECTOR_RE = re.compile(r"(.+?)\s*(#.*)?\[([^\[\]]+)\](?(2)[^\(\)]*)$")
OS_CLASSIFIERS = {
"Operating System :: OS Independent": tuple(PLATFORMS),
"Operating System :: POSIX": ("linux",),
"Operating System :: Unix": ("linux",),
"Operating System :: POSIX :: Linux": ("linux",),
"Operating System :: Microsoft :: Windows": ("windows",),
"Operating System :: MacOS": ("macos",),
}
PULL_REQUEST_EVENTS = ("pull_request",)
OLDEST_MINOR = 10
FREE_THREADED_MINOR = 13
# A Free Threading classifier adds 3.Nt from 3.14, the first supported one,
# which is also the oldest cibuildwheel builds.
CLASSIFIED_FREE_THREADED_MINOR = 14
# A conda python variant: 3.12, 3.12.*, 3.12.* *_cpython, 3.13.* *_cp313 or
# 3.14.* *_cp314t.
CONDA_SPEC_RE = re.compile(
r"3\.(\d+)(?:\.\*)?(?:\s+\*_(?:cpython|cp3(\d+)(t?)))?"
)
CLASSIFIER_RE = re.compile(r"Programming Language :: Python :: 3\.(\d+)")
FREE_THREADING_CLASSIFIER = "Programming Language :: Python :: Free Threading"
LOWER_BOUND_RE = re.compile(r">=\s*3\.(\d+)")
class DeclarationError(Exception):
"""
Raised when the build files declare no Python versions, or ones this cannot
read.
"""
@dataclass(frozen=True)
class Python:
"""One declared Python version."""
version: str # as artifact names spell it: 3.14 or 3.14t
spec: str # as the build system spells it, passed back to it unchanged
def version_key(version: str) -> tuple[int, bool]:
"""(minor, free-threaded); also the sort order."""
return int(version.rstrip("t").split(".")[1]), version.endswith("t")
def checked(minor: int, threaded: bool, where: str) -> str:
"""The version string, once it is one CI can test."""
if minor < OLDEST_MINOR or (threaded and minor < FREE_THREADED_MINOR):
raise DeclarationError(
f'{where}: 3.{minor}{"t" if threaded else ""} is not supported; '
f"the oldest is 3.{OLDEST_MINOR}, free-threaded from "
f"3.{FREE_THREADED_MINOR}"
)
return f'3.{minor}{"t" if threaded else ""}'
def _strip_comment(line: str, where: str) -> str:
"""
The line without a trailing comment; conda-build selectors are refused, not
guessed at.
"""
in_quote = ""
for index, char in enumerate(line):
if char in "\"'" and in_quote in ("", char):
in_quote = "" if in_quote else char
elif (
char == "#"
and not in_quote
and (index == 0 or line[index - 1].isspace())
):
if line[index:].lstrip("# ").startswith("["):
raise DeclarationError(
f"{where}: selectors in the python list are not supported"
)
return line[:index].rstrip()
return line.rstrip()
def _unquote(value: str, where: str) -> str:
"""A plain or quoted YAML scalar."""
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
return value[1:-1]
if not value or value[0] in "{[&*!|>" or ":" in value:
raise DeclarationError(
f"{where}: write each python entry as a plain value, not {value!r}"
)
return value
def yaml_python_list(text: str, where: str) -> list[str]:
"""
The top-level python: list of a variants file, without a YAML library.
Accepts a block list or a one-line [a, b] list of plain or quoted values.
Anything richer, such as if/then selectors or templating, is refused so the
matrix is never guessed.
"""
lines = text.splitlines()
for number, line in enumerate(lines):
if not re.match(r"python\s*:", line):
continue
rest = _strip_comment(line.split(":", 1)[1], where).strip()
if rest.startswith("[") and rest.endswith("]"):
return [
_unquote(item, where)
for item in rest[1:-1].split(",")
if item.strip()
]
if rest:
raise DeclarationError(f"{where}: python must be a list")
values = []
for item in lines[number + 1 :]:
# Checked before the comment, as the next key may have a selector
if item[:1] not in ("", " ", "\t", "-", "#"):
break # the next top-level key
entry = _strip_comment(item, where).lstrip()
if not entry:
continue
if not entry.startswith("- "):
raise DeclarationError(
f"{where}: python must be a plain list of versions"
)
values.append(_unquote(entry[2:], where))
return values
raise DeclarationError(f"{where} has no top-level python: list")
def from_conda_variants(path: Path) -> list[Python]:
"""The python: list of a variants.yaml or a conda_build_config.yaml."""
where = (
path.relative_to(ROOT).as_posix()
if path.is_relative_to(ROOT)
else str(path)
)
try:
text = path.read_text(encoding="utf-8")
except FileNotFoundError as ex:
raise DeclarationError(
f"{where} is missing; list the Python versions to build there"
) from ex
pythons = []
for spec in yaml_python_list(text, where):
match = CONDA_SPEC_RE.fullmatch(spec)
if not match or (match[2] and match[2] != match[1]):
raise DeclarationError(
f"{where}: {spec!r} is not a CPython variant such as "
'"3.13.* *_cp313" or "3.14.* *_cp314t"'
)
pythons.append(
Python(checked(int(match[1]), bool(match[3]), where), spec)
)
return pythons
def from_pyproject(path: Path) -> list[Python]:
"""
The 3.N classifiers in pyproject.toml, plus 3.Nt from 3.14 if free-threading
is declared.
"""
if TOMLLIB is None:
raise DeclarationError(
"reading pyproject.toml needs Python 3.11 or newer"
)
project = TOMLLIB.loads(path.read_text(encoding="utf-8")).get("project", {})
classifiers = project.get("classifiers", [])
minors = sorted(
{
int(match[1])
for classifier in classifiers
if (match := CLASSIFIER_RE.fullmatch(classifier))
}
)
if not minors:
raise DeclarationError(
"pyproject.toml lists no Programming Language :: Python :: 3.N "
"classifiers"
)
bound = LOWER_BOUND_RE.search(project.get("requires-python", ""))
if bound and minors[0] < int(bound[1]):
raise DeclarationError(
f"pyproject.toml classifies 3.{minors[0]}, below requires-python "
f'{project["requires-python"]}'
)
threaded = any(
classifier.startswith(FREE_THREADING_CLASSIFIER)
for classifier in classifiers
)
versions = [checked(minor, False, "pyproject.toml") for minor in minors]
versions += [
f"3.{minor}t"
for minor in minors
if threaded and minor >= CLASSIFIED_FREE_THREADED_MINOR
]
skips = (
TOMLLIB.loads(path.read_text(encoding="utf-8"))
.get("tool", {})
.get("cibuildwheel", {})
.get("skip", [])
)
skips = skips.split() if isinstance(skips, str) else skips
return [
Python(version, version)
for version in versions
if not wheel_skipped(version, skips)
]
def wheel_skipped(version: str, skips: list[str]) -> bool:
"""
Whether [tool.cibuildwheel] skip leaves out a version on every platform;
a skip that leaves it out on some platforms only is refused.
"""
minor, threaded = version_key(version)
identifiers = [
f'cp3{minor}{"t" if threaded else ""}-{tag}'
for tag in WHEEL_PLATFORMS.values()
]
matched = [
any(fnmatch.fnmatchcase(identifier, skip) for skip in skips)
for identifier in identifiers
]
if any(matched) and not all(matched):
raise DeclarationError(
f"pyproject.toml: [tool.cibuildwheel] skip leaves out Python "
f"{version} on some platforms only, which the matrix cannot list"
)
return all(matched)
def skips_platform(expression: str, platform: str, system: str) -> bool | None:
"""
Whether a skip expression rules out a whole platform, as the build system
reads it: True or False when it depends on the platform alone, None when it
also depends on anything else, such as the Python version.
"""
names = SELECTORS[platform] | (
CONDA_BUILD_SELECTORS if system == "conda-build" else {}
)
try:
tree = ast.parse(
expression.strip().removeprefix("${{").removesuffix("}}").strip(),
mode="eval",
).body
except SyntaxError:
return None
def value(node: ast.AST) -> bool:
if isinstance(node, ast.BoolOp):
values = [value(item) for item in node.values]
return all(values) if isinstance(node.op, ast.And) else any(values)
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
return not value(node.operand)
if isinstance(node, ast.Name) and names.get(node.id) is not None:
return names[node.id]
if isinstance(node, ast.Constant) and isinstance(node.value, bool):
return node.value
raise ValueError(ast.dump(node))
try:
return value(tree)
except ValueError:
return None
def platforms_without(skips: list[str], where: str, system: str) -> list[str]:
"""
Every platform in PLATFORMS, but those a skip rules out; a skip that
depends on more than the platform, or on a name the build system doesn't
define, is refused.
"""
for skip in skips:
if any(
skips_platform(skip, platform, system) is None
for platform in PLATFORMS
):
raise DeclarationError(
f"{where}: cannot tell which platforms the skip {skip!r} rules "
"out, so the matrix would still list the builds it skips"
)
kept = [
platform
for platform in PLATFORMS
if not any(skips_platform(skip, platform, system) for skip in skips)
]
if not kept:
raise DeclarationError(
f"{where} skips every platform CI builds: "
+ ", ".join(PLATFORMS.values())
)
return kept
def yaml_build_skips(text: str, where: str) -> list[str]:
"""
The skip: entries directly under a rattler-build recipe's top-level build:,
as a list of plain or quoted values, a one-line [a, b] list, or one value;
none when there is no skip.
"""
lines = text.splitlines()
starts = [
number
for number, line in enumerate(lines)
if re.match(r"build\s*:\s*(#.*)?$", line)
]
if not starts:
return []
child = ""
for number in range(starts[0] + 1, len(lines)):
line = (
_strip_comment(lines[number], where)
if "#" in lines[number]
else lines[number]
)
if not line.strip():
continue
if not line[0].isspace():
return [] # the next top-level key
indent = line[: len(line) - len(line.lstrip())]
child = child or indent
match = (
re.match(r"skip\s*:(.*)", line.lstrip())
if indent == child
else None
)
if not match:
continue
rest = match[1].strip()
if rest.startswith("[") and rest.endswith("]"):
return [
_unquote(item, where)
for item in rest[1:-1].split(",")
if item.strip()
]
if rest:
return [_unquote(rest, where)]
values = []
for item in lines[number + 1 :]:
entry = item.strip()
if not entry or entry.startswith("#"):
continue
if not entry.startswith("- "):
break
values.append(_unquote(entry[2:].split(" #")[0], where))
return values
return []
def from_rattler_recipe(recipe: Path) -> list[str]:
"""The platforms a rattler-build recipe builds on, from its build: skip:."""
where = (
recipe.relative_to(ROOT).as_posix()
if recipe.is_relative_to(ROOT)
else str(recipe)
)
return platforms_without(
yaml_build_skips(recipe.read_text(encoding="utf-8"), where),
where,
"rattler-build",
)
def from_conda_recipe(recipe: Path) -> list[str]:
"""
The platforms a conda-build meta.yaml builds on, from its skip: true #
[selector] lines; a skip: line it cannot read is refused.
"""
where = (
recipe.relative_to(ROOT).as_posix()
if recipe.is_relative_to(ROOT)
else str(recipe)
)
skips = []
for line in recipe.read_text(encoding="utf-8").splitlines():
if not CONDA_SKIP_RE.match(line):
continue
selected = CONDA_SELECTOR_RE.match(line)
key, selector = (
(selected[1], selected[3])
if selected
else (line.split(" #")[0], "True")
)
value = key.split(":", 1)[1].strip()
if value in ("false", "False", "no"):
continue
if value not in ("true", "True", "yes"):
raise DeclarationError(
f"{where}: cannot read {line.strip()!r}; write "
"skip: true # [selector]"
)
skips.append(selector)
return platforms_without(skips, where, "conda-build")
def from_os_classifiers(path: Path) -> list[str]:
"""
The platforms pyproject.toml's Operating System classifiers name; all of
them when it names none.
"""
if TOMLLIB is None:
raise DeclarationError(
"reading pyproject.toml needs Python 3.11 or newer"
)
classifiers = (
TOMLLIB.loads(path.read_text(encoding="utf-8"))
.get("project", {})
.get("classifiers", [])
)
named = [
classifier
for classifier in classifiers
if classifier.startswith("Operating System ::")
]
if not named:
return list(PLATFORMS)
found = {
platform
for classifier in named
for prefix, platforms in OS_CLASSIFIERS.items()
if classifier == prefix or classifier.startswith(prefix + " ::")
for platform in platforms
}
if not found:
raise DeclarationError(
"pyproject.toml names no Operating System CI builds: "
+ ", ".join(PLATFORMS.values())
)
return [platform for platform in PLATFORMS if platform in found]
# Build system -> where it declares Python versions, given the file that
# selected it.
READERS: dict[str, Callable[[Path], list[Python]]] = {
"rattler-build": lambda recipe: from_conda_variants(
recipe.parent / "variants.yaml"
),
"conda-build": lambda recipe: from_conda_variants(
recipe.parent / "conda_build_config.yaml"
),
"wheel": from_pyproject,
}
# Build system -> where it declares the platforms it builds on, given the file
# that selected it.
PLATFORM_READERS: dict[str, Callable[[Path], list[str]]] = {
"rattler-build": from_rattler_recipe,
"conda-build": from_conda_recipe,
"wheel": from_os_classifiers,
}
def detect(root: Path, system: str = "") -> tuple[str, Path]:
"""The build system and the file that selects it."""
for name, candidates in SYSTEMS.items():
if system and name != system:
continue
for candidate in candidates:
if (root / candidate).is_file():
return name, root / candidate
wanted = system or " or ".join(SYSTEMS)
raise DeclarationError(
f"no {wanted} input found; looked for "
+ ", ".join(c for name, cs in SYSTEMS.items() for c in cs)
)
def declared(system: str, selector: Path) -> list[Python]:
"""The build system's Python versions, sorted, each listed once."""
pythons = READERS[system](selector)
versions = [python.version for python in pythons]
if not pythons:
raise DeclarationError(f"{system} declares no Python versions")
if len(set(versions)) != len(versions):
raise DeclarationError(
f"{system} declares a Python version twice: {versions}"
)
return sorted(pythons, key=lambda python: version_key(python.version))
def declared_platforms(system: str, selector: Path) -> list[str]:
"""The platforms the build system builds on, in PLATFORMS order."""
return PLATFORM_READERS[system](selector)
def for_event(pythons: list[Python], event: str) -> list[Python]:
"""
All of them, or for a pull request the oldest and newest regular ones and
the newest free-threaded one.
"""
if event not in PULL_REQUEST_EVENTS:
return pythons
regular = [python for python in pythons if not python.version.endswith("t")]
threaded = [python for python in pythons if python.version.endswith("t")]
regular = regular or pythons
return list(dict.fromkeys(regular[:1] + regular[-1:] + threaded[-1:]))
def newest(pythons: list[Python]) -> list[Python]:
"""The newest regular and the newest free-threaded version."""
regular = [python for python in pythons if not python.version.endswith("t")]
threaded = [python for python in pythons if python.version.endswith("t")]
return list(dict.fromkeys(regular[-1:] + threaded[-1:]))
def build_matrix(system: str, selector: Path, event: str) -> dict:
"""
Every declared platform Actions can build on, with every Python version the
event builds.
"""
pythons = for_event(declared(system, selector), event)
platforms = declared_platforms(system, selector)
waiting = [
PLATFORMS[platform]
for platform in platforms
if platform not in BUILT_PLATFORMS
]
if waiting:
print(
f'matrix: {", ".join(waiting)} declared but not built: '
"no runners for it yet",
file=sys.stderr,
)
built = [platform for platform in platforms if platform in BUILT_PLATFORMS]
if not built:
raise DeclarationError(
"the build files declare only platforms there are no runners "
"for yet: " + ", ".join(waiting)
)
return {
"include": [
{
"platform": platform,
"name": PLATFORMS[platform],
"python": python.version,
}
for platform in built
for python in pythons
]
}
def main(argv: list[str] | None = None) -> int:
"""Prints the matrix to build; writes it for GitHub Actions if asked."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[1])
parser.add_argument(
"--system",
default="",
choices=("", *SYSTEMS),
help="build system to read instead of the detected one",
)
parser.add_argument(
"--event", default="", help="GitHub event name, such as pull_request"
)
parser.add_argument(
"--github-output",
default="",
metavar="NAME",
help="also write NAME=<matrix> to $GITHUB_OUTPUT",
)
parser.add_argument(
"--newest",
action="store_true",
help="only the newest regular and free-threaded versions, which "
"every event builds",
)
parser.add_argument(
"--platform",
default="",
choices=("", *PLATFORMS),
help="only this platform",
)
args = parser.parse_args(argv)
if args.github_output:
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]*", args.github_output):
raise DeclarationError(
f"{args.github_output!r} is not an output name"
)
if not os.environ.get("GITHUB_OUTPUT"):
raise DeclarationError(
"--github-output needs $GITHUB_OUTPUT, which Actions sets"
)
system, selector = detect(ROOT, args.system)
matrix = build_matrix(system, selector, args.event)
keep = [python.version for python in newest(declared(system, selector))]
matrix["include"] = [
cell
for cell in matrix["include"]
if (not args.newest or cell["python"] in keep)
and (not args.platform or cell["platform"] == args.platform)
]
if args.newest:
# The regular version first, for a job that needs just one
matrix["include"].sort(key=lambda cell: keep.index(cell["python"]))
if not matrix["include"]:
raise DeclarationError("--newest and --platform leave no build")
cells = ", ".join(
f'{cell["name"]} {cell["python"]}' for cell in matrix["include"]
)
print(
f"matrix: {system} from {selector.relative_to(ROOT)}: {cells}",
file=sys.stderr,
)
text = json.dumps(matrix)
print(text)
if args.github_output:
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
output.write(f"{args.github_output}={text}\n")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except DeclarationError as error:
print(f"matrix: {error}", file=sys.stderr)
sys.exit(1)