|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Generate TypeScript types from Kubernetes CRD OpenAPI schemas. |
| 3 | +
|
| 4 | +Usage: |
| 5 | + python3 hack/generate-types.py # from live cluster |
| 6 | + python3 hack/generate-types.py --from-dir crds/ # from local CRD YAML files |
| 7 | +
|
| 8 | +Generates src/models/generated/*.ts with TypeScript interfaces matching |
| 9 | +the CRD spec and status schemas. |
| 10 | +""" |
| 11 | + |
| 12 | +import json |
| 13 | +import os |
| 14 | +import subprocess |
| 15 | +import sys |
| 16 | +import textwrap |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +CRDS = { |
| 20 | + "proposals.agentic.openshift.io": "Proposal", |
| 21 | + "proposalapprovals.agentic.openshift.io": "ProposalApproval", |
| 22 | + "approvalpolicies.agentic.openshift.io": "ApprovalPolicy", |
| 23 | + "analysisresults.agentic.openshift.io": "AnalysisResult", |
| 24 | +} |
| 25 | + |
| 26 | +OUT_DIR = Path(__file__).resolve().parent.parent / "src" / "models" / "generated" |
| 27 | +BANNER = "// Auto-generated from CRD — do not edit manually.\n// Regenerate with: make generate-types\n" |
| 28 | + |
| 29 | + |
| 30 | +def extract_from_cluster() -> dict[str, dict]: |
| 31 | + schemas = {} |
| 32 | + for crd_name in CRDS: |
| 33 | + print(f" Extracting {crd_name}...") |
| 34 | + result = subprocess.run( |
| 35 | + ["oc", "get", "crd", crd_name, "-o", |
| 36 | + "jsonpath={.spec.versions[0].schema.openAPIV3Schema}"], |
| 37 | + capture_output=True, text=True, check=True, |
| 38 | + ) |
| 39 | + schemas[crd_name] = json.loads(result.stdout) |
| 40 | + return schemas |
| 41 | + |
| 42 | + |
| 43 | +def extract_from_dir(d: str) -> dict[str, dict]: |
| 44 | + import yaml |
| 45 | + schemas = {} |
| 46 | + for crd_name in CRDS: |
| 47 | + for f in Path(d).glob("*.yaml"): |
| 48 | + with open(f) as fh: |
| 49 | + doc = yaml.safe_load(fh) |
| 50 | + if doc and doc.get("metadata", {}).get("name") == crd_name: |
| 51 | + schemas[crd_name] = doc["spec"]["versions"][0]["schema"]["openAPIV3Schema"] |
| 52 | + print(f" {f.name} -> {crd_name}") |
| 53 | + break |
| 54 | + else: |
| 55 | + print(f" WARNING: {crd_name} not found in {d}") |
| 56 | + return schemas |
| 57 | + |
| 58 | + |
| 59 | +def schema_to_ts(schema: dict, indent: int = 0) -> str: |
| 60 | + """Convert an OpenAPI schema object to a TypeScript type string.""" |
| 61 | + pad = " " * indent |
| 62 | + |
| 63 | + if "x-kubernetes-preserve-unknown-fields" in schema: |
| 64 | + return "Record<string, unknown>" |
| 65 | + |
| 66 | + typ = schema.get("type", "object") |
| 67 | + |
| 68 | + if "enum" in schema: |
| 69 | + return " | ".join(f"'{v}'" for v in schema["enum"]) |
| 70 | + |
| 71 | + if typ == "string": |
| 72 | + fmt = schema.get("format", "") |
| 73 | + if fmt in ("date-time", "date"): |
| 74 | + return "string" |
| 75 | + return "string" |
| 76 | + |
| 77 | + if typ == "integer": |
| 78 | + return "number" |
| 79 | + |
| 80 | + if typ == "number": |
| 81 | + return "number" |
| 82 | + |
| 83 | + if typ == "boolean": |
| 84 | + return "boolean" |
| 85 | + |
| 86 | + if typ == "array": |
| 87 | + items = schema.get("items", {}) |
| 88 | + item_type = schema_to_ts(items, indent) |
| 89 | + return f"({item_type})[]" |
| 90 | + |
| 91 | + if typ == "object": |
| 92 | + props = schema.get("properties", {}) |
| 93 | + if not props: |
| 94 | + additional = schema.get("additionalProperties") |
| 95 | + if additional and isinstance(additional, dict): |
| 96 | + val_type = schema_to_ts(additional, indent) |
| 97 | + return f"Record<string, {val_type}>" |
| 98 | + return "Record<string, unknown>" |
| 99 | + |
| 100 | + required = set(schema.get("required", [])) |
| 101 | + lines = ["{"] |
| 102 | + for name, prop_schema in sorted(props.items()): |
| 103 | + desc = prop_schema.get("description", "") |
| 104 | + optional = "?" if name not in required else "" |
| 105 | + prop_type = schema_to_ts(prop_schema, indent + 1) |
| 106 | + if desc: |
| 107 | + short = desc.replace("\n", " ").strip() |
| 108 | + if len(short) > 100: |
| 109 | + short = short[:97] + "..." |
| 110 | + lines.append(f"{pad} /** {short} */") |
| 111 | + lines.append(f"{pad} {name}{optional}: {prop_type};") |
| 112 | + lines.append(f"{pad}}}") |
| 113 | + return "\n".join(lines) |
| 114 | + |
| 115 | + return "unknown" |
| 116 | + |
| 117 | + |
| 118 | +def generate_one(crd_name: str, type_name: str, schema: dict) -> str: |
| 119 | + """Generate TypeScript for a single CRD.""" |
| 120 | + lines = [BANNER, ""] |
| 121 | + |
| 122 | + props = schema.get("properties", {}) |
| 123 | + spec_schema = props.get("spec", {}) |
| 124 | + status_schema = props.get("status", {}) |
| 125 | + |
| 126 | + # Generate Spec type |
| 127 | + if spec_schema.get("properties"): |
| 128 | + spec_ts = schema_to_ts(spec_schema, 0) |
| 129 | + lines.append(f"export type {type_name}Spec = {spec_ts};\n") |
| 130 | + |
| 131 | + # Generate Status type |
| 132 | + if status_schema.get("properties"): |
| 133 | + status_ts = schema_to_ts(status_schema, 0) |
| 134 | + lines.append(f"export type {type_name}Status = {status_ts};\n") |
| 135 | + |
| 136 | + # Generate nested types that are reusable (conditions, steps, etc.) |
| 137 | + # Extract any deeply nested object types that appear in spec or status |
| 138 | + |
| 139 | + return "\n".join(lines) |
| 140 | + |
| 141 | + |
| 142 | +def main(): |
| 143 | + if len(sys.argv) > 2 and sys.argv[1] == "--from-dir": |
| 144 | + schemas = extract_from_dir(sys.argv[2]) |
| 145 | + else: |
| 146 | + print("Extracting CRD schemas from cluster...") |
| 147 | + schemas = extract_from_cluster() |
| 148 | + |
| 149 | + OUT_DIR.mkdir(parents=True, exist_ok=True) |
| 150 | + |
| 151 | + for crd_name, schema in schemas.items(): |
| 152 | + type_name = CRDS[crd_name] |
| 153 | + out_file = OUT_DIR / f"{crd_name.split('.')[0]}.ts" |
| 154 | + print(f" Generating {out_file.name} ({type_name})...") |
| 155 | + |
| 156 | + ts_code = generate_one(crd_name, type_name, schema) |
| 157 | + out_file.write_text(ts_code) |
| 158 | + |
| 159 | + # Barrel export |
| 160 | + barrel = OUT_DIR / "index.ts" |
| 161 | + barrel_lines = [BANNER, ""] |
| 162 | + for crd_name in schemas: |
| 163 | + base = crd_name.split(".")[0] |
| 164 | + barrel_lines.append(f"export * from './{base}';") |
| 165 | + barrel_lines.append("") |
| 166 | + barrel.write_text("\n".join(barrel_lines)) |
| 167 | + |
| 168 | + print(f"Done. Generated types in {OUT_DIR}") |
| 169 | + |
| 170 | + |
| 171 | +if __name__ == "__main__": |
| 172 | + main() |
0 commit comments