示例工程 39-ci-cd-release-pipeline

39-ci-cd-release-pipeline/01-ci-local-script/ci_local_script.py

python · 1.6 KB

"""本地 CI 脚本:按阶段运行命令,聚合退出码。"""
 
from __future__ import annotations
 
import subprocess
import sys
from dataclasses import dataclass
 
 
@dataclass(frozen=True)
class Step:
    name: str
    command: list[str]
 
 
@dataclass(frozen=True)
class Result:
    name: str
    returncode: int
 
    @property
    def ok(self) -> bool:
        return self.returncode == 0
 
 
def run_step(step: Step) -> Result:
    completed = subprocess.run(step.command, capture_output=True, text=True, check=False)
    return Result(step.name, completed.returncode)
 
 
def run_pipeline(steps: list[Step]) -> list[Result]:
    return [run_step(step) for step in steps]
 
 
def summarize(results: list[Result]) -> str:
    failed = [result.name for result in results if not result.ok]
    if not failed:
        return f"pipeline: passed ({len(results)} steps)"
    return f"pipeline: failed ({len(failed)}/{len(results)}: {', '.join(failed)})"
 
 
def steps_for(simulate_failure: bool) -> list[Step]:
    python = sys.executable
    return [
        Step("lint", [python, "-c", "import ast; ast.parse('x = 1')"]),
        Step(
            "typecheck",
            [python, "-c", "raise SystemExit(3)" if simulate_failure else "pass"],
        ),
        Step("test", [python, "-c", "assert 1 + 1 == 2"]),
    ]
 
 
def main() -> None:
    for label, simulate in (("clean", False), ("broken", True)):
        results = run_pipeline(steps_for(simulate))
        codes = {result.name: result.returncode for result in results}
        print(f"{label}: {codes}")
        print(f"{label} {summarize(results)}")
 
 
if __name__ == "__main__":
    main()