示例工程 39-ci-cd-release-pipeline
39-ci-cd-release-pipeline/02-github-actions-yaml/github_actions_yaml.py
"""解析并静态校验一份 GitHub Actions 工作流(YAML 子集,无第三方依赖)。"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
class YamlError(ValueError):
"""缩进或结构不符合本解析器支持的子集。"""
def _entries(text: str) -> list[tuple[int, str]]:
entries: list[tuple[int, str]] = []
for raw in text.splitlines():
if not raw.strip() or raw.lstrip().startswith("#"):
continue
if "\t" in raw[: len(raw) - len(raw.lstrip())]:
raise YamlError("tabs are not allowed for indentation")
body = raw.split(" #", 1)[0].rstrip()
entries.append((len(body) - len(body.lstrip()), body.strip()))
return entries
def _scalar(token: str) -> Any:
if len(token) >= 2 and token[0] == token[-1] and token[0] in "\"'":
return token[1:-1]
if token in {"true", "false"}:
return token == "true"
if token.isdigit():
return int(token)
return token
def _split_map(text: str) -> tuple[str, str]:
key, sep, value = text.partition(":")
if not sep or not key.strip():
raise YamlError(f"expected 'key: value', got {text!r}")
return key.strip(), value.strip()
def _parse_map(
entries: list[tuple[int, str]], index: int, indent: int
) -> tuple[dict[str, Any], int]:
result: dict[str, Any] = {}
while index < len(entries):
current_indent, text = entries[index]
if current_indent < indent or text.startswith("- "):
break
if current_indent > indent:
raise YamlError(f"unexpected indent at {text!r}")
key, value = _split_map(text)
index += 1
if value:
result[key] = _scalar(value)
elif index < len(entries) and entries[index][0] > indent:
result[key], index = _parse_block(entries, index, entries[index][0])
else:
result[key] = None
return result, index
def _parse_list(entries: list[tuple[int, str]], index: int, indent: int) -> tuple[list[Any], int]:
items: list[Any] = []
while index < len(entries):
current_indent, text = entries[index]
if current_indent != indent or not text.startswith("- "):
break
item = text[2:].strip()
index += 1
if ":" not in item:
items.append(_scalar(item))
continue
key, value = _split_map(item)
mapping: dict[str, Any] = {}
if value:
mapping[key] = _scalar(value)
elif index < len(entries) and entries[index][0] > indent:
mapping[key], index = _parse_block(entries, index, entries[index][0])
else:
mapping[key] = None
while index < len(entries) and entries[index][0] > indent:
extra, index = _parse_map(entries, index, entries[index][0])
mapping.update(extra)
items.append(mapping)
return items, index
def _parse_block(entries: list[tuple[int, str]], index: int, indent: int) -> tuple[Any, int]:
if entries[index][1].startswith("- "):
return _parse_list(entries, index, indent)
return _parse_map(entries, index, indent)
def parse_yaml(text: str) -> dict[str, Any]:
entries = _entries(text)
if not entries:
return {}
value, index = _parse_block(entries, 0, entries[0][0])
if index != len(entries):
raise YamlError(f"unparsed content at {entries[index][1]!r}")
if not isinstance(value, dict):
raise YamlError("workflow root must be a mapping")
return value
def lint_workflow(workflow: dict[str, Any]) -> list[str]:
problems: list[str] = []
if not workflow.get("name"):
problems.append("missing name")
if "on" not in workflow:
problems.append("missing on")
jobs = workflow.get("jobs")
if not isinstance(jobs, dict) or not jobs:
return [*problems, "missing jobs"]
for job_name, job in jobs.items():
if not isinstance(job, dict):
problems.append(f"{job_name}: job must be a mapping")
continue
if not isinstance(job.get("runs-on"), str):
problems.append(f"{job_name}: missing runs-on")
steps = job.get("steps")
if not isinstance(steps, list) or not steps:
problems.append(f"{job_name}: missing steps")
continue
for position, step in enumerate(steps, start=1):
if not isinstance(step, dict) or not ({"uses", "run"} & step.keys()):
problems.append(f"{job_name}: step {position} needs uses or run")
return problems
def load(path: Path) -> dict[str, Any]:
return parse_yaml(path.read_text(encoding="utf-8"))
def main() -> None:
workflow = load(Path(__file__).with_name("workflow.yml"))
jobs = workflow["jobs"]
job = jobs["test"]
versions = job["strategy"]["matrix"]["python-version"]
print(f"jobs: {list(jobs)}")
print(f"python_versions: {versions}")
print(f"steps: {len(job['steps'])}")
print(f"problems: {lint_workflow(workflow)}")
print(f"json_roundtrip: {json.loads(json.dumps(workflow))['name']}")
if __name__ == "__main__":
main()