Skip to main content

k8s_openapi_derive/
lib.rs

1#![recursion_limit = "1024"]
2#![warn(rust_2018_idioms)]
3
4//! This crate contains custom derives related to the [`k8s-openapi`](https://crates.io/crates/k8s-openapi) crate.
5
6mod custom_resource_definition;
7
8trait CustomDerive: Sized {
9    fn parse(input: syn::DeriveInput, tokens: proc_macro2::TokenStream) -> Result<Self, syn::Error>;
10    fn emit(self) -> Result<proc_macro2::TokenStream, syn::Error>;
11}
12
13fn run_custom_derive<T>(input: proc_macro::TokenStream) -> proc_macro::TokenStream where T: CustomDerive {
14    let input: proc_macro2::TokenStream = input.into();
15    let tokens = input.clone();
16    let token_stream = match syn::parse2(input).and_then(|input| <T as CustomDerive>::parse(input, tokens)).and_then(<T as CustomDerive>::emit) {
17        Ok(token_stream) => token_stream,
18        Err(err) => err.to_compile_error(),
19    };
20    token_stream.into()
21}
22
23trait ResultExt<T> {
24    fn spanning(self, spanned: impl quote::ToTokens) -> Result<T, syn::Error>;
25}
26
27impl<T, E> ResultExt<T> for Result<T, E> where E: std::fmt::Display {
28    fn spanning(self, spanned: impl quote::ToTokens) -> Result<T, syn::Error> {
29        self.map_err(|err| syn::Error::new_spanned(spanned, err))
30    }
31}
32
33/// This custom derive can be used on a Kubernetes custom resource spec type to generate a custom resource definition object type
34/// and related trait impls.
35///
36/// # Example
37///
38/// ```rust,ignore
39/// #[derive(
40///     Clone, Debug, PartialEq,
41///     k8s_openapi_derive::CustomResourceDefinition,
42///     serde::Deserialize, serde::Serialize,
43/// )]
44/// #[custom_resource_definition(
45///     group = "k8s-openapi-tests-custom-resource-definition.com",
46///     version = "v1",
47///     plural = "foobars",
48///     generate_schema,
49///     namespaced,
50///     has_subresources = "v1",
51///     impl_deep_merge,
52/// )]
53/// struct FooBarSpec {
54///     prop1: String,
55///     prop2: Vec<bool>,
56///     #[serde(skip_serializing_if = "Option::is_none")]
57///     prop3: Option<i32>,
58/// }
59/// ```
60///
61/// Note:
62///
63/// - The spec type must impl the following traits (either manually or via `#[derive]`): `Clone`, `Debug`, `PartialEq`,
64///   `serde::Deserialize` and `serde::Serialize`
65///
66/// - The name of the spec type must end with `Spec`. This suffix is trimmed to generate the name of the object type.
67///
68/// - The `k8s_openapi` crate must have been added as a dependency, since the macro expansion refers to types from it.
69///
70/// The custom derive then generates a `FooBar` type that represents a custom resource corresponding to this definition:
71///
72/// ```rust,ignore
73/// /// Custom resource for FooBarSpec
74/// #[derive(Clone, Debug, Default, PartialEq)]
75/// struct FooBar {
76///     metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta,
77///     spec: Option<FooBarSpec>,
78///     subresources: k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceSubresources,
79/// }
80///
81/// impl k8s_openapi::Resource for FooBar { ... }
82///
83/// impl k8s_openapi::ListableResource for FooBar { ... }
84///
85/// impl k8s_openapi::Metadata for FooBar {
86///     type Ty = k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
87///
88///     ...
89/// }
90///
91/// impl<'de> k8s_openapi::serde::Deserialize<'de> for FooBar { ... }
92///
93/// impl k8s_openapi::serde::Serialize for FooBar { ... }
94///
95/// impl k8s_openapi::schemars::JsonSchema for FooBar { ... }
96/// ```
97///
98/// The name of this type is automatically derived from the name of the spec type by truncating the `Spec` suffix.
99///
100/// The `group` and `version` meta items of the `#[custom_resource_definition]` attribute of the macro are used to set
101/// the "group" and "API version" in the `k8s_openapi::Resource` impl respectively. The "kind" is automatically set to be the same as the resource type name,
102/// ie `"FooBar"` in this example. The `plural` meta item is used to construct the URLs of API operations for this custom resource.
103///
104/// The `generate_schema` meta item is optional. If set, the generated custom resource type will have an impl of `schemars::JsonSchema` from the `schemars` crate.
105/// The `schemars` feature of the `k8s-openapi` crate must be enabled so that the types in that crate also have their `schemars::JsonSchema` impls enabled.
106/// You will also need to impl `schemars::JsonSchema` on the `Spec` type itself, either manually or via `#[derive(schemars::JsonSchema)]`.
107///
108/// The `has_subresources` meta item is optional. If set, the generated custom resource type will have a `subresources` field. The value of the meta item
109/// specifies which namespace the type will be used from. For example, setting `has_subresources = "v1"` causes the field to be of the
110/// `k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceSubresources` type.
111///
112/// The `impl_deep_merge` meta item is optional. If set, the generated custom resource type will impl the `k8s_openapi::DeepMerge` trait. This impl will require
113/// you to impl `k8s_openapi::DeepMerge` on the spec type yourself.
114///
115/// You would then register this custom resource definition with Kubernetes, with code like this:
116///
117/// ```rust,ignore
118/// use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1 as apiextensions;
119/// use k8s_openapi::apimachinery::pkg::apis::meta::v1 as meta;
120///
121/// // Same as the `plurals` meta item in the `#[custom_resource_definition]` attribute
122/// let plural = "foobars";
123///
124/// let custom_resource_definition_spec = apiextensions::CustomResourceDefinitionSpec {
125///     group: <FooBar as k8s_openapi::Resource>::GROUP.to_owned(),
126///     names: apiextensions::CustomResourceDefinitionNames {
127///         kind: <FooBar as k8s_openapi::Resource>::KIND.to_owned(),
128///         plural: plural.to_owned(),
129///         short_names: Some(vec!["fb".to_owned()]),
130///         singular: Some("foobar".to_owned()),
131///         ..Default::default()
132///     },
133///     scope: "Namespaced".to_owned(),
134///     version: <FooBar as k8s_openapi::Resource>::VERSION.to_owned().into(),
135///     ..Default::default()
136/// };
137///
138/// let custom_resource_definition = apiextensions::CustomResourceDefinition {
139///     metadata: meta::ObjectMeta {
140///         name: Some(format!("{plural}.{}", <FooBar as k8s_openapi::Resource>::GROUP)),
141///         ..Default::default()
142///     },
143///     spec: custom_resource_definition_spec.into(),
144///     ..Default::default()
145/// };
146///
147/// client.create(custom_resource_definition);
148/// ```
149///
150/// (You may wish to generate run your crate through `cargo-expand` to see the macro expansion.)
151///
152/// See the [`custom_resource_definition` test in the repository](https://github.com/Arnavion/k8s-openapi/blob/master/k8s-openapi-tests/src/custom_resource_definition.rs)
153/// for a full example of using this custom derive.
154#[proc_macro_derive(CustomResourceDefinition, attributes(custom_resource_definition))]
155pub fn derive_custom_resource_definition(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
156    run_custom_derive::<custom_resource_definition::CustomResourceDefinition>(input)
157}