Skip to main content

k8s_openapi_codegen_common/
lib.rs

1#![warn(rust_2018_idioms)]
2
3//! This crate contains common code for the [`k8s-openapi` code generator](https://github.com/Arnavion/k8s-openapi/tree/master/k8s-openapi-codegen)
4//! and the [`k8s-openapi-derive`](https://crates.io/crates/k8s-openapi-derive) custom derive crate.
5//!
6//! It can be used by code generators that want to generate crates like `k8s-openapi` and `k8s-openapi-derive` for Kubernetes-like software
7//! such as OpenShift.
8//!
9//! 1. Create a [`swagger20::Spec`] value, either by deserializing it from an OpenAPI spec JSON file or by creating it manually.
10//! 1. Invoke the [`run`] function for each definition in the spec.
11
12pub mod swagger20;
13
14mod templates;
15
16/// Statistics from a successful invocation of [`run`]
17#[derive(Clone, Copy, Debug)]
18pub struct RunResult {
19    pub num_generated_structs: usize,
20    pub num_generated_type_aliases: usize,
21}
22
23/// Error type reported by [`run`]
24#[derive(Debug)]
25pub struct Error(Box<dyn std::error::Error + Send + Sync>);
26
27impl std::fmt::Display for Error {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        self.0.fmt(f)
30    }
31}
32
33impl std::error::Error for Error {
34    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
35        self.0.source()
36    }
37}
38
39macro_rules! impl_from_for_error {
40    ($($ty:ty ,)*) => {
41        $(
42            impl From<$ty> for Error {
43                fn from(err: $ty) -> Self {
44                    Error(err.into())
45                }
46            }
47        )*
48    };
49}
50
51impl_from_for_error! {
52    &'_ str,
53    String,
54    std::fmt::Error,
55    std::io::Error,
56}
57
58/// A mechanism for converting (the components of) an openapi path to (the components of) a Rust namespace.
59///
60/// The k8s-openapi code generator uses this trait to emit the paths of all types relative to the `k8s_openapi` crate.
61/// For example, it maps the components of the openapi path `io.k8s.api.core.v1` to
62/// the components of the Rust namespace `crate::core::v1`. The `io.k8s.` prefix is stripped and the path starts with `crate::`.
63///
64/// Other code generators can have more complicated implementations. For example, an OpenShift code generator that has its own types but also wants to
65/// reuse types from the k8s-openapi crate would map `com.github.openshift.` to `crate::` and `io.k8s.` to `k8s_openapi::` instead.
66///
67/// The implementation should return `None` for paths that it does not recognize.
68pub trait MapNamespace {
69    fn map_namespace<'a>(&self, path_parts: &[&'a str]) -> Option<Vec<&'a str>>;
70}
71
72/// Used to create an impl of `std::io::Write` for each type that the type's generated code will be written to.
73pub trait RunState {
74    /// The impl of `std::io::Write` for each type that the type's generated code will be written to.
75    type Writer: std::io::Write;
76
77    /// Returns an impl of `std::io::Write` for each type that the type's generated code will be written to.
78    ///
79    /// # Parameters
80    ///
81    /// - `parts`: A list of strings making up the components of the path of the generated type. Code generators that are emitting crates
82    ///   can use this parameter to make module subdirectories for each component, and to emit `use` statements in the final module's `mod.rs`.
83    fn make_writer(&mut self, parts: &[&str]) -> std::io::Result<Self::Writer>;
84
85    /// This function is invoked when `k8s_openapi_codegen_common::run` is done with the writer and completes successfully.
86    /// The implementation can do any cleanup that it wants here.
87    fn finish(&mut self, writer: Self::Writer);
88}
89
90impl<T> RunState for &'_ mut T where T: RunState {
91    type Writer = <T as RunState>::Writer;
92
93    fn make_writer(&mut self, parts: &[&str]) -> std::io::Result<Self::Writer> {
94        (*self).make_writer(parts)
95    }
96
97    fn finish(&mut self, writer: Self::Writer) {
98        (*self).finish(writer);
99    }
100}
101
102/// Whether [`run`] should generate an impl of `schemars::JsonSchema` for the type or not.
103#[derive(Clone, Copy, Debug)]
104pub enum GenerateSchema<'a> {
105    Yes {
106        /// An optional feature that the impl of `schemars::JsonSchema` will be `cfg`-gated by.
107        feature: Option<&'a str>,
108    },
109
110    No,
111}
112
113/// Each invocation of this function generates a single type specified by the `definition_path` parameter.
114///
115/// # Parameters
116///
117/// - `definitions`: The definitions parsed from the OpenAPI spec that should be emitted as model types.
118///
119/// - `operations`: The list of operations parsed from the OpenAPI spec. The list is mutated to remove the operations
120///   that are determined to be associated with the type currently being generated.
121///
122/// - `definition_path`: The specific definition path out of the `definitions` collection that should be emitted.
123///
124/// - `map_namespace`: An instance of the [`MapNamespace`] trait that controls how OpenAPI namespaces of the definitions are mapped to rust namespaces.
125///
126/// - `vis`: The visibility modifier that should be emitted on the generated code.
127///
128/// - `state`: See the documentation of the [`RunState`] trait.
129pub fn run(
130    definitions: &std::collections::BTreeMap<swagger20::DefinitionPath, swagger20::Schema>,
131    operations: &mut Vec<swagger20::Operation>,
132    definition_path: &swagger20::DefinitionPath,
133    map_namespace: &impl MapNamespace,
134    vis: &str,
135    generate_schema: GenerateSchema<'_>,
136    mut state: impl RunState,
137) -> Result<RunResult, Error> {
138    let definition = definitions.get(definition_path).ok_or_else(|| format!("definition for {definition_path} does not exist in spec"))?;
139
140    let local = map_namespace_local_to_string(map_namespace)?;
141
142    let mut run_result = RunResult {
143        num_generated_structs: 0,
144        num_generated_type_aliases: 0,
145    };
146
147    let path_parts: Vec<_> = definition_path.split('.').collect();
148    let namespace_parts: Vec<_> =
149        map_namespace.map_namespace(&path_parts).ok_or_else(|| format!("unexpected path {definition_path:?}"))?
150        .into_iter()
151        .collect();
152
153    let mut out = state.make_writer(&namespace_parts)?;
154
155    let type_name = path_parts.last().ok_or_else(|| format!("path for {definition_path} has no parts"))?;
156
157    let derives = get_derives(&definition.kind, definitions, map_namespace)?;
158
159    templates::type_header::generate(
160        &mut out,
161        definition_path,
162        definition.description.as_deref(),
163        derives,
164        vis,
165    )?;
166
167    match &definition.kind {
168        swagger20::SchemaKind::Properties(properties) => {
169            let (template_properties, resource_metadata, metadata_ty) = {
170                let mut result = Vec::with_capacity(properties.len());
171
172                let mut single_group_version_kind = match &definition.kubernetes_group_kind_versions[..] {
173                    [group_version_kind] => Some((group_version_kind, false, false)),
174                    _ => None,
175                };
176
177                let mut metadata_ty = None;
178
179                for (name, (schema, required)) in properties {
180                    if name.0 == "apiVersion" {
181                        if let Some((_, has_api_version, _)) = &mut single_group_version_kind {
182                            *has_api_version = true;
183                            continue;
184                        }
185                    }
186
187                    if name.0 == "kind" {
188                        if let Some((_, _, has_kind)) = &mut single_group_version_kind {
189                            *has_kind = true;
190                            continue;
191                        }
192                    }
193
194                    let field_name = get_rust_ident(name);
195
196                    let mut field_type_name = String::new();
197
198                    let required = match required {
199                        true => templates::PropertyRequired::Required {
200                            is_default: is_default(&schema.kind, definitions, map_namespace)?,
201                        },
202                        false => templates::PropertyRequired::Optional,
203                    };
204
205                    if let templates::PropertyRequired::Optional = required {
206                        field_type_name.push_str("Option<");
207                    }
208
209                    let type_name = get_rust_type(&schema.kind, map_namespace)?;
210
211                    if name.0 == "metadata" {
212                        metadata_ty = Some((type_name.clone(), required));
213                    }
214
215                    // Fix cases of infinite recursion
216                    if let swagger20::SchemaKind::Ref(swagger20::RefPath { path, .. }) = &schema.kind {
217                        match (&**definition_path, &**name, &**path) {
218                            (
219                                "io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps",
220                                "not",
221                                "io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps",
222                            ) |
223                            (
224                                "io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps",
225                                "not",
226                                "io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps",
227                            ) => {
228                                field_type_name.push_str("std::boxed::Box<");
229                                field_type_name.push_str(&type_name);
230                                field_type_name.push('>');
231                            },
232
233                            _ => field_type_name.push_str(&type_name),
234                        }
235                    }
236                    else {
237                        field_type_name.push_str(&type_name);
238                    }
239
240                    if let templates::PropertyRequired::Optional = required {
241                        field_type_name.push('>');
242                    }
243
244                    let is_flattened = matches!(&schema.kind, swagger20::SchemaKind::Ty(swagger20::Type::CustomResourceSubresources(_)));
245
246                    result.push(templates::Property {
247                        name,
248                        comment: schema.description.as_deref(),
249                        field_name,
250                        field_type_name,
251                        required,
252                        is_flattened,
253                        merge_type: &schema.merge_type,
254                    });
255                }
256
257                let resource_metadata = match single_group_version_kind {
258                    Some((single_group_version_kind, true, true)) =>
259                        Some(if single_group_version_kind.group.is_empty() {
260                            (
261                                format!("{:?}", single_group_version_kind.version),
262                                format!("{:?}", ""),
263                                format!("{:?}", single_group_version_kind.kind),
264                                format!("{:?}", single_group_version_kind.version),
265                                definition.list_kind.as_ref().map(|kind| format!("{kind:?}")),
266                            )
267                        }
268                        else {
269                            (
270                                format!("{:?}", format!("{}/{}", single_group_version_kind.group, single_group_version_kind.version)),
271                                format!("{:?}", single_group_version_kind.group),
272                                format!("{:?}", single_group_version_kind.kind),
273                                format!("{:?}", single_group_version_kind.version),
274                                definition.list_kind.as_ref().map(|kind| format!("{kind:?}")),
275                            )
276                        }),
277                    Some((_, true, false)) => return Err(format!("{definition_path} has an apiVersion property but not a kind property").into()),
278                    Some((_, false, true)) => return Err(format!("{definition_path} has a kind property but not an apiVersion property").into()),
279                    Some((_, false, false)) | None => None,
280                };
281
282                (result, resource_metadata, metadata_ty)
283            };
284
285            templates::r#struct::generate(
286                &mut out,
287                vis,
288                type_name,
289                Default::default(),
290                &template_properties,
291            )?;
292
293            let mut namespace_or_cluster_scoped_url_path_segment_and_scope = vec![];
294            let mut subresource_url_path_segment_and_scope = vec![];
295
296            if !definition.kubernetes_group_kind_versions.is_empty() {
297                let mut kubernetes_group_kind_versions: Vec<_> = definition.kubernetes_group_kind_versions.iter().collect();
298                kubernetes_group_kind_versions.sort();
299
300                let mut operations_by_gkv: std::collections::BTreeMap<_, Vec<_>> = Default::default();
301                for operation in std::mem::take(operations) {
302                    operations_by_gkv
303                        .entry(operation.kubernetes_group_kind_version.clone())
304                        .or_default()
305                        .push(operation);
306                }
307
308                for kubernetes_group_kind_version in kubernetes_group_kind_versions {
309                    if let Some(mut operations) = operations_by_gkv.remove(&Some(kubernetes_group_kind_version.clone())) {
310                        operations.sort_by(|o1, o2| o1.id.cmp(&o2.id));
311
312                        for operation in operations {
313                            // If this is a CRUD operation, use it to determine the resource's URL path segment and scope.
314                            match operation.kubernetes_action {
315                                Some(
316                                    swagger20::KubernetesAction::Delete |
317                                    swagger20::KubernetesAction::Get |
318                                    swagger20::KubernetesAction::Post |
319                                    swagger20::KubernetesAction::Put
320                                ) => (),
321                                _ => continue,
322                            }
323                            let mut components = operation.path.rsplit('/');
324                            let components = (
325                                components.next().expect("str::rsplit returns at least one component"),
326                                components.next(),
327                                components.next(),
328                                components.next(),
329                            );
330
331                            let (url_path_segment_, scope_, url_path_segment_and_scope) = match components {
332                                ("{name}", Some(url_path_segment), Some("{namespace}"), Some("namespaces")) =>
333                                    (
334                                        format!("{url_path_segment:?}"),
335                                        format!("{local}NamespaceResourceScope"),
336                                        &mut namespace_or_cluster_scoped_url_path_segment_and_scope,
337                                    ),
338
339                                ("{name}", Some(url_path_segment), _, _) =>
340                                    (
341                                        format!("{url_path_segment:?}"),
342                                        format!("{local}ClusterResourceScope"),
343                                        &mut namespace_or_cluster_scoped_url_path_segment_and_scope,
344                                    ),
345
346                                (url_path_segment, Some("{name}"), _, _) =>
347                                    (
348                                        format!("{url_path_segment:?}"),
349                                        format!("{local}SubResourceScope"),
350                                        &mut subresource_url_path_segment_and_scope,
351                                    ),
352
353                                (url_path_segment, Some("{namespace}"), Some("namespaces"), _) =>
354                                    (
355                                        format!("{url_path_segment:?}"),
356                                        format!("{local}NamespaceResourceScope"),
357                                        &mut namespace_or_cluster_scoped_url_path_segment_and_scope,
358                                    ),
359
360                                (url_path_segment, _, _, _) =>
361                                    (
362                                        format!("{url_path_segment:?}"),
363                                        format!("{local}ClusterResourceScope"),
364                                        &mut namespace_or_cluster_scoped_url_path_segment_and_scope,
365                                    ),
366                            };
367
368                            url_path_segment_and_scope.push((url_path_segment_, scope_));
369                        }
370                    }
371                }
372
373                *operations = operations_by_gkv.into_values().flatten().collect();
374            }
375
376            match &**definition_path {
377                "io.k8s.apimachinery.pkg.apis.meta.v1.APIGroup" |
378                "io.k8s.apimachinery.pkg.apis.meta.v1.APIGroupList" |
379                "io.k8s.apimachinery.pkg.apis.meta.v1.APIResourceList" |
380                "io.k8s.apimachinery.pkg.apis.meta.v1.APIVersions" =>
381                    namespace_or_cluster_scoped_url_path_segment_and_scope.push((r#""""#.to_owned(), format!("{local}ClusterResourceScope"))),
382                "io.k8s.apimachinery.pkg.apis.meta.v1.Status" =>
383                    subresource_url_path_segment_and_scope.push((r#""status""#.to_owned(), format!("{local}SubResourceScope"))),
384                _ => (),
385            }
386
387            namespace_or_cluster_scoped_url_path_segment_and_scope.dedup();
388            subresource_url_path_segment_and_scope.dedup();
389
390            let template_resource_metadata = match (&resource_metadata, &metadata_ty) {
391                (
392                    Some((api_version, group, kind, version, list_kind)),
393                    Some((metadata_ty, templates::PropertyRequired::Required { is_default: _ })),
394                ) => Some(templates::ResourceMetadata {
395                    api_version,
396                    group,
397                    kind,
398                    version,
399                    list_kind: list_kind.as_deref(),
400                    metadata_ty: Some(metadata_ty),
401                    url_path_segment_and_scope: match (&*namespace_or_cluster_scoped_url_path_segment_and_scope, &*subresource_url_path_segment_and_scope) {
402                        ([(url_path_segment, scope)], _) |
403                        ([], [(url_path_segment, scope)]) => (&**url_path_segment, &**scope),
404
405                        ([], []) => return Err(format!(
406                            "definition {definition_path} is a Resource but its URL path segment and scope could not be inferred").into()),
407                        ([_, ..], _) => return Err(format!(
408                            "definition {definition_path} is a Resource but was inferred to have multiple scopes {namespace_or_cluster_scoped_url_path_segment_and_scope:?}").into()),
409                        ([], [_, ..]) => return Err(format!(
410                            "definition {definition_path} is a Resource but was inferred to have multiple scopes {subresource_url_path_segment_and_scope:?}").into()),
411                    },
412                }),
413
414                (Some(_), Some((_, templates::PropertyRequired::Optional | templates::PropertyRequired::OptionalDefault))) =>
415                    return Err(format!("definition {definition_path} has optional metadata").into()),
416
417                (
418                    Some((api_version, group, kind, version, list_kind)),
419                    None,
420                ) => Some(templates::ResourceMetadata {
421                    api_version,
422                    group,
423                    kind,
424                    version,
425                    list_kind: list_kind.as_deref(),
426                    metadata_ty: None,
427                    url_path_segment_and_scope: match (&*namespace_or_cluster_scoped_url_path_segment_and_scope, &*subresource_url_path_segment_and_scope) {
428                        ([(url_path_segment, scope)], _) |
429                        ([], [(url_path_segment, scope)]) => (&**url_path_segment, &**scope),
430
431                        ([], []) => return Err(format!(
432                            "definition {definition_path} is a Resource but its URL path segment and scope could not be inferred").into()),
433                        ([_, _, ..], _) => return Err(format!(
434                            "definition {definition_path} is a Resource but was inferred to have multiple scopes {namespace_or_cluster_scoped_url_path_segment_and_scope:?}").into()),
435                        ([], [_, _, ..]) => return Err(format!(
436                            "definition {definition_path} is a Resource but was inferred to have multiple scopes {subresource_url_path_segment_and_scope:?}").into()),
437                    },
438                }),
439
440                (None, _) => None,
441            };
442
443            if let Some(template_resource_metadata) = &template_resource_metadata {
444                templates::impl_resource::generate(
445                    &mut out,
446                    type_name,
447                    Default::default(),
448                    map_namespace,
449                    template_resource_metadata,
450                )?;
451
452                templates::impl_listable_resource::generate(
453                    &mut out,
454                    type_name,
455                    Default::default(),
456                    map_namespace,
457                    template_resource_metadata,
458                )?;
459
460                templates::impl_metadata::generate(
461                    &mut out,
462                    type_name,
463                    Default::default(),
464                    map_namespace,
465                    template_resource_metadata,
466                )?;
467            }
468
469            if definition.impl_deep_merge {
470                templates::struct_deep_merge::generate(
471                    &mut out,
472                    type_name,
473                    Default::default(),
474                    &template_properties,
475                    map_namespace,
476                )?;
477            }
478
479            templates::impl_deserialize::generate(
480                &mut out,
481                type_name,
482                Default::default(),
483                &template_properties,
484                map_namespace,
485                template_resource_metadata.as_ref(),
486            )?;
487
488            templates::impl_serialize::generate(
489                &mut out,
490                type_name,
491                Default::default(),
492                &template_properties,
493                map_namespace,
494                template_resource_metadata.as_ref(),
495            )?;
496
497            run_result.num_generated_structs += 1;
498        },
499
500        swagger20::SchemaKind::Ref(_) => return Err(format!("{definition_path} is a Ref").into()),
501
502        swagger20::SchemaKind::Ty(swagger20::Type::IntOrString) => {
503            templates::int_or_string::generate(
504                &mut out,
505                type_name,
506                map_namespace,
507            )?;
508
509            run_result.num_generated_structs += 1;
510        },
511
512        swagger20::SchemaKind::Ty(swagger20::Type::JsonSchemaPropsOr(namespace, json_schema_props_or)) => {
513            let json_schema_props_or = match json_schema_props_or {
514                swagger20::JsonSchemaPropsOr::Array => templates::json_schema_props_or::Or::Array,
515                swagger20::JsonSchemaPropsOr::Bool => templates::json_schema_props_or::Or::Bool,
516                swagger20::JsonSchemaPropsOr::StringArray => templates::json_schema_props_or::Or::StringArray,
517            };
518
519            let json_schema_props_type_name =
520                get_fully_qualified_type_name(
521                    &swagger20::RefPath {
522                        path: format!("io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.{namespace}.JSONSchemaProps"),
523                        can_be_default: None,
524                    },
525                    map_namespace);
526
527            templates::json_schema_props_or::generate(
528                &mut out,
529                type_name,
530                json_schema_props_or,
531                &json_schema_props_type_name,
532                map_namespace,
533            )?;
534
535            run_result.num_generated_structs += 1;
536        },
537
538        swagger20::SchemaKind::Ty(swagger20::Type::Quantity) => {
539            templates::quantity::generate(
540                &mut out,
541                type_name,
542                map_namespace,
543            )?;
544
545            run_result.num_generated_structs += 1;
546        },
547
548        swagger20::SchemaKind::Ty(swagger20::Type::Patch) => {
549            templates::patch::generate(
550                &mut out,
551                type_name,
552                map_namespace,
553            )?;
554
555            run_result.num_generated_structs += 1;
556        },
557
558        swagger20::SchemaKind::Ty(swagger20::Type::WatchEvent(raw_extension_ref_path)) => {
559            let error_status_rust_type = get_rust_type(
560                &swagger20::SchemaKind::Ref(swagger20::RefPath {
561                    path: "io.k8s.apimachinery.pkg.apis.meta.v1.Status".to_owned(),
562                    can_be_default: None,
563                }),
564                map_namespace,
565            )?;
566
567            let error_other_rust_type = get_rust_type(
568                &swagger20::SchemaKind::Ref(raw_extension_ref_path.clone()),
569                map_namespace,
570            )?;
571
572            templates::watch_event::generate(
573                &mut out,
574                type_name,
575                &error_status_rust_type,
576                &error_other_rust_type,
577                map_namespace,
578            )?;
579
580            run_result.num_generated_structs += 1;
581        },
582
583        swagger20::SchemaKind::Ty(swagger20::Type::ListDef { metadata }) => {
584            let metadata_rust_type = get_rust_type(metadata, map_namespace)?;
585
586            let template_generics_where_part = format!("T: {local}ListableResource");
587            let template_generics = templates::Generics {
588                type_part: Some("T"),
589                where_part: Some(&template_generics_where_part),
590            };
591
592            let items_merge_type = swagger20::MergeType::List {
593                strategy: swagger20::KubernetesListType::Map,
594                keys: vec!["metadata().namespace".to_string(), "metadata().name".to_string()],
595                item_merge_type: Box::new(swagger20::MergeType::Default),
596            };
597
598            let template_properties = vec![
599                templates::Property {
600                    name: "items",
601                    comment: Some("List of objects."),
602                    field_name: "items".into(),
603                    field_type_name: "std::vec::Vec<T>".to_owned(),
604                    required: templates::PropertyRequired::Required { is_default: true },
605                    is_flattened: false,
606                    merge_type: &items_merge_type,
607                },
608
609                templates::Property {
610                    name: "metadata",
611                    comment: Some("Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds"),
612                    field_name: "metadata".into(),
613                    field_type_name: (*metadata_rust_type).to_owned(),
614                    required: templates::PropertyRequired::Required { is_default: true },
615                    is_flattened: false,
616                    merge_type: &swagger20::MergeType::Default,
617                },
618            ];
619
620            let template_resource_metadata = templates::ResourceMetadata {
621                api_version: "<T as crate::Resource>::API_VERSION",
622                group: "<T as crate::Resource>::GROUP",
623                kind: "<T as crate::ListableResource>::LIST_KIND",
624                version: "<T as crate::Resource>::VERSION",
625                list_kind: None,
626                metadata_ty: Some(&metadata_rust_type),
627                url_path_segment_and_scope: (r#""""#, "<T as crate::Resource>::Scope"),
628            };
629
630            templates::r#struct::generate(
631                &mut out,
632                vis,
633                type_name,
634                template_generics,
635                &template_properties,
636            )?;
637
638            templates::impl_resource::generate(
639                &mut out,
640                type_name,
641                template_generics,
642                map_namespace,
643                &template_resource_metadata,
644            )?;
645
646            templates::impl_listable_resource::generate(
647                &mut out,
648                type_name,
649                template_generics,
650                map_namespace,
651                &template_resource_metadata,
652            )?;
653
654            templates::impl_metadata::generate(
655                &mut out,
656                type_name,
657                template_generics,
658                map_namespace,
659                &template_resource_metadata,
660            )?;
661
662            if definition.impl_deep_merge {
663                let template_generics_where_part = format!("T: {local}DeepMerge + {local}Metadata<Ty = {local}apimachinery::pkg::apis::meta::v1::ObjectMeta> + {local}ListableResource");
664                let template_generics = templates::Generics {
665                    where_part: Some(&template_generics_where_part),
666                    ..template_generics
667                };
668
669                templates::struct_deep_merge::generate(
670                    &mut out,
671                    type_name,
672                    template_generics,
673                    &template_properties,
674                    map_namespace,
675                )?;
676            }
677
678            {
679                let template_generics_where_part = format!("T: {local}serde::Deserialize<'de> + {local}ListableResource");
680                let template_generics = templates::Generics {
681                    where_part: Some(&template_generics_where_part),
682                    ..template_generics
683                };
684
685                templates::impl_deserialize::generate(
686                    &mut out,
687                    type_name,
688                    template_generics,
689                    &template_properties,
690                    map_namespace,
691                    Some(&template_resource_metadata),
692                )?;
693            }
694
695            {
696                let template_generics_where_part = format!("T: {local}serde::Serialize + {local}ListableResource");
697                let template_generics = templates::Generics {
698                    where_part: Some(&template_generics_where_part),
699                    ..template_generics
700                };
701
702                templates::impl_serialize::generate(
703                    &mut out,
704                    type_name,
705                    template_generics,
706                    &template_properties,
707                    map_namespace,
708                    Some(&template_resource_metadata),
709                )?;
710            }
711
712            run_result.num_generated_structs += 1;
713        },
714
715        swagger20::SchemaKind::Ty(swagger20::Type::ListRef { .. }) => return Err(format!("definition {definition_path} is a ListRef").into()),
716
717        swagger20::SchemaKind::Ty(_) => {
718            let inner_type_name = get_rust_type(&definition.kind, map_namespace)?;
719
720            // Kubernetes requires MicroTime to be serialized with exactly six decimal digits, instead of the default serde serialization of `jiff::Timestamp`
721            // that uses a variable number up to nine.
722            //
723            // Furthermore, while Kubernetes does deserialize a Time from a string with one or more decimal digits,
724            // the format string it uses to *serialize* datetimes does not contain any decimal digits. So match that behavior just to be safe, and to have
725            // the same behavior as the golang client.
726            //
727            // Refs:
728            // - https://github.com/Arnavion/k8s-openapi/issues/63
729            // - https://github.com/deislabs/krustlet/issues/5
730            // - https://github.com/kubernetes/apimachinery/issues/88
731            let datetime_serialization_format = match (&**definition_path, &definition.kind) {
732                (
733                    "io.k8s.apimachinery.pkg.apis.meta.v1.MicroTime",
734                    swagger20::SchemaKind::Ty(swagger20::Type::String { format: Some(swagger20::StringFormat::DateTime) }),
735                ) => templates::DateTimeSerializationFormat::SixDecimalDigits,
736
737                (
738                    "io.k8s.apimachinery.pkg.apis.meta.v1.Time",
739                    swagger20::SchemaKind::Ty(swagger20::Type::String { format: Some(swagger20::StringFormat::DateTime) }),
740                ) => templates::DateTimeSerializationFormat::ZeroDecimalDigits,
741
742                _ => templates::DateTimeSerializationFormat::Default,
743            };
744
745            templates::newtype::generate(
746                &mut out,
747                vis,
748                type_name,
749                &inner_type_name,
750                datetime_serialization_format,
751                map_namespace,
752            )?;
753
754            run_result.num_generated_type_aliases += 1;
755        },
756    }
757
758    if let GenerateSchema::Yes { feature: schemars_feature } = generate_schema {
759        match &definition.kind {
760            swagger20::SchemaKind::Properties(_) |
761            swagger20::SchemaKind::Ty(
762                swagger20::Type::Any |
763                swagger20::Type::Array { .. } |
764                swagger20::Type::Boolean |
765                swagger20::Type::Integer { .. } |
766                swagger20::Type::Number { .. } |
767                swagger20::Type::Object { .. } |
768                swagger20::Type::String { .. } |
769                swagger20::Type::IntOrString |
770                swagger20::Type::JsonSchemaPropsOr(_, _) |
771                swagger20::Type::Quantity |
772                swagger20::Type::Patch
773            ) => {
774                templates::impl_schema::generate(
775                    &mut out,
776                    type_name,
777                    Default::default(),
778                    definition_path,
779                    definition,
780                    schemars_feature,
781                    map_namespace,
782                )?;
783            }
784
785            swagger20::SchemaKind::Ty(swagger20::Type::WatchEvent(_)) => {
786                templates::impl_schema::generate(
787                    &mut out,
788                    type_name,
789                    templates::Generics {
790                        type_part: Some("T"),
791                        where_part: None,
792                    },
793                    definition_path,
794                    definition,
795                    schemars_feature,
796                    map_namespace,
797                )?;
798            }
799
800            _ => (),
801        }
802    }
803
804    state.finish(out);
805
806    Ok(run_result)
807}
808
809fn map_namespace_local_to_string(map_namespace: &impl MapNamespace) -> Result<String, Error> {
810    let namespace_parts = map_namespace.map_namespace(&["io", "k8s"]).ok_or(r#"unexpected path "io.k8s""#)?;
811
812    let mut result = String::new();
813    for namespace_part in namespace_parts {
814        result.push_str(&get_rust_ident(namespace_part));
815        result.push_str("::");
816    }
817    Ok(result)
818}
819
820fn get_derives(
821    kind: &swagger20::SchemaKind,
822    definitions: &std::collections::BTreeMap<swagger20::DefinitionPath, swagger20::Schema>,
823    map_namespace: &impl MapNamespace,
824) -> Result<Option<templates::type_header::Derives>, Error> {
825    if matches!(kind, swagger20::SchemaKind::Ty(swagger20::Type::ListRef { .. })) {
826        // ListRef is emitted as a type alias.
827        return Ok(None);
828    }
829
830    let derive_clone =
831        evaluate_trait_bound(
832            kind,
833            true,
834            definitions,
835            map_namespace,
836            |_, _| Ok(true))?;
837
838    let derive_copy =
839        derive_clone &&
840        evaluate_trait_bound(
841            kind,
842            false,
843            definitions,
844            map_namespace,
845            |_, _| Ok(false))?;
846
847    #[allow(clippy::match_same_arms)]
848    let is_default = evaluate_trait_bound(kind, false, definitions, map_namespace, |kind, required| match kind {
849        // Option<T>::default is None regardless of T
850        _ if !required => Ok(true),
851
852        swagger20::SchemaKind::Ref(swagger20::RefPath { can_be_default: Some(can_be_default), .. }) => Ok(*can_be_default),
853
854        swagger20::SchemaKind::Ref(ref_path @ swagger20::RefPath { .. }) if ref_path.references_scope(map_namespace) => Ok(false),
855
856        // metadata field in resource type created by #[derive(CustomResourceDefinition)]
857        swagger20::SchemaKind::Ref(ref_path @ swagger20::RefPath { .. })
858            if !ref_path.references_scope(map_namespace) && ref_path.path == "io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" => Ok(true),
859
860        // Handled by evaluate_trait_bound
861        swagger20::SchemaKind::Ref(ref_path @ swagger20::RefPath { .. }) if !ref_path.references_scope(map_namespace) => unreachable!(),
862
863        // jiff::Timestamp defaults to `UNIX_EPOCH`, so best to not use the default value.
864        swagger20::SchemaKind::Ty(swagger20::Type::String { format: Some(swagger20::StringFormat::DateTime) }) => Ok(false),
865
866        // Enums without a default value
867        swagger20::SchemaKind::Ty(
868            swagger20::Type::JsonSchemaPropsOr(_, _) |
869            swagger20::Type::Patch |
870            swagger20::Type::WatchEvent(_)
871        ) => Ok(false),
872
873        _ => Ok(true),
874    })?;
875    let derive_default =
876        is_default &&
877        // IntOrString has a manual Default impl, so don't #[derive] it.
878        !matches!(kind, swagger20::SchemaKind::Ty(swagger20::Type::IntOrString));
879
880    let derive_partial_eq =
881        evaluate_trait_bound(
882            kind,
883            true,
884            definitions,
885            map_namespace,
886            |_, _| Ok(true))?;
887
888    // The choice of deriving Eq, Ord and PartialOrd is deliberately more conservative than the choice of deriving PartialEq,
889    // so as to not change dramatically between Kubernetes versions. For example, ObjectMeta is Ord in v1.15 but not in v1.16 because
890    // it indirectly gained a serde_json::Value field (`managed_fields.fields_v1.0`).
891    //
892    // Also, being conservative means the types generated by #[derive(k8s_openapi_derive::CustomResource)] don't have to require them either.
893
894    let derive_eq =
895        derive_partial_eq &&
896        matches!(kind, swagger20::SchemaKind::Ty(
897            swagger20::Type::IntOrString |
898            swagger20::Type::String { format: Some(swagger20::StringFormat::DateTime) }
899        ));
900
901    let derive_partial_ord =
902        derive_partial_eq &&
903        matches!(kind, swagger20::SchemaKind::Ty(swagger20::Type::String { format: Some(swagger20::StringFormat::DateTime) }));
904
905    let derive_ord = derive_partial_ord && derive_eq;
906
907    Ok(Some(templates::type_header::Derives {
908        clone: derive_clone,
909        copy: derive_copy,
910        default: derive_default,
911        eq: derive_eq,
912        ord: derive_ord,
913        partial_eq: derive_partial_eq,
914        partial_ord: derive_partial_ord,
915    }))
916}
917
918fn is_default(
919    kind: &swagger20::SchemaKind,
920    definitions: &std::collections::BTreeMap<swagger20::DefinitionPath, swagger20::Schema>,
921    map_namespace: &impl MapNamespace,
922) -> Result<bool, Error> {
923    #[allow(clippy::match_same_arms)]
924    evaluate_trait_bound(kind, false, definitions, map_namespace, |kind, required| match kind {
925        // Option<T>::default is None regardless of T
926        _ if !required => Ok(true),
927
928        swagger20::SchemaKind::Ref(swagger20::RefPath { can_be_default: Some(can_be_default), .. }) => Ok(*can_be_default),
929
930        swagger20::SchemaKind::Ref(ref_path @ swagger20::RefPath { .. }) if ref_path.references_scope(map_namespace) => Ok(false),
931
932        // metadata field in resource type created by #[derive(CustomResourceDefinition)]
933        swagger20::SchemaKind::Ref(ref_path @ swagger20::RefPath { .. })
934            if !ref_path.references_scope(map_namespace) && ref_path.path == "io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" => Ok(true),
935
936        // Handled by evaluate_trait_bound
937        swagger20::SchemaKind::Ref(ref_path @ swagger20::RefPath { .. }) if !ref_path.references_scope(map_namespace) => unreachable!(),
938
939        // jiff::Timestamp defaults to `UNIX_EPOCH`, so best to not use the default value.
940        swagger20::SchemaKind::Ty(swagger20::Type::String { format: Some(swagger20::StringFormat::DateTime) }) => Ok(false),
941
942        // Enums without a default value
943        swagger20::SchemaKind::Ty(
944            swagger20::Type::JsonSchemaPropsOr(_, _) |
945            swagger20::Type::Patch |
946            swagger20::Type::WatchEvent(_)
947        ) => Ok(false),
948
949        _ => Ok(true),
950    })
951}
952
953fn evaluate_trait_bound(
954    kind: &swagger20::SchemaKind,
955    array_follows_elements: bool,
956    definitions: &std::collections::BTreeMap<swagger20::DefinitionPath, swagger20::Schema>,
957    map_namespace: &impl MapNamespace,
958    mut f: impl FnMut(&swagger20::SchemaKind, bool) -> Result<bool, Error>,
959) -> Result<bool, Error> {
960    fn evaluate_trait_bound_inner<'a>(
961        #[allow(clippy::ptr_arg)] // False positive. Clippy wants this to be `&SchemaKind` but we use Cow-specific operations (`.clone()`).
962        kind: &std::borrow::Cow<'a, swagger20::SchemaKind>,
963        required: bool,
964        array_follows_elements: bool,
965        definitions: &std::collections::BTreeMap<swagger20::DefinitionPath, swagger20::Schema>,
966        map_namespace: &impl MapNamespace,
967        visited: &mut std::collections::BTreeSet<std::borrow::Cow<'a, swagger20::SchemaKind>>,
968        f: &mut impl FnMut(&swagger20::SchemaKind, bool) -> Result<bool, Error>,
969    ) -> Result<bool, Error> {
970        if !visited.insert(kind.clone()) {
971            // In case of recursive types, assume the bound holds.
972            return Ok(true);
973        }
974
975        match &**kind {
976            swagger20::SchemaKind::Properties(properties) => {
977                for (property_schema, property_required) in properties.values() {
978                    let mut visited = visited.clone();
979                    let field_bound =
980                        evaluate_trait_bound_inner(
981                            &std::borrow::Cow::Borrowed(&property_schema.kind),
982                            required && *property_required,
983                            array_follows_elements,
984                            definitions,
985                            map_namespace,
986                            &mut visited,
987                            f,
988                        )?;
989                    if !field_bound {
990                        return Ok(false);
991                    }
992                }
993
994                Ok(true)
995            },
996
997            swagger20::SchemaKind::Ref(ref_path @ swagger20::RefPath { .. }) if !ref_path.references_scope(map_namespace) => {
998                let trait_bound =
999                    if let Some(target) = definitions.get(&*ref_path.path) {
1000                        let mut visited = visited.clone();
1001                        evaluate_trait_bound_inner(
1002                            &std::borrow::Cow::Borrowed(&target.kind),
1003                            required,
1004                            array_follows_elements,
1005                            definitions,
1006                            map_namespace,
1007                            &mut visited,
1008                            f,
1009                        )
1010                    }
1011                    else {
1012                        f(kind, required)
1013                    };
1014                trait_bound
1015            },
1016
1017            swagger20::SchemaKind::Ty(swagger20::Type::Array { items }) if array_follows_elements =>
1018                evaluate_trait_bound_inner(
1019                    &std::borrow::Cow::Owned(items.kind.clone()),
1020                    required,
1021                    array_follows_elements,
1022                    definitions,
1023                    map_namespace,
1024                    visited,
1025                    f,
1026                ),
1027
1028            swagger20::SchemaKind::Ty(swagger20::Type::JsonSchemaPropsOr(namespace, _)) => {
1029                let json_schema_props_ref_path = swagger20::RefPath {
1030                    path: format!("io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.{namespace}.JSONSchemaProps"),
1031                    can_be_default: None,
1032                };
1033                let json_schema_props_bound =
1034                    evaluate_trait_bound_inner(
1035                        &std::borrow::Cow::Owned(swagger20::SchemaKind::Ref(json_schema_props_ref_path)),
1036                        required,
1037                        array_follows_elements,
1038                        definitions,
1039                        map_namespace,
1040                        visited,
1041                        f,
1042                    )?;
1043                if !json_schema_props_bound {
1044                    return Ok(false);
1045                }
1046
1047                f(kind, required)
1048            },
1049
1050            swagger20::SchemaKind::Ty(swagger20::Type::WatchEvent(raw_extension_ref_path)) => {
1051                let raw_extension_bound =
1052                    evaluate_trait_bound_inner(
1053                        &std::borrow::Cow::Owned(swagger20::SchemaKind::Ref(raw_extension_ref_path.clone())),
1054                        required,
1055                        array_follows_elements,
1056                        definitions,
1057                        map_namespace,
1058                        visited,
1059                        f,
1060                    )?;
1061                if !raw_extension_bound {
1062                    return Ok(false);
1063                }
1064
1065                f(kind, required)
1066            },
1067
1068            kind => f(kind, required),
1069        }
1070    }
1071
1072    let mut visited = Default::default();
1073    evaluate_trait_bound_inner(
1074        &std::borrow::Cow::Borrowed(kind),
1075        true,
1076        array_follows_elements,
1077        definitions,
1078        map_namespace,
1079        &mut visited,
1080        &mut f,
1081    )
1082}
1083
1084fn get_comment_text<'a>(s: &'a str, indent: &'a str) -> impl Iterator<Item = std::borrow::Cow<'static, str>> + 'a {
1085    s.lines().scan(true, move |previous_line_was_empty, line|
1086        if line.is_empty() {
1087            *previous_line_was_empty = true;
1088            Some("".into())
1089        }
1090        else {
1091            let line =
1092                line
1093                .replace('\\', r"\\")
1094                .replace('[', r"\[")
1095                .replace(']', r"\]")
1096                .replace('<', r"\<")
1097                .replace('>', r"\>")
1098                .replace('\t', "    ")
1099                .replace("```", "");
1100
1101            let line =
1102                if *previous_line_was_empty && line.starts_with("    ") {
1103                    // Collapse this line's spaces into two. Otherwise rustdoc will think this is the start of a code block containing a Rust test.
1104                    format!("  {}", line.trim_start())
1105                }
1106                else {
1107                    line
1108                };
1109            let line = line.trim_end();
1110
1111            *previous_line_was_empty = false;
1112
1113            Some(format!("{indent} {line}").into())
1114        })
1115}
1116
1117fn get_fully_qualified_type_name(
1118    ref_path: &swagger20::RefPath,
1119    map_namespace: &impl MapNamespace,
1120) -> String {
1121    let path_parts: Vec<_> = ref_path.path.split('.').collect();
1122    let namespace_parts = map_namespace.map_namespace(&path_parts[..(path_parts.len() - 1)]);
1123    if let Some(namespace_parts) = namespace_parts {
1124        let mut result = String::new();
1125        for namespace_part in namespace_parts {
1126            result.push_str(&get_rust_ident(namespace_part));
1127            result.push_str("::");
1128        }
1129        result.push_str(path_parts[path_parts.len() - 1]);
1130        result
1131    }
1132    else {
1133        let last_part = *path_parts.last().expect("str::split yields at least one item");
1134        last_part.to_owned()
1135    }
1136}
1137
1138/// Converts the given string into a string that can be used as a Rust ident.
1139pub fn get_rust_ident(name: &str) -> std::borrow::Cow<'static, str> {
1140    // Fix cases of invalid rust idents
1141    match name {
1142        "$ref" => return "ref_path".into(),
1143        "$schema" => return "schema".into(),
1144        "as" => return "as_".into(),
1145        "continue" => return "continue_".into(),
1146        "enum" => return "enum_".into(),
1147        "ref" => return "ref_".into(),
1148        "type" => return "type_".into(),
1149        _ => (),
1150    }
1151
1152    // Some cases of "ABc" should be converted to "abc" instead of "a_bc".
1153    // Eg "JSONSchemas" => "json_schemas", but "externalIPs" => "external_ips" instead of "external_i_ps".
1154    // Mostly happens with plurals of abbreviations.
1155    match name {
1156        "clusterIPs" => return "cluster_ips".into(),
1157        "externalIPs" => return "external_ips".into(),
1158        "hostIPs" => return "host_ips".into(),
1159        "nonResourceURLs" => return "non_resource_urls".into(),
1160        "podCIDRs" => return "pod_cidrs".into(),
1161        "podIPs" => return "pod_ips".into(),
1162        "serverAddressByClientCIDRs" => return "server_address_by_client_cidrs".into(),
1163        "targetWWNs" => return "target_wwns".into(),
1164        _ => (),
1165    }
1166
1167    let mut result = String::new();
1168
1169    let chars =
1170        name.chars()
1171        .zip(std::iter::once(None).chain(name.chars().map(|c| Some(c.is_uppercase()))))
1172        .zip(name.chars().skip(1).map(|c| Some(c.is_uppercase())).chain(std::iter::once(None)));
1173
1174    for ((c, previous), next) in chars {
1175        if c.is_uppercase() {
1176            match (previous, next) {
1177                (Some(false), _) |
1178                (Some(true), Some(false)) => result.push('_'),
1179                _ => (),
1180            }
1181
1182            result.extend(c.to_lowercase());
1183        }
1184        else {
1185            result.push(match c {
1186                '-' => '_',
1187                c => c,
1188            });
1189        }
1190    }
1191
1192    result.into()
1193}
1194
1195fn get_rust_type(
1196    schema_kind: &swagger20::SchemaKind,
1197    map_namespace: &impl MapNamespace,
1198) -> Result<std::borrow::Cow<'static, str>, Error> {
1199    let local = map_namespace_local_to_string(map_namespace)?;
1200
1201    match schema_kind {
1202        swagger20::SchemaKind::Properties(_) => Err("Nested anonymous types not supported".into()),
1203
1204        swagger20::SchemaKind::Ref(ref_path) =>
1205            Ok(get_fully_qualified_type_name(ref_path, map_namespace).into()),
1206
1207        swagger20::SchemaKind::Ty(swagger20::Type::Any) => Ok(format!("{local}serde_json::Value").into()),
1208
1209        swagger20::SchemaKind::Ty(swagger20::Type::Array { items }) =>
1210            Ok(format!("std::vec::Vec<{}>", get_rust_type(&items.kind, map_namespace)?).into()),
1211
1212        swagger20::SchemaKind::Ty(swagger20::Type::Boolean) => Ok("bool".into()),
1213
1214        swagger20::SchemaKind::Ty(swagger20::Type::Integer { format: swagger20::IntegerFormat::Int32 }) => Ok("i32".into()),
1215        swagger20::SchemaKind::Ty(swagger20::Type::Integer { format: swagger20::IntegerFormat::Int64 }) => Ok("i64".into()),
1216
1217        swagger20::SchemaKind::Ty(swagger20::Type::Number { format: swagger20::NumberFormat::Double }) => Ok("f64".into()),
1218
1219        swagger20::SchemaKind::Ty(swagger20::Type::Object { additional_properties }) =>
1220            Ok(format!("std::collections::BTreeMap<std::string::String, {}>", get_rust_type(&additional_properties.kind, map_namespace)?).into()),
1221
1222        swagger20::SchemaKind::Ty(swagger20::Type::String { format: Some(swagger20::StringFormat::Byte) }) =>
1223            Ok(format!("{local}ByteString").into()),
1224        swagger20::SchemaKind::Ty(swagger20::Type::String { format: Some(swagger20::StringFormat::DateTime) }) =>
1225            Ok(format!("{local}jiff::Timestamp").into()),
1226        swagger20::SchemaKind::Ty(swagger20::Type::String { format: None }) => Ok("std::string::String".into()),
1227
1228        swagger20::SchemaKind::Ty(swagger20::Type::CustomResourceSubresources(namespace)) => {
1229            let namespace_parts =
1230                &["io", "k8s", "apiextensions_apiserver", "pkg", "apis", "apiextensions", namespace];
1231            let namespace_parts =
1232                map_namespace.map_namespace(namespace_parts)
1233                .ok_or_else(|| format!("unexpected path {:?}", namespace_parts.join(".")))?;
1234
1235            let mut result = String::new();
1236            for namespace_part in namespace_parts {
1237                result.push_str(&get_rust_ident(namespace_part));
1238                result.push_str("::");
1239            }
1240            result.push_str("CustomResourceSubresources");
1241            Ok(result.into())
1242        },
1243
1244        swagger20::SchemaKind::Ty(swagger20::Type::IntOrString) => Err("nothing should be trying to refer to IntOrString".into()),
1245        swagger20::SchemaKind::Ty(swagger20::Type::JsonSchemaPropsOr(_, _)) => Err("JSON schema types not supported".into()),
1246        swagger20::SchemaKind::Ty(swagger20::Type::Quantity) => Err("nothing should be trying to refer to Quantity".into()),
1247
1248        swagger20::SchemaKind::Ty(swagger20::Type::Patch) => Err("Patch type not supported".into()),
1249        swagger20::SchemaKind::Ty(swagger20::Type::WatchEvent(_)) => Err("WatchEvent type not supported".into()),
1250
1251        swagger20::SchemaKind::Ty(swagger20::Type::ListDef { .. }) => Err("ListDef type not supported".into()),
1252        swagger20::SchemaKind::Ty(swagger20::Type::ListRef { items }) =>
1253            Ok(format!("{local}List<{}>", get_rust_type(items, map_namespace)?).into()),
1254    }
1255}