use std::collections::BTreeMap;
use crate::catalog::{KindEntry, Subresource};
use crate::emit_typed::{SchemaView, emit_fields, emit_struct};
use crate::openapi::KindShape;
const HEADER: &str = "\
//! GENERATED — DO NOT EDIT by hand. Source: engenho-kube-codegen.
//!
//! Regenerate via `cargo run -p engenho-kube-codegen -- \\
//! --schema engenho-types/vendor/openapi/v1.34.0 \\
//! --output engenho-types/src/generated_v1_34`.
//!
//! Edit src/catalog.rs to add or remove kinds.
#![allow(clippy::module_name_repetitions)]
use std::borrow::Cow;
use serde::{Deserialize, Serialize};
use crate::kind::{GroupVersionKind, GroupVersionResource, KubeResource, Scope};
use crate::meta::ObjectMeta;
";
#[must_use]
pub fn emit_kind(entry: &KindEntry, shape: &KindShape) -> String {
let scope = if entry.cluster_scoped {
"Scope::Cluster"
} else {
"Scope::Namespaced"
};
let api_version = if entry.group.is_empty() {
entry.version.to_string()
} else {
format!("{}/{}", entry.group, entry.version)
};
let doc = if shape.description.is_empty() {
format!(
"/// `{}/{}` typed kind — generated by engenho-kube-codegen.",
api_version, entry.kind
)
} else {
let first_para = shape
.description
.split("\n\n")
.next()
.unwrap_or(&shape.description);
first_para
.lines()
.map(|l| {
let trimmed = l.trim_start();
if trimmed.is_empty() {
"///".to_string()
} else {
format!("/// {trimmed}")
}
})
.collect::<Vec<_>>()
.join("\n")
};
format!(
"{HEADER}\n\
{doc}\n\
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]\n\
pub struct {kind} {{\n\
/// Standard object metadata.\n\
#[serde(default, skip_serializing_if = \"is_empty_meta\")]\n\
pub metadata: ObjectMeta,\n\
/// Spec (typed expansion is M0.0.4; today opaque JSON).\n\
#[serde(default, skip_serializing_if = \"serde_json::Value::is_null\")]\n\
pub spec: serde_json::Value,\n\
/// Status (typed expansion is M0.0.4; today opaque JSON).\n\
#[serde(default, skip_serializing_if = \"Option::is_none\")]\n\
pub status: Option<serde_json::Value>,\n\
}}\n\
\n\
impl KubeResource for {kind} {{\n\
const GVK: GroupVersionKind = GroupVersionKind {{\n\
group: {group:?},\n\
version: {version:?},\n\
kind: {kind:?},\n\
}};\n\
const GVR: GroupVersionResource = GroupVersionResource {{\n\
group: {group:?},\n\
version: {version:?},\n\
resource: {resource:?},\n\
}};\n\
const SCOPE: Scope = {scope};\n\
\n\
fn name(&self) -> Cow<'_, str> {{\n\
Cow::Borrowed(self.metadata.name.as_str())\n\
}}\n\
fn namespace(&self) -> Option<Cow<'_, str>> {{\n\
self.metadata.namespace.as_deref().map(Cow::Borrowed)\n\
}}\n\
fn resource_version(&self) -> Option<Cow<'_, str>> {{\n\
if self.metadata.resource_version.is_empty() {{\n\
None\n\
}} else {{\n\
Some(Cow::Borrowed(self.metadata.resource_version.as_str()))\n\
}}\n\
}}\n\
}}\n\
\n\
fn is_empty_meta(m: &ObjectMeta) -> bool {{ m == &ObjectMeta::default() }}\n\
",
kind = entry.kind,
group = entry.group,
version = entry.version,
resource = entry.resource,
)
}
fn kind_doc(description: &str, api_version: &str, kind: &str) -> String {
if description.is_empty() {
return format!(
"/// `{api_version}/{kind}` typed kind — generated by engenho-kube-codegen."
);
}
let first = description.split("\n\n").next().unwrap_or(description);
first
.lines()
.map(|l| {
let t = l.trim_start();
if t.is_empty() {
"///".to_string()
} else {
format!("/// {t}")
}
})
.collect::<Vec<_>>()
.join("\n")
}
#[must_use]
pub fn emit_kind_typed(
entry: &KindEntry,
kind_view: &SchemaView,
schemas: &BTreeMap<String, SchemaView>,
) -> String {
let scope = if entry.cluster_scoped {
"Scope::Cluster"
} else {
"Scope::Namespaced"
};
let api_version = if entry.group.is_empty() {
entry.version.to_string()
} else {
format!("{}/{}", entry.group, entry.version)
};
let doc = kind_doc(&kind_view.description, &api_version, entry.kind);
let _ = schemas;
let mut refs = std::collections::BTreeSet::new();
let fields = emit_fields(
entry.openapi_key,
&kind_view.properties,
&kind_view.required,
&mut refs,
);
let shared_import = if refs.is_empty() {
String::new()
} else {
"use crate::generated_v1_34::types::*;\n".to_string()
};
format!(
"{HEADER}{shared_import}\n\
{doc}\n\
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]\n\
pub struct {kind} {{\n\
{fields}}}\n\
\n\
impl KubeResource for {kind} {{\n\
const GVK: GroupVersionKind = GroupVersionKind {{\n\
group: {group:?},\n\
version: {version:?},\n\
kind: {kind:?},\n\
}};\n\
const GVR: GroupVersionResource = GroupVersionResource {{\n\
group: {group:?},\n\
version: {version:?},\n\
resource: {resource:?},\n\
}};\n\
const SCOPE: Scope = {scope};\n\
\n\
fn name(&self) -> Cow<'_, str> {{\n\
Cow::Borrowed(self.metadata.name.as_str())\n\
}}\n\
fn namespace(&self) -> Option<Cow<'_, str>> {{\n\
self.metadata.namespace.as_deref().map(Cow::Borrowed)\n\
}}\n\
fn resource_version(&self) -> Option<Cow<'_, str>> {{\n\
if self.metadata.resource_version.is_empty() {{\n\
None\n\
}} else {{\n\
Some(Cow::Borrowed(self.metadata.resource_version.as_str()))\n\
}}\n\
}}\n\
}}\n\
\n\
fn is_empty_meta(m: &ObjectMeta) -> bool {{ m == &ObjectMeta::default() }}\n",
kind = entry.kind,
group = entry.group,
version = entry.version,
resource = entry.resource,
)
}
const SHARED_HEADER: &str = "\
//! GENERATED — DO NOT EDIT by hand. Source: engenho-kube-codegen.
//!
//! Shared sub-structs referenced by the generated kinds — emitted once,
//! globally deduplicated, so every kind references one canonical type.
#![allow(clippy::module_name_repetitions)]
use serde::{Deserialize, Serialize};
";
#[must_use]
pub fn emit_shared_module(
shared: &[(String, String, SchemaView)],
catalog: &[KindEntry],
) -> String {
let mut out = String::from(SHARED_HEADER);
let mut referenced_keys = std::collections::BTreeSet::new();
for (_, key, view) in shared {
let mut r = std::collections::BTreeSet::new();
let _ = emit_fields(key, &view.properties, &view.required, &mut r);
referenced_keys.extend(r);
}
for e in catalog {
if referenced_keys.contains(e.openapi_key) {
out.push_str(&format!(
"use crate::generated_v1_34::{}::{};\n",
e.module, e.kind
));
}
}
for (name, key, view) in shared {
let (src, _) = emit_struct(name, key, view);
out.push('\n');
out.push_str(&src);
}
if out.contains("\"is_empty_meta\"") {
out.push_str(
"\nfn is_empty_meta(m: &crate::meta::ObjectMeta) -> bool { m == &crate::meta::ObjectMeta::default() }\n",
);
}
out
}
const CATALOG_HEADER: &str = "\
//! GENERATED — DO NOT EDIT by hand. Source: engenho-kube-codegen.
//!
//! Runtime-iterable resource catalog — one [`ResourceDescriptor`] per
//! generated kind. The apiserver folds [`RESOURCE_CATALOG`] to build
//! handlers, register routes, and serve discovery; the curated plural
//! (`KindEntry.resource`) flows verbatim into every consumer so there is
//! ONE source of truth for pluralization (no `+s` derivation).
//!
//! Regenerate via `cargo run -p engenho-kube-codegen -- \\
//! --schema engenho-types/vendor/openapi/v1.34.0 \\
//! --output engenho-types/src/generated_v1_34`.
//!
//! Edit src/catalog.rs to add or remove kinds.
use crate::kind::{GroupVersionKind, GroupVersionResource, Scope};
";
const CATALOG_TYPE_DECL: &str = "\
/// A K8s subresource a kind serves under `<plural>/<name>/<sub>`.
///
/// Typed — NOT a string — so a bad combination is unrepresentable: the
/// discovery emitter, the router dispatch, and the store-scoping handler all
/// `match` on this enum, and the compiler refuses any value outside the
/// closed set. `Status` is the `/status` subresource (controller-written
/// status, isolated from spec on write); `Scale` is the autoscaling/v1
/// `/scale` subresource (the projected replica view).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Subresource {
/// `/status` — get/patch/update the `.status` only (spec untouched).
Status,
/// `/scale` — get/patch/update the autoscaling/v1 Scale projection
/// (`spec.replicas` only).
Scale,
/// `/log` — GET a Pod container's stdout/stderr (`kubectl logs`). Read-only
/// (GET only). Pod-only; the router dispatches it to the kubelet
/// (single-node: in-process) which reads `backend.logs`.
Log,
/// `/token` — POST a `TokenRequest`, receive a signed ServiceAccount JWT
/// (`kubectl create token`, and every in-cluster client's identity).
///
/// The ONLY create-shaped subresource: status/scale/log are read or
/// update shapes, so the router's blanket \"POST on a subresource is not
/// a CREATE\" rule has exactly this exception. It is also the only one
/// whose response body is not the stored object — nothing is persisted,
/// the minted token is returned in `.status.token` and never stored.
Token,
}
/// One runtime row describing a routable/discoverable Kubernetes kind.
///
/// `plural` is the curated URL segment (`KindEntry.resource`) — irregular
/// plurals (e.g. `Endpoints` → `endpoints`) are correct by construction.
/// `api_version` is `\"v1\"` for the core group, `\"<group>/<version>\"`
/// otherwise — precomputed so consumers never re-derive it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ResourceDescriptor {
/// API group (`\"\"` for core/v1).
pub group: &'static str,
/// API version (`\"v1\"`, …).
pub version: &'static str,
/// Kind (`\"Pod\"`, `\"Deployment\"`, …).
pub kind: &'static str,
/// Plural URL segment (`\"pods\"`, `\"endpoints\"`, …) — curated, never `+s`.
pub plural: &'static str,
/// `true` ⇒ namespaced; `false` ⇒ cluster-scoped.
pub namespaced: bool,
/// `\"v1\"` for core, `\"<group>/<version>\"` otherwise.
pub api_version: &'static str,
/// kubectl short-name aliases (e.g. `[\"deploy\"]`). Empty for kinds
/// with no upstream short name. Pure registration metadata (NOT in the
/// OpenAPI schema) — flows into discovery `shortNames`.
pub short_names: &'static [&'static str],
/// Singular resource name (lowercase kind) — served as discovery
/// `singularName`.
pub singular: &'static str,
/// kubectl resource categories (e.g. `[\"all\"]`). Empty for kinds in
/// no category. Flows into discovery `categories`.
pub categories: &'static [&'static str],
/// `true` ⇒ this kind has NO vendored OpenAPI v3 schema document and NO
/// typed struct — it is served as opaque JSON via the generic
/// `StoreBackedHandler` (e.g.
/// `apiextensions.k8s.io/v1.CustomResourceDefinition`, stored as plain
/// JSON). Such kinds are routable + discoverable but absent from the
/// `/openapi/v3` served set, so the ★★ CATALOG-REFLECTION invariant
/// (`SERVED (group,version) == non-opaque RESOURCE_CATALOG (group,version)`)
/// excludes them. `kubectl apply` of an opaque kind needs
/// `--validate=false` (no schema to validate against); `kubectl explain`
/// is unavailable. Non-opaque kinds are `false`.
pub opaque: bool,
/// The subresources this kind serves under `<plural>/<name>/<sub>`
/// (`/status`, `/scale`). Typed slice — the SINGLE source the router
/// dispatch, the store-scoping handler, and discovery all read; no kind
/// is ever special-cased by name. `&[]` for kinds with no subresource.
pub subresources: &'static [Subresource],
}
impl ResourceDescriptor {
/// `true` iff this kind serves the `/status` subresource.
#[must_use]
pub fn has_status(&self) -> bool {
self.subresources.contains(&Subresource::Status)
}
/// `true` iff this kind serves the autoscaling/v1 `/scale` subresource.
#[must_use]
pub fn has_scale(&self) -> bool {
self.subresources.contains(&Subresource::Scale)
}
/// `true` iff this kind serves the `/log` subresource (Pod only).
#[must_use]
pub fn has_log(&self) -> bool {
self.subresources.contains(&Subresource::Log)
}
/// The Group/Version/Kind triple for this descriptor.
#[must_use]
pub const fn to_gvk(&self) -> GroupVersionKind {
GroupVersionKind {
group: self.group,
version: self.version,
kind: self.kind,
}
}
/// The Group/Version/Resource triple for this descriptor.
#[must_use]
pub const fn to_gvr(&self) -> GroupVersionResource {
GroupVersionResource {
group: self.group,
version: self.version,
resource: self.plural,
}
}
/// The runtime [`Scope`] for this descriptor.
#[must_use]
pub const fn scope(&self) -> Scope {
if self.namespaced {
Scope::Namespaced
} else {
Scope::Cluster
}
}
}
";
#[must_use]
pub fn emit_catalog(catalog: &[KindEntry]) -> String {
let mut out = String::from(CATALOG_HEADER);
out.push('\n');
out.push_str(CATALOG_TYPE_DECL);
out.push('\n');
out.push_str(
"/// Every routable/discoverable kind, in `KIND_CATALOG` order.\n\
pub const RESOURCE_CATALOG: &[ResourceDescriptor] = &[\n",
);
for e in catalog {
let api_version = if e.group.is_empty() {
e.version.to_string()
} else {
format!("{}/{}", e.group, e.version)
};
out.push_str(&format!(
" ResourceDescriptor {{ group: {:?}, version: {:?}, kind: {:?}, plural: {:?}, namespaced: {}, api_version: {:?}, short_names: {}, singular: {:?}, categories: {}, opaque: {}, subresources: {} }},\n",
e.group,
e.version,
e.kind,
e.resource,
!e.cluster_scoped,
api_version,
render_str_slice(e.short_names),
e.singular,
render_str_slice(e.categories),
e.opaque,
render_subresources(e.subresources),
));
}
out.push_str("];\n");
out
}
fn render_str_slice(items: &[&str]) -> String {
if items.is_empty() {
return "&[]".to_string();
}
let joined = items
.iter()
.map(|s| format!("{s:?}"))
.collect::<Vec<_>>()
.join(", ");
format!("&[{joined}]")
}
fn render_subresources(items: &[Subresource]) -> String {
if items.is_empty() {
return "&[]".to_string();
}
let joined = items
.iter()
.map(|s| match s {
Subresource::Status => "Subresource::Status",
Subresource::Scale => "Subresource::Scale",
Subresource::Log => "Subresource::Log",
Subresource::Token => "Subresource::Token",
})
.collect::<Vec<_>>()
.join(", ");
format!("&[{joined}]")
}
#[must_use]
pub fn emit_module(module_name: &str, entries: &[&KindEntry]) -> String {
let mut out =
format!("//! GENERATED — `{module_name}` typed kinds. Source: engenho-kube-codegen.\n\n");
for e in entries {
out.push_str(&format!("mod {};\n", e.kind.to_lowercase()));
}
out.push('\n');
for e in entries {
out.push_str(&format!("pub use {}::{};\n", e.kind.to_lowercase(), e.kind));
}
out.push_str("\npub use crate::generated_v1_34::types::*;\n");
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::openapi::{KindShape, XGvk};
use std::collections::BTreeMap;
fn entry() -> KindEntry {
KindEntry {
kind: "Pod",
openapi_key: "io.k8s.api.core.v1.Pod",
group: "",
version: "v1",
resource: "pods",
cluster_scoped: false,
module: "core_v1",
short_names: &["po"],
singular: "pod",
categories: &["all"],
opaque: false,
subresources: &[Subresource::Status],
}
}
fn shape() -> KindShape {
KindShape {
gvks: vec![XGvk {
group: "".into(),
version: "v1".into(),
kind: "Pod".into(),
}],
description: "Pod is a collection of containers that can run on a host.".into(),
properties: BTreeMap::new(),
required: vec![],
}
}
#[test]
fn emit_kind_contains_struct_decl() {
let s = emit_kind(&entry(), &shape());
assert!(s.contains("pub struct Pod"));
assert!(s.contains("impl KubeResource for Pod"));
}
#[test]
fn emit_kind_namespaced_scope() {
let s = emit_kind(&entry(), &shape());
assert!(s.contains("Scope::Namespaced"));
}
#[test]
fn emit_kind_cluster_scoped_when_flag_set() {
let mut e = entry();
e.cluster_scoped = true;
e.kind = "Namespace";
e.resource = "namespaces";
let s = emit_kind(&e, &shape());
assert!(s.contains("Scope::Cluster"));
assert!(s.contains("pub struct Namespace"));
}
#[test]
fn emit_kind_resource_in_gvr() {
let s = emit_kind(&entry(), &shape());
assert!(s.contains(r#"resource: "pods""#));
}
#[test]
fn emit_kind_doc_from_openapi_description() {
let s = emit_kind(&entry(), &shape());
assert!(s.contains("Pod is a collection of containers"));
}
#[test]
fn emit_kind_is_deterministic() {
let s1 = emit_kind(&entry(), &shape());
let s2 = emit_kind(&entry(), &shape());
assert_eq!(s1, s2);
}
#[test]
fn emit_catalog_has_one_row_per_entry() {
use crate::catalog::KIND_CATALOG;
let src = emit_catalog(KIND_CATALOG);
let rows = src.matches(" ResourceDescriptor { group:").count();
assert_eq!(
rows,
KIND_CATALOG.len(),
"one RESOURCE_CATALOG row per KIND_CATALOG entry"
);
}
#[test]
fn emit_catalog_uses_curated_plural_not_plus_s() {
use crate::catalog::KIND_CATALOG;
let src = emit_catalog(KIND_CATALOG);
assert!(
src.contains(r#"kind: "Endpoints", plural: "endpoints""#),
"Endpoints row carries the curated plural"
);
assert!(
!src.contains("endpointss"),
"no naive +s pluralization survives in the catalog"
);
}
#[test]
fn emit_catalog_api_version_core_vs_grouped() {
use crate::catalog::KIND_CATALOG;
let src = emit_catalog(KIND_CATALOG);
assert!(
src.contains(r#"kind: "Pod", plural: "pods", namespaced: true, api_version: "v1""#)
);
assert!(src.contains(
r#"kind: "Deployment", plural: "deployments", namespaced: true, api_version: "apps/v1""#
));
}
#[test]
fn emit_catalog_namespaced_flag_matches_scope() {
use crate::catalog::KIND_CATALOG;
let src = emit_catalog(KIND_CATALOG);
assert!(
src.contains(r#"kind: "Namespace", plural: "namespaces", namespaced: false"#),
"cluster-scoped Namespace → namespaced: false"
);
}
#[test]
fn emit_catalog_is_deterministic() {
use crate::catalog::KIND_CATALOG;
assert_eq!(emit_catalog(KIND_CATALOG), emit_catalog(KIND_CATALOG));
}
#[test]
fn opaque_crd_kind_is_catalog_only_no_module_struct() {
use crate::catalog::KIND_CATALOG;
let crd = KIND_CATALOG
.iter()
.find(|e| e.kind == "CustomResourceDefinition")
.expect("CustomResourceDefinition cataloged");
assert!(crd.opaque, "CRD kind is opaque (no typed struct)");
assert!(crd.module.is_empty(), "opaque CRD has no module");
assert!(crd.openapi_key.is_empty(), "opaque CRD has no openapi_key");
assert_eq!(crd.group, "apiextensions.k8s.io");
assert_eq!(crd.resource, "customresourcedefinitions");
assert!(crd.cluster_scoped, "CRDs are cluster-scoped");
let src = emit_catalog(KIND_CATALOG);
assert!(
src.contains(
r#"kind: "CustomResourceDefinition", plural: "customresourcedefinitions""#
),
"opaque CRD still gets a RESOURCE_CATALOG row"
);
}
#[test]
fn every_singular_is_lowercase_kind() {
use crate::catalog::KIND_CATALOG;
for e in KIND_CATALOG {
assert_eq!(
e.singular,
e.kind.to_lowercase(),
"{}: singular must be the lowercased kind",
e.kind
);
}
}
#[test]
fn emit_catalog_renders_short_names_singular_categories() {
use crate::catalog::KIND_CATALOG;
let src = emit_catalog(KIND_CATALOG);
assert!(
src.contains(
r#"kind: "Deployment", plural: "deployments", namespaced: true, api_version: "apps/v1", short_names: &["deploy"], singular: "deployment", categories: &["all"]"#
),
"Deployment row carries deploy/deployment/all"
);
assert!(
src.contains(
r#"kind: "Secret", plural: "secrets", namespaced: true, api_version: "v1", short_names: &[], singular: "secret", categories: &[]"#
),
"Secret row carries an empty short_names + categories slice"
);
assert!(
src.contains(r#"short_names: &["po"], singular: "pod", categories: &["all"]"#),
"Pod row carries po/pod/all"
);
}
#[test]
fn render_str_slice_empty_and_nonempty() {
assert_eq!(render_str_slice(&[]), "&[]");
assert_eq!(render_str_slice(&["deploy"]), r#"&["deploy"]"#);
assert_eq!(render_str_slice(&["a", "b"]), r#"&["a", "b"]"#);
}
#[test]
fn render_subresources_empty_status_and_both() {
assert_eq!(render_subresources(&[]), "&[]");
assert_eq!(
render_subresources(&[Subresource::Status]),
"&[Subresource::Status]"
);
assert_eq!(
render_subresources(&[Subresource::Status, Subresource::Scale]),
"&[Subresource::Status, Subresource::Scale]"
);
}
#[test]
fn emit_catalog_renders_subresource_slices() {
use crate::catalog::KIND_CATALOG;
let src = emit_catalog(KIND_CATALOG);
assert!(
src.contains(r#"kind: "Deployment""#)
&& src.contains("subresources: &[Subresource::Status, Subresource::Scale]"),
"Deployment row carries Status + Scale"
);
assert!(
src.contains(
r#"kind: "DaemonSet", plural: "daemonsets", namespaced: true, api_version: "apps/v1", short_names: &["ds"], singular: "daemonset", categories: &["all"], opaque: false, subresources: &[Subresource::Status]"#
),
"DaemonSet row carries Status only"
);
assert!(
src.contains(
r#"kind: "ConfigMap", plural: "configmaps", namespaced: true, api_version: "v1", short_names: &["cm"], singular: "configmap", categories: &[], opaque: false, subresources: &[]"#
),
"ConfigMap row carries an empty subresources slice"
);
assert!(
src.contains("pub enum Subresource"),
"the generated catalog emits the Subresource enum decl"
);
}
#[test]
fn emit_module_lists_each_kind() {
let entries: Vec<KindEntry> = vec![
entry(),
KindEntry {
kind: "Service",
openapi_key: "io.k8s.api.core.v1.Service",
group: "",
version: "v1",
resource: "services",
cluster_scoped: false,
module: "core_v1",
short_names: &["svc"],
singular: "service",
categories: &["all"],
opaque: false,
subresources: &[Subresource::Status],
},
];
let refs: Vec<&KindEntry> = entries.iter().collect();
let m = emit_module("core_v1", &refs);
assert!(m.contains("mod pod;"));
assert!(m.contains("mod service;"));
assert!(m.contains("pub use pod::Pod;"));
assert!(m.contains("pub use service::Service;"));
}
}