|
| 1 | +"""Command line helpers for stage authors. |
| 2 | +
|
| 3 | +``python -m psrunner validate <stage-folder>`` |
| 4 | + Validates ``stage.json`` and checks that the script declares exactly one ``@stage``. |
| 5 | +
|
| 6 | +``python -m psrunner run <stage-folder> --input sample.json [--secret NAME=VALUE ...]`` |
| 7 | + Runs the stage locally with the real protocol (separate process, temporary work folder). |
| 8 | + File inputs in the sample are written as ``{"$path": "relative/to/sample.json"}``. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import argparse |
| 14 | +import json |
| 15 | +import os |
| 16 | +import shutil |
| 17 | +import subprocess |
| 18 | +import sys |
| 19 | +import tempfile |
| 20 | +import uuid |
| 21 | +from collections.abc import Sequence |
| 22 | +from pathlib import Path |
| 23 | +from typing import Any |
| 24 | + |
| 25 | +from psrunner.errors import ScriptLoadError |
| 26 | +from psrunner.manifest import Manifest, ManifestError, load_manifest |
| 27 | +from psrunner.protocol import ( |
| 28 | + ENV_INPUT, |
| 29 | + ENV_MEMORY_LIMIT_MB, |
| 30 | + ENV_OUTPUT, |
| 31 | + ENV_PROTOCOL, |
| 32 | + ENV_SCRIPT, |
| 33 | + ENV_SECRET_PREFIX, |
| 34 | + ENV_WORK_DIR, |
| 35 | + PROTOCOL_VERSION, |
| 36 | +) |
| 37 | +from psrunner.stage import load_stage_function |
| 38 | +from psrunner.testing import _copy_input_files |
| 39 | + |
| 40 | + |
| 41 | +def _validate(folder: Path) -> int: |
| 42 | + try: |
| 43 | + manifest = load_manifest(folder) |
| 44 | + load_stage_function(manifest.script_path) |
| 45 | + except ManifestError as exc: |
| 46 | + print(f"Invalid manifest {exc.path}:", file=sys.stderr) |
| 47 | + for error in exc.errors: |
| 48 | + print(f" - {error}", file=sys.stderr) |
| 49 | + return 1 |
| 50 | + except ScriptLoadError as exc: |
| 51 | + print(f"Invalid script: [{exc.code}] {exc.message}", file=sys.stderr) |
| 52 | + return 1 |
| 53 | + print( |
| 54 | + f"OK: {manifest.key}@{manifest.version} " |
| 55 | + f"({len(manifest.inputs)} inputs, {len(manifest.outputs)} outputs)" |
| 56 | + ) |
| 57 | + return 0 |
| 58 | + |
| 59 | + |
| 60 | +def _resolve_sample(sample: dict[str, Any], sample_dir: Path, work_dir: Path) -> dict[str, Any]: |
| 61 | + resolved: dict[str, Any] = {} |
| 62 | + for name, value in sample.items(): |
| 63 | + if isinstance(value, dict) and "$path" in value: |
| 64 | + resolved[name] = _copy_input_files(name, sample_dir / value["$path"], work_dir) |
| 65 | + elif ( |
| 66 | + isinstance(value, list) |
| 67 | + and value |
| 68 | + and all(isinstance(v, dict) and "$path" in v for v in value) |
| 69 | + ): |
| 70 | + resolved[name] = _copy_input_files( |
| 71 | + name, [sample_dir / v["$path"] for v in value], work_dir |
| 72 | + ) |
| 73 | + else: |
| 74 | + resolved[name] = value |
| 75 | + return resolved |
| 76 | + |
| 77 | + |
| 78 | +def _run(folder: Path, input_file: Path | None, secrets: Sequence[str], keep: bool) -> int: |
| 79 | + try: |
| 80 | + manifest: Manifest = load_manifest(folder) |
| 81 | + except ManifestError as exc: |
| 82 | + print(f"Invalid manifest {exc.path}: {'; '.join(exc.errors)}", file=sys.stderr) |
| 83 | + return 1 |
| 84 | + |
| 85 | + work_dir = Path(tempfile.mkdtemp(prefix="psrunner-run-")) |
| 86 | + for sub in ("in", "out", "tmp"): |
| 87 | + (work_dir / sub).mkdir() |
| 88 | + |
| 89 | + sample: dict[str, Any] = {} |
| 90 | + if input_file is not None: |
| 91 | + sample = json.loads(input_file.read_text(encoding="utf-8")) |
| 92 | + inputs = _resolve_sample( |
| 93 | + sample, (input_file or folder).parent if input_file else folder, work_dir |
| 94 | + ) |
| 95 | + |
| 96 | + document = { |
| 97 | + "protocol": PROTOCOL_VERSION, |
| 98 | + "context": { |
| 99 | + "runId": uuid.uuid4().hex, |
| 100 | + "stepKey": manifest.key, |
| 101 | + "attempt": 1, |
| 102 | + "stage": {"key": manifest.key, "version": manifest.version}, |
| 103 | + "isTest": True, |
| 104 | + "inputFields": manifest.raw["inputs"], |
| 105 | + "outputFields": manifest.raw["outputs"], |
| 106 | + }, |
| 107 | + "inputs": inputs, |
| 108 | + } |
| 109 | + (work_dir / "input.json").write_text(json.dumps(document, ensure_ascii=False), encoding="utf-8") |
| 110 | + |
| 111 | + env = {key: value for key, value in os.environ.items() if key in {"PATH", "SYSTEMROOT", "LANG"}} |
| 112 | + env.update( |
| 113 | + { |
| 114 | + "TEMP": str(work_dir / "tmp"), |
| 115 | + "TMP": str(work_dir / "tmp"), |
| 116 | + ENV_PROTOCOL: str(PROTOCOL_VERSION), |
| 117 | + ENV_INPUT: str(work_dir / "input.json"), |
| 118 | + ENV_OUTPUT: str(work_dir / "output.json"), |
| 119 | + ENV_WORK_DIR: str(work_dir), |
| 120 | + ENV_SCRIPT: str(manifest.script_path.resolve()), |
| 121 | + ENV_MEMORY_LIMIT_MB: str(manifest.raw.get("memoryLimitMb", 0)), |
| 122 | + } |
| 123 | + ) |
| 124 | + for item in secrets: |
| 125 | + name, _, value = item.partition("=") |
| 126 | + env[f"{ENV_SECRET_PREFIX}{name}"] = value |
| 127 | + |
| 128 | + completed = subprocess.run( |
| 129 | + [sys.executable, "-I", "-X", "utf8", "-m", "psrunner.host"], |
| 130 | + cwd=work_dir, |
| 131 | + env=env, |
| 132 | + capture_output=True, |
| 133 | + text=True, |
| 134 | + encoding="utf-8", |
| 135 | + errors="replace", |
| 136 | + check=False, |
| 137 | + ) |
| 138 | + if completed.stdout: |
| 139 | + print("--- stdout ---") |
| 140 | + print(completed.stdout.rstrip()) |
| 141 | + if completed.stderr: |
| 142 | + print("--- stderr ---") |
| 143 | + print(completed.stderr.rstrip()) |
| 144 | + |
| 145 | + output_path = work_dir / "output.json" |
| 146 | + if not output_path.exists(): |
| 147 | + print( |
| 148 | + f"Process exited with code {completed.returncode} without output.json.", file=sys.stderr |
| 149 | + ) |
| 150 | + return 1 |
| 151 | + output = json.loads(output_path.read_text(encoding="utf-8")) |
| 152 | + print("--- output.json ---") |
| 153 | + print(json.dumps(output, indent=2, ensure_ascii=False)) |
| 154 | + if keep: |
| 155 | + print(f"Work folder: {work_dir}") |
| 156 | + else: |
| 157 | + shutil.rmtree(work_dir, ignore_errors=True) |
| 158 | + return 0 if output.get("status") == "ok" else 1 |
| 159 | + |
| 160 | + |
| 161 | +def main(argv: Sequence[str] | None = None) -> int: |
| 162 | + parser = argparse.ArgumentParser(prog="psrunner", description="PythonScriptRunner stage tools") |
| 163 | + commands = parser.add_subparsers(dest="command", required=True) |
| 164 | + |
| 165 | + validate = commands.add_parser("validate", help="validate stage.json and the script") |
| 166 | + validate.add_argument("folder", type=Path) |
| 167 | + |
| 168 | + run = commands.add_parser("run", help="run a stage locally with the real protocol") |
| 169 | + run.add_argument("folder", type=Path) |
| 170 | + run.add_argument("--input", type=Path, help="JSON file with the inputs") |
| 171 | + run.add_argument("--secret", action="append", default=[], help="NAME=VALUE (repeatable)") |
| 172 | + run.add_argument("--keep", action="store_true", help="print the work folder path") |
| 173 | + |
| 174 | + args = parser.parse_args(argv) |
| 175 | + if args.command == "validate": |
| 176 | + return _validate(args.folder) |
| 177 | + return _run(args.folder, args.input, args.secret, args.keep) |
0 commit comments