Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 99 additions & 26 deletions .github/actions/repo-gate/repo_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,35 +429,103 @@ def single_document(documents: list[object]) -> object:
return documents[0]


UVX_READER = (
"import json, sys, yaml\n"
"def step(item):\n"
" if not isinstance(item, dict):\n"
" return None\n"
" out = {'run': item['run']} if isinstance(item.get('run'), str) else {}\n"
" if item.get('name') and not isinstance(item['name'], (dict, list)):\n"
" out['name'] = str(item['name'])\n"
" if item.get('shell') is not None:\n"
" out['shell'] = item['shell'] if isinstance(item['shell'], str) else ''\n"
" return out\n"
"def project(document):\n"
" if not isinstance(document, dict):\n"
" return None\n"
" runs = document.get('runs')\n"
" steps = runs.get('steps') if isinstance(runs, dict) else None\n"
" if not isinstance(steps, list):\n"
" return {}\n"
" return {'runs': {'steps': [step(item) for item in steps]}}\n"
"try:\n"
" with open(sys.argv[1], encoding='utf-8') as handle:\n"
" text = json.dumps([project(document) for document in yaml.safe_load_all(handle)])\n"
"except Exception as error:\n"
" if isinstance(error, yaml.YAMLError):\n"
" line = f'invalid YAML: {error}'\n"
" else:\n"
" line = f'unreadable: {type(error).__name__}: {error}'\n"
" sys.exit(' '.join(line.split()))\n"
"sys.stdout.write(text)\n"
)
PYYAML_PYTHON: list[str] = []
ISOLATED = ("-I", "-X", "utf8")


class UvxUnavailable(Exception):
"""uvx could not provide an interpreter with PyYAML, so no action can be read through it."""


def run_utf8(command: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(
command,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=YAML_TIMEOUT,
)


def pyyaml_python() -> str:
"""An interpreter that imports PyYAML, resolved through uvx once per run."""
if PYYAML_PYTHON:
return PYYAML_PYTHON[0]
uvx = shutil.which("uvx")
if uvx is None:
raise UvxUnavailable("neither PyYAML nor uvx is available to read the action")
probe = "import sys, yaml; print(sys.executable)"
try:
result = run_utf8([uvx, "--with", "pyyaml", "python", *ISOLATED, "-c", probe])
except subprocess.TimeoutExpired:
raise UvxUnavailable(f"uvx timed out after {YAML_TIMEOUT}s providing PyYAML") from None
except OSError as error:
raise UvxUnavailable(f"uvx could not start: {error}") from None
if result.returncode != 0 or not result.stdout.strip():
lines = [line for line in result.stderr.splitlines() if line.strip()]
first = f": {lines[0]}" if lines else ""
raise UvxUnavailable(f"uvx exited {result.returncode} providing PyYAML{first}")
PYYAML_PYTHON.append(result.stdout.strip())
return PYYAML_PYTHON[0]


def load_through_uvx(path: Path) -> list[object]:
"""The fields the check reads from each document, parsed by PyYAML in the uvx interpreter."""
python = pyyaml_python()
try:
result = run_utf8([python, *ISOLATED, "-c", UVX_READER, str(path)])
except subprocess.TimeoutExpired:
raise ValueError(f"reading timed out after {YAML_TIMEOUT}s") from None
except OSError as error:
raise UvxUnavailable(f"the interpreter uvx provided could not start: {error}") from None
if result.returncode != 0:
lines = [line for line in result.stderr.splitlines() if line.strip()]
raise ValueError(lines[-1] if lines else f"the reader exited {result.returncode}")
documents: list[object] = json.loads(result.stdout)
return documents


def load_action(path: Path) -> object:
"""The one parsed document of an action file, through PyYAML where importable, else yq."""
"""The one parsed document of an action file, through PyYAML on every host.

PyYAML is used in process where it is importable, and otherwise under uvx, a declared host tool.
"""
try:
import yaml # type: ignore[import-untyped]
except ImportError:
yq = shutil.which("yq")
if yq is None:
raise RuntimeError("neither PyYAML nor yq is available to read the action") from None
result = subprocess.run(
[yq, "-o=json", ".", str(path)],
capture_output=True,
text=True,
encoding="utf-8",
check=False,
timeout=YAML_TIMEOUT,
)
if result.returncode != 0:
raise ValueError(f"yq could not read the action: {result.stderr.strip()}")
decoder = json.JSONDecoder()
documents: list[object] = []
text, at = result.stdout, 0
while True:
while at < len(text) and text[at].isspace():
at += 1
if at >= len(text):
break
document, at = decoder.raw_decode(text, at)
documents.append(document)
return single_document(documents)
return single_document(load_through_uvx(path))
try:
with path.open(encoding="utf-8") as handle:
return single_document(list(yaml.safe_load_all(handle)))
Expand Down Expand Up @@ -684,8 +752,13 @@ def check_composite_actions(root: Path, files: list[str]) -> list[str]:
if unreachable is not None:
hits.append(f"{unreachable}, so no run body was shellchecked")
else:
PYYAML_PYTHON.clear()
for path in actions:
hits.extend(check_composite_shell(root, path))
try:
hits.extend(check_composite_shell(root, path))
except UvxUnavailable as error:
hits.append(f"{error}, so no run body was shellchecked")
break
hits.extend(check_composite_schema(root, actions))
NOTES.append(f"checked {len(actions)} action file(s).")
return hits
Expand Down
4 changes: 2 additions & 2 deletions scripts/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Repo Scripts

The fleet's checks and review tooling, run by hand, with the deterministic ones also gating CI. Each one exists because the CI linters pass on the failure it catches: `markdownlint`, `cspell`, `actionlint`, and `editorconfig-checker` all report clean on prose that breaks a documented [`GOVERNANCE.md`][governance] rule. The pre-commit hook runs two deterministic doc gates, each at the scope that fits it. `python3 scripts/prose_lint.py . --diff HEAD` is diff-scoped, at about 0.13 seconds where its whole-tree sweep costs about 2.2. `python3 scripts/repo_gate.py --check eol` is repo-wide, since it reads `.gitattributes` against `.editorconfig` and takes no file list, and at about 0.04 seconds there is nothing to scope. The earlier decision to keep doc linters out was made when a sweep was the only mode, and what reversed it is the diff scope rather than a change of preference. The gates needing Docker, and `sha-pin` which resolves a pin against the GitHub API, stay in CI. A plain `repo_gate.py` run also includes `composite-actions`, which needs Docker and `uvx` or `pipx`. The hook reads the working tree rather than the index, so a partially staged file is judged on all of its edits. The pull request gate reads every line the branch changes against its base. A merge commit is diffed against `MERGE_HEAD` rather than `HEAD`, so the lines the merged-in parent brought are not read as added.
The fleet's checks and review tooling, run by hand, with the deterministic ones also gating CI. Each one exists because the CI linters pass on the failure it catches: `markdownlint`, `cspell`, `actionlint`, and `editorconfig-checker` all report clean on prose that breaks a documented [`GOVERNANCE.md`][governance] rule. The pre-commit hook runs two deterministic doc gates, each at the scope that fits it. `python3 scripts/prose_lint.py . --diff HEAD` is diff-scoped, at about 0.13 seconds where its whole-tree sweep costs about 2.2. `python3 scripts/repo_gate.py --check eol` is repo-wide, since it reads `.gitattributes` against `.editorconfig` and takes no file list, and at about 0.04 seconds there is nothing to scope. The earlier decision to keep doc linters out was made when a sweep was the only mode, and what reversed it is the diff scope rather than a change of preference. The gates needing Docker, and `sha-pin` which resolves a pin against the GitHub API, stay in CI. A plain `repo_gate.py` run also includes `composite-actions`, whose shell half needs Docker and either PyYAML or `uvx`, and whose schema half needs `uvx` or `pipx`. The hook reads the working tree rather than the index, so a partially staged file is judged on all of its edits. The pull request gate reads every line the branch changes against its base. A merge commit is diffed against `MERGE_HEAD` rather than `HEAD`, so the lines the merged-in parent brought are not read as added.

**Hosted here and reached, never carried.** These are not declared in [`spec/files.json`][files], so the audit does not expect a downstream repo to ship them, the same footing as `spec/audit.py`. That is the fleet model rather than an omission: a gate holding no per-repo content has one canonical implementation for the fleet. The prose and repository gate implementations live beside their composite actions under `.github/actions/`, which lets reusable workflows reach the implementation at their pinned hub commit through `$/.github/actions/` without checking out the hub. The same-named files in `scripts/` are thin local entry points that call those action-owned implementations, so maintainers and hooks retain the established commands from a hub checkout without creating a second copy of either gate. A repository that cannot reach the hub reports a local check as not run rather than reconstructing it, since a rebuilt gate encodes its author's reading of the rule and agrees with no other repository.

Expand Down Expand Up @@ -114,7 +114,7 @@ Deterministic checks:
- `sha-pin`: every external action or reusable-workflow `uses:` reference is a 40-hex commit SHA, with the documented `dotnet/nbgv@master` exception. References under the scanned repository's owner are also resolved through GitHub. References under another owner are shape-checked only. Local (`./`) and self-repository (`$/`) references name no ref, so they take no pin, and a quoted one is recognized once its quotes are stripped. They resolve differently, though. A `$/` reference and a job-level `./` reusable-workflow call resolve at the calling workflow file's commit, while a `./` action reference resolves against whatever the job checked out, which is the caller's tree where a reusable workflow called from another repository checks out its caller. A reference starting with a bare `.github/` is reported, since GitHub reads it as `owner/repo` rather than as a path.
- `eol`: every path pinned LF in [`.gitattributes`][gitattributes] has the matching [`.editorconfig`][editorconfig] override the line-ending rule requires, with EditorConfig brace syntax expanded. One direction only: an `.editorconfig` LF glob with no git pin is legitimate, since `.editorconfig` governs what the editor writes where git enforces a class it must not guess at.
- `eol-coverage`: the same pins read against the tree instead. A tracked file opening `#!` that git does not resolve to `eol=lf` is an interpreter line a CRLF checkout breaks, and a pin matching no tracked file is dead unless its block is marked `forward-declared`.
- `composite-actions`: every tracked `action.yml` or `action.yaml` under `.github/actions/`, at any depth, is shellchecked and schema-checked, because actionlint reads workflows only. Each non-empty `run:` body of a bash, sh, or unset-shell step goes to shellcheck. Every `${{ }}` expression is replaced by a placeholder first. A finding names the action file and the step. A pwsh or python step is skipped. The file set goes to `check-jsonschema`'s `vendor.github-actions` builtin through `uvx check-jsonschema@latest`, or `pipx run` where `uvx` is absent. Shellcheck runs from the `koalaman/shellcheck:stable` image, so the check needs Docker. It reads the action through PyYAML or `yq`. Each half reports its own missing tool. Bodies run at warning severity without SC2154, so this is weaker than shellcheck over a `.sh` file. A tree with no action file is skipped with a note.
- `composite-actions`: every tracked `action.yml` or `action.yaml` under `.github/actions/`, at any depth, is shellchecked and schema-checked, because actionlint reads workflows only. Each non-empty `run:` body of a bash, sh, or unset-shell step goes to shellcheck. Every `${{ }}` expression is replaced by a placeholder first. A finding names the action file and the step. A pwsh or python step is skipped. The file set goes to `check-jsonschema`'s `vendor.github-actions` builtin through `uvx check-jsonschema@latest`, or `pipx run` where `uvx` is absent. Shellcheck runs from the `koalaman/shellcheck:stable` image, so the check needs Docker. It reads the action through PyYAML, in process where it is importable and through `uvx --with pyyaml` otherwise. Each half reports its own missing tool. Bodies run at warning severity without SC2154, so this is weaker than shellcheck over a `.sh` file. A tree with no action file is skipped with a note.

```sh
python3 scripts/repo_gate.py
Expand Down
Loading
Loading