Buckets:

download
raw
10.8 kB
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""Deterministic GitHub Actions workflow generator for the AGT monorepo.
The source of truth is ``.github/ci/workflows.toml`` plus the pinned action
registry ``.github/ci/actions.toml``. This script renders the committed YAML
under ``.github/workflows`` so CI configuration has a single reviewed manifest
instead of many hand edited files.
Usage::
python3 scripts/ci/generate_workflows.py --write # regenerate YAML
python3 scripts/ci/generate_workflows.py --check # fail on drift
The renderer is intentionally deterministic and dependency free. It emits a
``DO NOT EDIT`` banner, enforces full SHA pinned actions resolved from the
registry, and restricts workflow level permissions to ``contents: read``. An
optional proposal agent may edit the manifest, but it never writes YAML and the
deterministic ``--check`` job is the gate, so generation stays reproducible and
reviewable.
"""
from __future__ import annotations
import argparse
import re
import sys
import tomllib
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
MANIFEST_PATH = REPO_ROOT / ".github" / "ci" / "workflows.toml"
ACTIONS_PATH = REPO_ROOT / ".github" / "ci" / "actions.toml"
OPA_VERSION = "0.70.0"
OPA_LINUX_AMD64_SHA256 = "00d114b94fdb1606a48cccdfc73c9ccdc62c38721150131ae578d5ff3df5c084"
SHA_RE = re.compile(r"^[^@]+@[0-9a-f]{40}$")
KNOWN_TOOLCHAINS = {"rust", "python", "node", "dotnet"}
# Default toolchain versions. Kept here, not in the manifest, so the manifest
# stays terse and version bumps are a single reviewed edit.
PYTHON_VERSION = "3.12"
NODE_VERSION = "20"
DOTNET_VERSION = "8.0.x"
BANNER = (
"# DO NOT EDIT. Generated by scripts/ci/generate_workflows.py.\n"
"# Source: .github/ci/workflows.toml and .github/ci/actions.toml.\n"
"# Regenerate: python3 scripts/ci/generate_workflows.py --write\n"
"# Check drift: python3 scripts/ci/generate_workflows.py --check\n"
)
class GenerationError(Exception):
"""Raised when the manifest or registry is invalid."""
def _load_toml(path: Path) -> dict:
try:
with path.open("rb") as handle:
return tomllib.load(handle)
except FileNotFoundError as exc:
raise GenerationError(f"missing required file: {path}") from exc
except tomllib.TOMLDecodeError as exc:
raise GenerationError(f"invalid TOML in {path}: {exc}") from exc
def _load_actions(path: Path) -> dict[str, str]:
"""Return a map of action key to a `uses` string with an inline comment."""
raw = _load_toml(path)
registry: dict[str, str] = {}
for key, entry in raw.items():
if not isinstance(entry, dict) or "uses" not in entry:
raise GenerationError(f"action '{key}' must define a uses value")
uses = entry["uses"]
if not SHA_RE.match(uses):
raise GenerationError(
f"action '{key}' is not pinned to a 40 character SHA: {uses}"
)
comment = entry.get("comment")
registry[key] = f"{uses} # {comment}" if comment else uses
return registry
def _indent(text: str, spaces: int) -> list[str]:
pad = " " * spaces
return [f"{pad}{line}" if line else "" for line in text.splitlines()]
def _render_uses_step(action_ref: str, name: str | None, with_lines: list[str]) -> list[str]:
lines: list[str] = []
if name:
lines.append(f" - name: {name}")
lines.append(f" uses: {action_ref}")
else:
lines.append(f" - uses: {action_ref}")
if with_lines:
lines.append(" with:")
lines.extend(f" {line}" for line in with_lines)
return lines
def _render_run_step(name: str, run_body: str) -> list[str]:
lines = [f" - name: {name}", " run: |"]
body = run_body.strip("\n")
for line in body.splitlines():
lines.append(f" {line}" if line else "")
return lines
def _toolchain_steps(toolchain: str, actions: dict[str, str]) -> list[str]:
if toolchain == "rust":
return _render_uses_step(
actions["rust-toolchain"],
"Install Rust toolchain",
["toolchain: stable", "components: rustfmt, clippy"],
)
if toolchain == "python":
return _render_uses_step(
actions["setup-python"],
"Set up Python",
[f"python-version: '{PYTHON_VERSION}'"],
)
if toolchain == "node":
return _render_uses_step(
actions["setup-node"],
"Set up Node.js",
[f"node-version: '{NODE_VERSION}'"],
)
if toolchain == "dotnet":
return _render_uses_step(
actions["setup-dotnet"],
"Set up .NET",
[f"dotnet-version: '{DOTNET_VERSION}'"],
)
raise GenerationError(f"unknown toolchain: {toolchain}")
def _opa_step(on_path: bool = False, set_env: bool = True) -> list[str]:
lines = [
f'curl --proto \'=https\' --tlsv1.2 -fSLo "$RUNNER_TEMP/opa" '
'--retry 5 --retry-all-errors --retry-delay 5 --connect-timeout 20 '
f'"https://openpolicyagent.org/downloads/v{OPA_VERSION}/opa_linux_amd64_static"\n',
f'echo "{OPA_LINUX_AMD64_SHA256} $RUNNER_TEMP/opa" | sha256sum -c -\n',
'chmod +x "$RUNNER_TEMP/opa"\n',
]
if set_env:
lines.append('echo "ACS_OPA_PATH=$RUNNER_TEMP/opa" >> "$GITHUB_ENV"\n')
if on_path:
# The Python generator locates opa via shutil.which("opa") (PATH only),
# unlike the Rust core which honors ACS_OPA_PATH. Jobs that run the
# generator opt in to also putting opa on PATH.
lines.append('echo "$RUNNER_TEMP" >> "$GITHUB_PATH"\n')
lines.append('"$RUNNER_TEMP/opa" version')
return _render_run_step("Install OPA", "".join(lines))
def _render_job(job: dict, actions: dict[str, str]) -> list[str]:
job_id = job.get("id")
if not job_id:
raise GenerationError("every job needs an id")
name = job.get("name", job_id)
toolchains = job.get("toolchains", [])
unknown = set(toolchains) - KNOWN_TOOLCHAINS
if unknown:
raise GenerationError(f"job '{job_id}' uses unknown toolchains: {sorted(unknown)}")
steps = job.get("step", [])
if not steps:
raise GenerationError(f"job '{job_id}' has no steps")
lines = [f" {job_id}:", f" name: {name}", " runs-on: ubuntu-latest", " timeout-minutes: 30"]
working_directory = job.get("working_directory")
if working_directory:
lines += [" defaults:", " run:", f" working-directory: {working_directory}"]
lines.append(" steps:")
lines += _render_uses_step(actions["checkout"], None, [])
for toolchain in toolchains:
lines += _toolchain_steps(toolchain, actions)
if job.get("opa"):
lines += _opa_step(job.get("opa_on_path", False), job.get("opa_env", True))
for step in steps:
step_name = step.get("name")
run_body = step.get("run")
if not step_name or run_body is None:
raise GenerationError(f"job '{job_id}' has a step missing name or run")
lines += _render_run_step(step_name, run_body)
return lines
def render_workflow(workflow: dict, actions: dict[str, str]) -> str:
name = workflow.get("name")
if not name:
raise GenerationError("every workflow needs a name")
output = workflow.get("output", "")
if not output.startswith(".github/workflows/") or not output.endswith(".yml"):
raise GenerationError(f"workflow '{name}' output must be a .github/workflows/*.yml path")
push_branches = workflow.get("push_branches", [])
pull_request_paths = workflow.get("pull_request_paths", [])
lines = [BANNER.rstrip("\n"), f"name: {name}", "", "on:"]
if push_branches:
lines.append(" push:")
lines.append(" branches:")
lines += [f" - {branch}" for branch in push_branches]
if pull_request_paths:
lines.append(" pull_request:")
lines.append(" paths:")
lines += [f" - '{path}'" for path in pull_request_paths]
lines += [
"",
"permissions:",
" contents: read",
"",
"concurrency:",
" group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}",
" cancel-in-progress: true",
"",
"jobs:",
]
jobs = workflow.get("job", [])
if not jobs:
raise GenerationError(f"workflow '{name}' has no jobs")
for index, job in enumerate(jobs):
if index:
lines.append("")
lines += _render_job(job, actions)
return "\n".join(lines) + "\n"
def build_outputs() -> dict[Path, str]:
actions = _load_actions(ACTIONS_PATH)
manifest = _load_toml(MANIFEST_PATH)
workflows = manifest.get("workflow", [])
if not workflows:
raise GenerationError("manifest defines no [[workflow]] entries")
outputs: dict[Path, str] = {}
seen_ids: set[str] = set()
for workflow in workflows:
wid = workflow.get("id", "")
if wid in seen_ids:
raise GenerationError(f"duplicate workflow id: {wid}")
seen_ids.add(wid)
outputs[REPO_ROOT / workflow["output"]] = render_workflow(workflow, actions)
return outputs
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--write", action="store_true", help="write generated workflow YAML")
group.add_argument("--check", action="store_true", help="fail if committed YAML drifts")
args = parser.parse_args(argv)
try:
outputs = build_outputs()
except GenerationError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
if args.write:
for path, content in outputs.items():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
print(f"wrote {path.relative_to(REPO_ROOT)}")
return 0
drifted: list[str] = []
for path, content in outputs.items():
rel = path.relative_to(REPO_ROOT)
if not path.exists():
drifted.append(f"{rel} (missing, run --write)")
elif path.read_text(encoding="utf-8") != content:
drifted.append(f"{rel} (out of date, run --write)")
if drifted:
print("error: generated workflows are out of date:", file=sys.stderr)
for item in drifted:
print(f" - {item}", file=sys.stderr)
return 1
print("generated workflows are up to date")
return 0
if __name__ == "__main__":
raise SystemExit(main())

Xet Storage Details

Size:
10.8 kB
·
Xet hash:
0fce29d0a1d4ef35511b4a544803743cd0f4f440ec7426f707ef21a5a681989d

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.