use anyhow::{anyhow, Context, Result};
use serde::Deserialize;
use std::collections::BTreeMap;
#[derive(Debug, Deserialize)]
pub struct OpenApiDoc {
pub components: Components,
}
#[derive(Debug, Deserialize)]
pub struct Components {
pub schemas: BTreeMap<String, KindShape>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct KindShape {
#[serde(default, rename = "x-kubernetes-group-version-kind")]
pub gvks: Vec<XGvk>,
#[serde(default)]
pub description: String,
#[serde(default)]
pub properties: BTreeMap<String, serde_json::Value>,
#[serde(default)]
pub required: Vec<String>,
}
#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
pub struct XGvk {
pub group: String,
pub version: String,
pub kind: String,
}
impl OpenApiDoc {
pub fn load(path: &std::path::Path) -> Result<Self> {
let bytes = std::fs::read(path)
.with_context(|| format!("read {}", path.display()))?;
serde_json::from_slice(&bytes)
.with_context(|| format!("parse {}", path.display()))
}
pub fn shape(&self, openapi_key: &str) -> Result<&KindShape> {
self.components.schemas.get(openapi_key)
.ok_or_else(|| anyhow!("kind {openapi_key:?} not in OpenAPI components.schemas"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_minimal_openapi_doc() {
let json = serde_json::json!({
"components": {
"schemas": {
"io.k8s.api.core.v1.Pod": {
"x-kubernetes-group-version-kind": [
{"group": "", "version": "v1", "kind": "Pod"}
],
"description": "Pod is a collection of containers",
"properties": {"metadata": {}, "spec": {}, "status": {}},
"required": ["spec"]
}
}
}
});
let doc: OpenApiDoc = serde_json::from_value(json).unwrap();
let pod = doc.shape("io.k8s.api.core.v1.Pod").unwrap();
assert_eq!(pod.gvks.len(), 1);
assert_eq!(pod.gvks[0], XGvk {
group: "".into(), version: "v1".into(), kind: "Pod".into(),
});
}
#[test]
fn missing_shape_errors() {
let doc = OpenApiDoc {
components: Components { schemas: BTreeMap::new() },
};
let err = doc.shape("io.k8s.api.core.v1.Pod").unwrap_err();
assert!(err.to_string().contains("not in OpenAPI"));
}
}