use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use crate::types::{RustType, map_schema, type_name_from_ref};
const PROVIDED: &[&str] = &["ObjectMeta", "ListMeta", "TypeMeta"];
const FIELD_OVERRIDES: &[(&str, &str, &str)] = &[
(
"io.k8s.api.core.v1.PodStatus",
"phase",
"Option<crate::curated_enums::PodPhase>",
),
(
"io.k8s.api.core.v1.Secret",
"type",
"Option<crate::curated_enums::SecretType>",
),
];
const SCALAR_TYPE_OVERRIDES: &[(&str, &str)] = &[
(
"io.k8s.apimachinery.pkg.api.resource.Quantity",
"/// `Quantity` — a fixed-point number on the wire as a STRING (`\"1Gi\"`,\n\
/// `\"100m\"`, `\"1.5\"`). Kept as the literal wire text rather than\n\
/// parsed: comparing quantities needs suffix-aware arithmetic, and a\n\
/// lossy round-trip through f64 would change bytes we must echo back\n\
/// verbatim in a GET.\n\
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\n\
#[serde(transparent)]\n\
pub struct Quantity(pub String);\n",
),
(
"io.k8s.apimachinery.pkg.util.intstr.IntOrString",
"/// `IntOrString` — an int OR a string on the wire. `targetPort: 8080`\n\
/// and `targetPort: http` are both legal, as are `maxUnavailable: 1`\n\
/// and `maxUnavailable: \"25%\"`.\n\
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]\n\
#[serde(untagged)]\n\
pub enum IntOrString {\n\
\x20 Int(i64),\n\
\x20 Str(String),\n\
}\n\
\n\
impl Default for IntOrString {\n\
\x20 fn default() -> Self {\n\
\x20 Self::Int(0)\n\
\x20 }\n\
}\n",
),
(
"io.k8s.apimachinery.pkg.apis.meta.v1.Time",
"/// `Time` — RFC3339 on the wire, as a string.\n\
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\n\
#[serde(transparent)]\n\
pub struct Time(pub String);\n",
),
(
"io.k8s.apimachinery.pkg.apis.meta.v1.MicroTime",
"/// `MicroTime` — RFC3339 with microseconds, on the wire as a string.\n\
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\n\
#[serde(transparent)]\n\
pub struct MicroTime(pub String);\n",
),
(
"io.k8s.apimachinery.pkg.runtime.RawExtension",
"/// `RawExtension` — arbitrary JSON held verbatim. Used for webhook\n\
/// payloads and CRD defaults, where the shape is not knowable here.\n\
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]\n\
#[serde(transparent)]\n\
pub struct RawExtension(pub serde_json::Value);\n",
),
];
#[must_use]
pub fn scalar_type_override(owner_key: &str) -> Option<&'static str> {
SCALAR_TYPE_OVERRIDES
.iter()
.find(|(k, _)| *k == owner_key)
.map(|(_, body)| *body)
}
fn field_override(owner_key: &str, wire_field: &str) -> Option<&'static str> {
FIELD_OVERRIDES
.iter()
.find(|(o, f, _)| *o == owner_key && *f == wire_field)
.map(|(_, _, t)| *t)
}
fn is_envelope_field(name: &str) -> bool {
matches!(name, "apiVersion" | "kind")
}
#[must_use]
pub fn emit_fields(
owner_key: &str,
properties: &BTreeMap<String, serde_json::Value>,
required: &[String],
refs: &mut BTreeSet<String>,
) -> String {
emit_fields_with(
owner_key,
properties,
required,
refs,
EnvelopePolicy::StripTypeMeta,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnvelopePolicy {
StripTypeMeta,
KeepAllFields,
}
const RAW_KEYWORDS: &[&str] = &[
"as", "break", "const", "continue", "dyn", "else", "enum", "extern", "false", "fn", "for",
"if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
"static", "struct", "trait", "true", "type", "unsafe", "use", "where", "while", "async",
"await", "box", "do", "final", "macro", "override", "priv", "typeof", "unsized", "virtual",
"yield", "try", "gen",
];
const NON_RAW_KEYWORDS: &[&str] = &["self", "Self", "super", "crate"];
#[must_use]
pub fn field_ident(wire: &str) -> (String, Option<String>) {
let snake = snake_case(wire);
if NON_RAW_KEYWORDS.contains(&snake.as_str()) {
(format!("{snake}_"), Some(wire.to_string()))
} else if RAW_KEYWORDS.contains(&snake.as_str()) {
(format!("r#{snake}"), Some(wire.to_string()))
} else if snake == wire {
(snake, None)
} else {
(snake.clone(), Some(wire.to_string()))
}
}
#[must_use]
pub fn snake_case(camel: &str) -> String {
let chars: Vec<char> = camel.chars().collect();
let mut out = String::with_capacity(camel.len() + 4);
for i in 0..chars.len() {
let c = chars[i];
if c.is_ascii_uppercase() {
let prev_lower_or_digit =
i > 0 && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
let plural_s_at_end = i + 1 == chars.len() - 1 && chars[i + 1] == 's';
let acronym_end = i > 0
&& chars[i - 1].is_ascii_uppercase()
&& i + 1 < chars.len()
&& chars[i + 1].is_ascii_lowercase()
&& !plural_s_at_end;
if prev_lower_or_digit || acronym_end {
out.push('_');
}
out.push(c.to_ascii_lowercase());
} else {
out.push(c);
}
}
out
}
fn rustdoc(desc: &str, indent: &str) -> String {
if desc.is_empty() {
return String::new();
}
let first = desc.split("\n\n").next().unwrap_or(desc);
first
.lines()
.map(|l| {
let t = l.trim_start();
if t.is_empty() {
format!("{indent}///")
} else {
format!("{indent}/// {t}")
}
})
.collect::<Vec<_>>()
.join("\n")
}
#[must_use]
pub fn emit_fields_with(
owner_key: &str,
properties: &BTreeMap<String, serde_json::Value>,
required: &[String],
refs: &mut BTreeSet<String>,
envelope: EnvelopePolicy,
) -> String {
let mut out = String::new();
for (name, schema) in properties {
if envelope == EnvelopePolicy::StripTypeMeta && is_envelope_field(name) {
continue;
}
let (field, rename_to) = field_ident(name);
let doc = schema
.get("description")
.and_then(serde_json::Value::as_str)
.map(|d| format!("{}\n", rustdoc(d, " ")))
.unwrap_or_default();
if let Some(ovr) = field_override(owner_key, name) {
let rename = rename_to
.map(|w| format!(", rename = \"{w}\""))
.unwrap_or_default();
out.push_str(&doc);
let _ = writeln!(
out,
" #[serde(default{rename}, skip_serializing_if = \"Option::is_none\")]"
);
let _ = writeln!(out, " pub {field}: {ovr},");
continue;
}
if name == "metadata" {
out.push_str(&doc);
out.push_str(" #[serde(default, skip_serializing_if = \"is_empty_meta\")]\n");
out.push_str(" pub metadata: crate::meta::ObjectMeta,\n");
continue;
}
let ty = map_schema(schema, refs);
let is_required = required.iter().any(|r| r == name);
let rename = rename_to
.map(|w| format!(", rename = \"{w}\""))
.unwrap_or_default();
let (decl_ty, skip) = match (&ty, is_required) {
(RustType::Vec(_), _) => (ty.render(), ", skip_serializing_if = \"Vec::is_empty\""),
(RustType::Map(_), _) => (
ty.render(),
", skip_serializing_if = \"std::collections::BTreeMap::is_empty\"",
),
(_, true) => (ty.render(), ""),
(_, false) => (
format!("Option<{}>", ty.render()),
", skip_serializing_if = \"Option::is_none\"",
),
};
out.push_str(&doc);
let _ = writeln!(out, " #[serde(default{rename}{skip})]");
let _ = writeln!(out, " pub {field}: {decl_ty},");
}
out
}
#[must_use]
pub fn emit_struct(name: &str, owner_key: &str, shape: &SchemaView) -> (String, BTreeSet<String>) {
if let Some(body) = scalar_type_override(owner_key) {
return (body.to_string(), BTreeSet::new());
}
let mut refs = BTreeSet::new();
let fields = emit_fields_with(
owner_key,
&shape.properties,
&shape.required,
&mut refs,
EnvelopePolicy::KeepAllFields,
);
let doc = rustdoc(&shape.description, "");
let doc = if doc.is_empty() {
format!("/// `{name}` — generated typed struct.")
} else {
doc
};
let body = format!(
"{doc}\n#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]\npub struct {name} {{\n{fields}}}\n",
);
(body, refs)
}
#[must_use]
pub fn transitive_structs(
seeds: &BTreeSet<String>,
schemas: &BTreeMap<String, SchemaView>,
) -> Vec<(String, String, SchemaView)> {
let mut queue: Vec<String> = seeds.iter().cloned().collect();
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut collected: BTreeMap<String, (String, SchemaView)> = BTreeMap::new();
while let Some(key) = queue.pop() {
if !seen.insert(key.clone()) {
continue;
}
let name = type_name_from_ref(&key);
if PROVIDED.contains(&name.as_str()) {
continue;
}
let Some(shape) = schemas.get(&key) else {
continue; };
let mut sub_refs = BTreeSet::new();
let _ = emit_fields(&key, &shape.properties, &shape.required, &mut sub_refs);
for r in sub_refs {
if !seen.contains(&r) {
queue.push(r);
}
}
collected.insert(name, (key, shape.clone()));
}
collected
.into_iter()
.map(|(name, (key, shape))| (name, key, shape))
.collect()
}
#[must_use]
pub fn shared_substructs(
kind_keys: &[&str],
kind_names: &[&str],
schemas: &BTreeMap<String, SchemaView>,
) -> Vec<(String, String, SchemaView)> {
let mut seeds = BTreeSet::new();
for k in kind_keys {
if let Some(v) = schemas.get(*k) {
let mut refs = BTreeSet::new();
let _ = emit_fields(k, &v.properties, &v.required, &mut refs);
seeds.extend(refs);
}
}
transitive_structs(&seeds, schemas)
.into_iter()
.filter(|(name, _, _)| !kind_names.contains(&name.as_str()))
.collect()
}
#[derive(Debug, Clone, Default)]
pub struct SchemaView {
pub description: String,
pub properties: BTreeMap<String, serde_json::Value>,
pub required: Vec<String>,
}
#[cfg(test)]
mod snake_case_acronym_tests {
use super::snake_case;
#[test]
fn an_acronym_plus_plural_s_is_one_word() {
assert_eq!(snake_case("nonResourceURLs"), "non_resource_urls");
assert_eq!(snake_case("externalIPs"), "external_ips");
assert_eq!(snake_case("clusterIPs"), "cluster_ips");
assert_eq!(
snake_case("serverAddressByClientCIDRs"),
"server_address_by_client_cidrs"
);
}
#[test]
fn an_acronym_plus_a_word_still_splits() {
assert_eq!(snake_case("IPAddress"), "ip_address");
assert_eq!(snake_case("TLSConfig"), "tls_config");
assert_eq!(snake_case("HTTPSPort"), "https_port");
}
#[test]
fn ordinary_camel_case_is_unchanged() {
assert_eq!(snake_case("podIP"), "pod_ip");
assert_eq!(snake_case("nodeName"), "node_name");
assert_eq!(snake_case("apiGroups"), "api_groups");
assert_eq!(snake_case("resourceNames"), "resource_names");
assert_eq!(snake_case("verbs"), "verbs");
}
}
#[cfg(test)]
mod scalar_override_tests {
use super::{SCALAR_TYPE_OVERRIDES, SchemaView, emit_struct, scalar_type_override};
#[test]
fn all_five_scalar_types_are_overridden() {
for key in [
"io.k8s.apimachinery.pkg.api.resource.Quantity",
"io.k8s.apimachinery.pkg.util.intstr.IntOrString",
"io.k8s.apimachinery.pkg.apis.meta.v1.Time",
"io.k8s.apimachinery.pkg.apis.meta.v1.MicroTime",
"io.k8s.apimachinery.pkg.runtime.RawExtension",
] {
assert!(
scalar_type_override(key).is_some(),
"{key} must be overridden or it emits an empty struct"
);
}
}
#[test]
fn no_override_emits_an_empty_struct() {
for (key, body) in SCALAR_TYPE_OVERRIDES {
assert!(
!body.contains("{}"),
"{key} still emits an empty struct: {body}"
);
assert!(
body.contains("(pub ") || body.contains("pub enum"),
"{key} must be a newtype or an enum: {body}"
);
}
}
#[test]
fn quantity_is_a_transparent_string_newtype() {
let body = scalar_type_override("io.k8s.apimachinery.pkg.api.resource.Quantity").unwrap();
assert!(body.contains("pub struct Quantity(pub String);"));
assert!(body.contains("#[serde(transparent)]"));
}
#[test]
fn int_or_string_is_an_untagged_enum_over_both_forms() {
let body = scalar_type_override("io.k8s.apimachinery.pkg.util.intstr.IntOrString").unwrap();
assert!(body.contains("#[serde(untagged)]"));
assert!(body.contains("Int(i64)"));
assert!(body.contains("Str(String)"));
}
#[test]
fn emit_struct_routes_through_the_override() {
let empty = SchemaView::default();
let (src, refs) = emit_struct(
"Quantity",
"io.k8s.apimachinery.pkg.api.resource.Quantity",
&empty,
);
assert!(src.contains("pub struct Quantity(pub String);"), "{src}");
assert!(refs.is_empty(), "an override references no other schema");
let (plain, _) = emit_struct("SomeThing", "io.k8s.api.core.v1.SomeThing", &empty);
assert!(plain.contains("pub struct SomeThing {"), "{plain}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[allow(clippy::needless_pass_by_value)]
fn view(props: serde_json::Value, required: &[&str]) -> SchemaView {
let properties = props
.as_object()
.unwrap()
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
SchemaView {
description: "A test kind.".into(),
properties,
required: required.iter().map(|s| (*s).to_string()).collect(),
}
}
#[test]
fn snake_case_handles_k8s_camel() {
assert_eq!(
snake_case("automountServiceAccountToken"),
"automount_service_account_token"
);
assert_eq!(snake_case("metadata"), "metadata");
assert_eq!(snake_case("clusterIP"), "cluster_ip");
assert_eq!(snake_case("podIP"), "pod_ip");
assert_eq!(snake_case("hostIP"), "host_ip");
assert_eq!(snake_case("IPAddress"), "ip_address");
}
#[test]
fn rust_keyword_fields_become_raw_or_suffixed_with_rename() {
assert_eq!(
field_ident("type"),
("r#type".to_string(), Some("type".to_string()))
);
assert_eq!(
field_ident("continue"),
("r#continue".to_string(), Some("continue".to_string()))
);
assert_eq!(
field_ident("self"),
("self_".to_string(), Some("self".to_string()))
);
assert_eq!(field_ident("name"), ("name".to_string(), None));
assert_eq!(
field_ident("nodeName"),
("node_name".to_string(), Some("nodeName".to_string()))
);
}
#[test]
fn field_override_emits_curated_enum_not_string() {
let mut refs = BTreeSet::new();
let f = emit_fields(
"io.k8s.api.core.v1.Secret",
&view(json!({"type": {"type": "string"}}), &[]).properties,
&[],
&mut refs,
);
assert!(f.contains("pub r#type: Option<crate::curated_enums::SecretType>"));
assert!(f.contains("rename = \"type\""));
assert!(refs.is_empty());
let mut refs2 = BTreeSet::new();
let g = emit_fields(
"io.k8s.api.core.v1.NotSecret",
&view(json!({"type": {"type": "string"}}), &[]).properties,
&[],
&mut refs2,
);
assert!(g.contains("pub r#type: Option<String>"));
}
#[test]
fn keyword_field_emitted_as_raw_ident() {
let mut refs = BTreeSet::new();
let f = emit_fields(
"",
&view(json!({"type": {"type": "string"}}), &[]).properties,
&[],
&mut refs,
);
assert!(f.contains("rename = \"type\""));
assert!(f.contains("pub r#type: Option<String>"));
}
#[test]
fn envelope_and_metadata_fields_special_cased() {
let mut refs = BTreeSet::new();
let f = emit_fields(
"",
&view(
json!({
"apiVersion": {"type": "string"},
"kind": {"type": "string"},
"metadata": {"allOf": [{"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta"}]}
}),
&[],
)
.properties,
&[],
&mut refs,
);
assert!(!f.contains("pub api_version")); assert!(!f.contains("pub kind")); assert!(f.contains("pub metadata: crate::meta::ObjectMeta"));
}
#[test]
fn serviceaccount_shape_types_correctly() {
let mut refs = BTreeSet::new();
let f = emit_fields(
"",
&view(
json!({
"automountServiceAccountToken": {"type": "boolean"},
"imagePullSecrets": {"type": "array", "items": {"$ref": "#/components/schemas/io.k8s.api.core.v1.LocalObjectReference"}},
"secrets": {"type": "array", "items": {"$ref": "#/components/schemas/io.k8s.api.core.v1.ObjectReference"}}
}),
&[],
)
.properties,
&[],
&mut refs,
);
assert!(f.contains("rename = \"automountServiceAccountToken\""));
assert!(f.contains("pub automount_service_account_token: Option<bool>"));
assert!(f.contains("pub image_pull_secrets: Vec<LocalObjectReference>"));
assert!(f.contains("skip_serializing_if = \"Vec::is_empty\""));
assert!(f.contains("pub secrets: Vec<ObjectReference>"));
assert!(refs.contains("io.k8s.api.core.v1.LocalObjectReference"));
assert!(refs.contains("io.k8s.api.core.v1.ObjectReference"));
}
#[test]
fn required_field_is_bare_not_option() {
let mut refs = BTreeSet::new();
let f = emit_fields(
"",
&view(
json!({"replicas": {"type": "integer", "format": "int32"}}),
&["replicas"],
)
.properties,
&["replicas".to_string()],
&mut refs,
);
assert!(f.contains("pub replicas: i32"));
assert!(!f.contains("Option<i32>"));
}
#[test]
fn emit_struct_wraps_fields_in_decl() {
let (src, refs) = emit_struct(
"LocalObjectReference",
"io.k8s.api.core.v1.LocalObjectReference",
&view(json!({"name": {"type": "string"}}), &[]),
);
assert!(src.contains("pub struct LocalObjectReference {"));
assert!(src.contains("pub name: Option<String>"));
assert!(
src.contains("#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]")
);
assert!(refs.is_empty());
}
#[test]
fn transitive_closure_walks_refs_skips_provided_and_missing() {
let mut schemas = BTreeMap::new();
schemas.insert(
"io.k8s.api.core.v1.A".to_string(),
view(
json!({
"b": {"$ref": "#/components/schemas/io.k8s.api.core.v1.B"},
"meta": {"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta"},
"z": {"$ref": "#/components/schemas/io.k8s.api.core.v1.Z"}
}),
&[],
),
);
schemas.insert(
"io.k8s.api.core.v1.B".to_string(),
view(json!({"name": {"type": "string"}}), &[]),
);
let mut seeds = BTreeSet::new();
seeds.insert("io.k8s.api.core.v1.A".to_string());
let structs = transitive_structs(&seeds, &schemas);
let names: Vec<&str> = structs.iter().map(|(n, _, _)| n.as_str()).collect();
assert!(names.contains(&"A"));
assert!(names.contains(&"B")); assert!(!names.contains(&"ObjectMeta")); assert!(!names.contains(&"Z")); }
}