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
|
"""Split Tox to GitHub Actions
This is a small script to split a tox.ini config file into multiple GitHub actions configuration files.
This way each group of frameworks defined in tox.ini will get its own GitHub actions configuration file
which allows them to be run in parallel in GitHub actions.
This will generate/update several configuration files, that need to be commited to Git afterwards.
Whenever tox.ini is changed, this script needs to be run.
Usage:
python split-tox-gh-actions.py [--fail-on-changes]
If the parameter `--fail-on-changes` is set, the script will raise a RuntimeError in case the yaml
files have been changed by the scripts execution. This is used in CI to check if the yaml files
represent the current tox.ini file. (And if not the CI run fails.)
"""
import configparser
import hashlib
import sys
from collections import defaultdict
from functools import reduce
from glob import glob
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
OUT_DIR = Path(__file__).resolve().parent.parent.parent / ".github" / "workflows"
TOX_FILE = Path(__file__).resolve().parent.parent.parent / "tox.ini"
TEMPLATE_DIR = Path(__file__).resolve().parent / "templates"
FRAMEWORKS_NEEDING_POSTGRES = {
"django",
"asyncpg",
}
FRAMEWORKS_NEEDING_REDIS = {
"celery",
}
FRAMEWORKS_NEEDING_CLICKHOUSE = {
"clickhouse_driver",
}
FRAMEWORKS_NEEDING_AWS = {
"aws_lambda",
}
FRAMEWORKS_NEEDING_GITHUB_SECRETS = {
"aws_lambda",
}
# Frameworks grouped here will be tested together to not hog all GitHub runners.
# If you add or remove a group, make sure to git rm the generated YAML file as
# well.
GROUPS = {
"Common": [
"common",
],
"AI": [
"anthropic",
"cohere",
"langchain",
"openai",
"huggingface_hub",
],
"AWS": [
# this is separate from Cloud Computing because only this one test suite
# needs to run with access to GitHub secrets
"aws_lambda",
],
"Cloud": [
"boto3",
"chalice",
"cloud_resource_context",
"gcp",
],
"Tasks": [
"arq",
"beam",
"celery",
"dramatiq",
"huey",
"ray",
"rq",
"spark",
],
"DBs": [
"asyncpg",
"clickhouse_driver",
"pymongo",
"redis",
"redis_py_cluster_legacy",
"sqlalchemy",
],
"GraphQL": [
"ariadne",
"gql",
"graphene",
"strawberry",
],
"Network": [
"gevent",
"grpc",
"httpx",
"requests",
],
"Web 1": [
"django",
"flask",
"starlette",
"fastapi",
],
"Web 2": [
"aiohttp",
"asgi",
"bottle",
"falcon",
"litestar",
"pyramid",
"quart",
"sanic",
"starlite",
"tornado",
],
"Misc": [
"launchdarkly",
"loguru",
"openfeature",
"opentelemetry",
"potel",
"pure_eval",
"trytond",
],
}
ENV = Environment(
loader=FileSystemLoader(TEMPLATE_DIR),
)
def main(fail_on_changes):
"""Create one CI workflow for each framework defined in tox.ini."""
if fail_on_changes:
old_hash = get_files_hash()
print("Parsing tox.ini...")
py_versions_pinned, py_versions_latest = parse_tox()
if fail_on_changes:
print("Checking if all frameworks belong in a group...")
missing_frameworks = find_frameworks_missing_from_groups(
py_versions_pinned, py_versions_latest
)
if missing_frameworks:
raise RuntimeError(
"Please add the following frameworks to the corresponding group "
"in `GROUPS` in `scripts/split-tox-gh-actions/split-tox-gh-actions.py: "
+ ", ".join(missing_frameworks)
)
print("Rendering templates...")
for group, frameworks in GROUPS.items():
contents = render_template(
group, frameworks, py_versions_pinned, py_versions_latest
)
filename = write_file(contents, group)
print(f"Created {filename}")
if fail_on_changes:
new_hash = get_files_hash()
if old_hash != new_hash:
raise RuntimeError(
"The yaml configuration files have changed. This means that either `tox.ini` "
"or one of the constants in `split-tox-gh-actions.py` has changed "
"but the changes have not been propagated to the GitHub actions config files. "
"Please run `python scripts/split-tox-gh-actions/split-tox-gh-actions.py` "
"locally and commit the changes of the yaml configuration files to continue. "
)
print("All done. Have a nice day!")
def parse_tox():
config = configparser.ConfigParser()
config.read(TOX_FILE)
lines = [
line
for line in config["tox"]["envlist"].split("\n")
if line.strip() and not line.strip().startswith("#")
]
py_versions_pinned = defaultdict(set)
py_versions_latest = defaultdict(set)
for line in lines:
# normalize lines
line = line.strip().lower()
try:
# parse tox environment definition
try:
(raw_python_versions, framework, framework_versions) = line.split("-")
except ValueError:
(raw_python_versions, framework) = line.split("-")
framework_versions = []
# collect python versions to test the framework in
raw_python_versions = set(
raw_python_versions.replace("{", "").replace("}", "").split(",")
)
if "latest" in framework_versions:
py_versions_latest[framework] |= raw_python_versions
else:
py_versions_pinned[framework] |= raw_python_versions
except ValueError:
print(f"ERROR reading line {line}")
py_versions_pinned = _normalize_py_versions(py_versions_pinned)
py_versions_latest = _normalize_py_versions(py_versions_latest)
return py_versions_pinned, py_versions_latest
def find_frameworks_missing_from_groups(py_versions_pinned, py_versions_latest):
frameworks_in_a_group = _union(GROUPS.values())
all_frameworks = set(py_versions_pinned.keys()) | set(py_versions_latest.keys())
return all_frameworks - frameworks_in_a_group
def _normalize_py_versions(py_versions):
def replace_and_sort(versions):
return sorted(
[py.replace("py", "") for py in versions],
key=lambda v: tuple(map(int, v.split("."))),
)
if isinstance(py_versions, dict):
normalized = defaultdict(set)
normalized |= {
framework: replace_and_sort(versions)
for framework, versions in py_versions.items()
}
elif isinstance(py_versions, set):
normalized = replace_and_sort(py_versions)
return normalized
def get_files_hash():
"""Calculate a hash of all the yaml configuration files"""
hasher = hashlib.md5()
path_pattern = (OUT_DIR / "test-integrations-*.yml").as_posix()
for file in glob(path_pattern):
with open(file, "rb") as f:
buf = f.read()
hasher.update(buf)
return hasher.hexdigest()
def _union(seq):
return reduce(lambda x, y: set(x) | set(y), seq)
def render_template(group, frameworks, py_versions_pinned, py_versions_latest):
template = ENV.get_template("base.jinja")
categories = set()
py_versions = defaultdict(set)
for framework in frameworks:
if py_versions_pinned[framework]:
categories.add("pinned")
py_versions["pinned"] |= set(py_versions_pinned[framework])
if py_versions_latest[framework]:
categories.add("latest")
py_versions["latest"] |= set(py_versions_latest[framework])
context = {
"group": group,
"frameworks": frameworks,
"categories": sorted(categories),
"needs_aws_credentials": bool(set(frameworks) & FRAMEWORKS_NEEDING_AWS),
"needs_clickhouse": bool(set(frameworks) & FRAMEWORKS_NEEDING_CLICKHOUSE),
"needs_postgres": bool(set(frameworks) & FRAMEWORKS_NEEDING_POSTGRES),
"needs_redis": bool(set(frameworks) & FRAMEWORKS_NEEDING_REDIS),
"needs_github_secrets": bool(
set(frameworks) & FRAMEWORKS_NEEDING_GITHUB_SECRETS
),
"py_versions": {
category: [f'"{version}"' for version in _normalize_py_versions(versions)]
for category, versions in py_versions.items()
},
}
rendered = template.render(context)
rendered = postprocess_template(rendered)
return rendered
def postprocess_template(rendered):
return "\n".join([line for line in rendered.split("\n") if line.strip()]) + "\n"
def write_file(contents, group):
group = group.lower().replace(" ", "-")
outfile = OUT_DIR / f"test-integrations-{group}.yml"
with open(outfile, "w") as file:
file.write(contents)
return outfile
if __name__ == "__main__":
fail_on_changes = len(sys.argv) == 2 and sys.argv[1] == "--fail-on-changes"
main(fail_on_changes)
|