"""Render the `stewardship/repoctl-result@0.1` envelope as human, YAML or JSON output.""" from __future__ import annotations import sys from collections.abc import Callable from typing import Any from .constants import RESULT_SCHEMA from .io import dump_json, yaml_text from .types import Finding def build_envelope(command: str, outcome: str, data: Any, findings: list[Finding]) -> dict[str, Any]: return { "schema": RESULT_SCHEMA, "command": command, "outcome": outcome, "data": data, "findings": [f.to_dict() for f in findings], } def print_findings_human(findings: list[Finding]) -> None: for finding in findings: location = f" [{finding.resource}]" if finding.resource else "" path = f" ({finding.path})" if finding.path else "" print(f"{finding.severity.upper()} {finding.code}{location}{path}: {finding.message}", file=sys.stderr) def emit( envelope: dict[str, Any], output: str, human_renderer: Callable[[dict[str, Any]], None] | None = None, ) -> None: if output == "json": sys.stdout.write(dump_json(envelope)) elif output == "yaml": sys.stdout.write(yaml_text(envelope)) else: for finding in envelope["findings"]: location = f" [{finding['resource']}]" if finding.get("resource") else "" path = f" ({finding['path']})" if finding.get("path") else "" print(f"{finding['severity'].upper()} {finding['code']}{location}{path}: {finding['message']}", file=sys.stderr) if human_renderer is not None: human_renderer(envelope) else: print(f"{envelope['command']}: {envelope['outcome']}")