engenho_kube_codegen/
openapi.rs1use anyhow::{Context, Result, anyhow};
11use serde::Deserialize;
12use std::collections::BTreeMap;
13
14#[derive(Debug, Deserialize)]
17pub struct OpenApiDoc {
18 pub components: Components,
20}
21
22#[derive(Debug, Deserialize)]
24pub struct Components {
25 pub schemas: BTreeMap<String, KindShape>,
28}
29
30#[derive(Debug, Deserialize, Clone)]
32pub struct KindShape {
33 #[serde(default, rename = "x-kubernetes-group-version-kind")]
36 pub gvks: Vec<XGvk>,
37
38 #[serde(default)]
40 pub description: String,
41
42 #[serde(default)]
44 pub properties: BTreeMap<String, serde_json::Value>,
45
46 #[serde(default)]
48 pub required: Vec<String>,
49}
50
51#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
53pub struct XGvk {
54 pub group: String,
56 pub version: String,
58 pub kind: String,
60}
61
62impl OpenApiDoc {
63 pub fn load(path: &std::path::Path) -> Result<Self> {
69 let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
70 serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))
71 }
72
73 pub fn shape(&self, openapi_key: &str) -> Result<&KindShape> {
79 self.components
80 .schemas
81 .get(openapi_key)
82 .ok_or_else(|| anyhow!("kind {openapi_key:?} not in OpenAPI components.schemas"))
83 }
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89
90 #[test]
91 fn parses_minimal_openapi_doc() {
92 let json = serde_json::json!({
93 "components": {
94 "schemas": {
95 "io.k8s.api.core.v1.Pod": {
96 "x-kubernetes-group-version-kind": [
97 {"group": "", "version": "v1", "kind": "Pod"}
98 ],
99 "description": "Pod is a collection of containers",
100 "properties": {"metadata": {}, "spec": {}, "status": {}},
101 "required": ["spec"]
102 }
103 }
104 }
105 });
106 let doc: OpenApiDoc = serde_json::from_value(json).unwrap();
107 let pod = doc.shape("io.k8s.api.core.v1.Pod").unwrap();
108 assert_eq!(pod.gvks.len(), 1);
109 assert_eq!(
110 pod.gvks[0],
111 XGvk {
112 group: String::new(),
113 version: "v1".into(),
114 kind: "Pod".into(),
115 }
116 );
117 }
118
119 #[test]
120 fn missing_shape_errors() {
121 let doc = OpenApiDoc {
122 components: Components {
123 schemas: BTreeMap::new(),
124 },
125 };
126 let err = doc.shape("io.k8s.api.core.v1.Pod").unwrap_err();
127 assert!(err.to_string().contains("not in OpenAPI"));
128 }
129}