Skip to content

refactor(stackable-versioned): Simplify attribute handling #1053

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 40 additions & 11 deletions crates/stackable-versioned-macros/src/attrs/common.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::ops::Deref;

use darling::{
Error, FromMeta, Result,
util::{Flag, Override, SpannedValue},
util::{Flag, Override as FlagOrOverride, SpannedValue},
};
use itertools::Itertools;
use k8s_version::Version;
Expand All @@ -11,15 +13,15 @@ pub trait CommonOptions {

#[derive(Debug, FromMeta)]
#[darling(and_then = CommonRootArguments::validate)]
pub(crate) struct CommonRootArguments<T>
pub struct CommonRootArguments<T>
where
T: CommonOptions + Default,
{
#[darling(default)]
pub(crate) options: T,
pub options: T,

#[darling(multiple, rename = "version")]
pub(crate) versions: SpannedValue<Vec<VersionArguments>>,
pub versions: SpannedValue<Vec<VersionArguments>>,
}

impl<T> CommonRootArguments<T>
Expand Down Expand Up @@ -78,11 +80,11 @@ where
/// - `skip` option to skip generating various pieces of code.
/// - `doc` option to add version-specific documentation.
#[derive(Clone, Debug, FromMeta)]
pub(crate) struct VersionArguments {
pub(crate) deprecated: Option<Override<String>>,
pub(crate) name: Version,
pub(crate) skip: Option<SkipArguments>,
pub(crate) doc: Option<String>,
pub struct VersionArguments {
pub deprecated: Option<FlagOrOverride<String>>,
pub skip: Option<SkipArguments>,
pub doc: Option<String>,
pub name: Version,
}

/// This struct contains supported common skip arguments.
Expand All @@ -91,8 +93,35 @@ pub(crate) struct VersionArguments {
///
/// - `from` flag, which skips generating [`From`] implementations when provided.
#[derive(Clone, Debug, Default, FromMeta)]
pub(crate) struct SkipArguments {
pub struct SkipArguments {
/// Whether the [`From`] implementation generation should be skipped for all versions of this
/// container.
pub(crate) from: Flag,
pub from: Flag,
}

/// Wraps a value to indicate whether it is original or has been overridden.
#[derive(Clone, Debug)]
pub enum Override<T> {
Default(T),
Explicit(T),
}

impl<T> FromMeta for Override<T>
where
T: FromMeta,
{
fn from_meta(item: &syn::Meta) -> Result<Self> {
FromMeta::from_meta(item).map(Override::Explicit)
}
}

impl<T> Deref for Override<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
match &self {
Override::Default(inner) => inner,
Override::Explicit(inner) => inner,
}
}
}
179 changes: 179 additions & 0 deletions crates/stackable-versioned-macros/src/attrs/container/k8s.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
use darling::{FromMeta, util::Flag};
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::{Path, parse_quote};

use crate::attrs::common::Override;

/// This struct contains supported Kubernetes arguments.
///
/// The arguments are passed through to the `#[kube]` attribute. More details can be found in the
/// official docs: <https://docs.rs/kube/latest/kube/derive.CustomResource.html>.
///
/// Supported arguments are:
///
/// - `group`: Set the group of the CR object, usually the domain of the company.
/// This argument is Required.
/// - `kind`: Override the kind field of the CR object. This defaults to the struct
/// name (without the 'Spec' suffix).
/// - `singular`: Set the singular name of the CR object.
/// - `plural`: Set the plural name of the CR object.
/// - `namespaced`: Indicate that this is a namespaced scoped resource rather than a
/// cluster scoped resource.
/// - `crates`: Override specific crates.
/// - `status`: Set the specified struct as the status subresource.
/// - `shortname`: Set a shortname for the CR object. This can be specified multiple
/// times.
/// - `skip`: Controls skipping parts of the generation.
#[derive(Clone, Debug, FromMeta)]
pub struct KubernetesArguments {
pub group: String,
pub kind: Option<String>,
pub singular: Option<String>,
pub plural: Option<String>,
pub namespaced: Flag,
// root
#[darling(default)]
pub crates: KubernetesCrateArguments,
pub status: Option<Path>,
// derive
// schema
// scale
// printcolumn
#[darling(multiple, rename = "shortname")]
pub shortnames: Vec<String>,
// category
// selectable
// doc
// annotation
// label
pub skip: Option<KubernetesSkipArguments>,

#[darling(default)]
pub options: KubernetesConfigOptions,
}

/// This struct contains supported kubernetes skip arguments.
///
/// Supported arguments are:
///
/// - `merged_crd` flag, which skips generating the `crd()` and `merged_crd()` functions are
/// generated.
#[derive(Clone, Debug, FromMeta)]
pub struct KubernetesSkipArguments {
/// Whether the `crd()` and `merged_crd()` generation should be skipped for
/// this container.
pub merged_crd: Flag,
}

/// This struct contains crate overrides to be passed to `#[kube]`.
#[derive(Clone, Debug, FromMeta)]
pub struct KubernetesCrateArguments {
#[darling(default = default_kube_core)]
pub kube_core: Override<Path>,

#[darling(default = default_kube_client)]
pub kube_client: Override<Path>,

#[darling(default = default_k8s_openapi)]
pub k8s_openapi: Override<Path>,

#[darling(default = default_schemars)]
pub schemars: Override<Path>,

#[darling(default = default_serde)]
pub serde: Override<Path>,

#[darling(default = default_serde_json)]
pub serde_json: Override<Path>,

#[darling(default = default_versioned)]
pub versioned: Override<Path>,
}

impl Default for KubernetesCrateArguments {
fn default() -> Self {
Self {
kube_core: default_kube_core(),
kube_client: default_kube_client(),
k8s_openapi: default_k8s_openapi(),
schemars: default_schemars(),
serde: default_serde(),
serde_json: default_serde_json(),
versioned: default_versioned(),
}
}
}

fn default_kube_core() -> Override<Path> {
Override::Default(parse_quote! { ::kube::core })
}

fn default_kube_client() -> Override<Path> {
Override::Default(parse_quote! { ::kube::client })
}

fn default_k8s_openapi() -> Override<Path> {
Override::Default(parse_quote! { ::k8s_openapi })
}

fn default_schemars() -> Override<Path> {
Override::Default(parse_quote! { ::schemars })
}

fn default_serde() -> Override<Path> {
Override::Default(parse_quote! { ::serde })
}

fn default_serde_json() -> Override<Path> {
Override::Default(parse_quote! { ::serde_json })
}

fn default_versioned() -> Override<Path> {
Override::Default(parse_quote! { ::stackable_versioned })
}

impl ToTokens for KubernetesCrateArguments {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let mut crate_overrides = TokenStream::new();

let KubernetesCrateArguments {
kube_client: _,
k8s_openapi,
serde_json,
kube_core,
schemars,
serde,
..
} = self;

if let Override::Explicit(k8s_openapi) = k8s_openapi {
crate_overrides.extend(quote! { k8s_openapi = #k8s_openapi, });
}

if let Override::Explicit(serde_json) = serde_json {
crate_overrides.extend(quote! { serde_json = #serde_json, });
}

if let Override::Explicit(kube_core) = kube_core {
crate_overrides.extend(quote! { kube_core = #kube_core, });
}

if let Override::Explicit(schemars) = schemars {
crate_overrides.extend(quote! { schemars = #schemars, });
}

if let Override::Explicit(serde) = serde {
crate_overrides.extend(quote! { serde = #serde, });
}

if !crate_overrides.is_empty() {
tokens.extend(quote! { , crates(#crate_overrides) });
}
}
}

#[derive(Clone, Default, Debug, FromMeta)]
pub struct KubernetesConfigOptions {
pub experimental_conversion_tracking: Flag,
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ use darling::{Error, FromAttributes, FromMeta, Result, util::Flag};

use crate::attrs::{
common::{CommonOptions, CommonRootArguments, SkipArguments},
k8s::KubernetesArguments,
container::k8s::KubernetesArguments,
};

pub mod k8s;

#[derive(Debug, FromMeta)]
#[darling(and_then = StandaloneContainerAttributes::validate)]
pub(crate) struct StandaloneContainerAttributes {
pub struct StandaloneContainerAttributes {
#[darling(rename = "k8s")]
pub(crate) kubernetes_arguments: Option<KubernetesArguments>,
pub kubernetes_arguments: Option<KubernetesArguments>,

#[darling(flatten)]
pub(crate) common: CommonRootArguments<StandaloneContainerOptions>,
pub common: CommonRootArguments<StandaloneContainerOptions>,
}

impl StandaloneContainerAttributes {
Expand All @@ -28,9 +30,9 @@ impl StandaloneContainerAttributes {
}

#[derive(Debug, FromMeta, Default)]
pub(crate) struct StandaloneContainerOptions {
pub(crate) allow_unsorted: Flag,
pub(crate) skip: Option<SkipArguments>,
pub struct StandaloneContainerOptions {
pub allow_unsorted: Flag,
pub skip: Option<SkipArguments>,
}

impl CommonOptions for StandaloneContainerOptions {
Expand All @@ -44,12 +46,12 @@ impl CommonOptions for StandaloneContainerOptions {
attributes(versioned),
and_then = NestedContainerAttributes::validate
)]
pub(crate) struct NestedContainerAttributes {
pub struct NestedContainerAttributes {
#[darling(rename = "k8s")]
pub(crate) kubernetes_arguments: Option<KubernetesArguments>,
pub kubernetes_arguments: Option<KubernetesArguments>,

#[darling(default)]
pub(crate) options: NestedContainerOptionArguments,
pub options: NestedContainerOptionArguments,
}

impl NestedContainerAttributes {
Expand All @@ -65,6 +67,6 @@ impl NestedContainerAttributes {
}

#[derive(Debug, Default, FromMeta)]
pub(crate) struct NestedContainerOptionArguments {
pub(crate) skip: Option<SkipArguments>,
pub struct NestedContainerOptionArguments {
pub skip: Option<SkipArguments>,
}
10 changes: 5 additions & 5 deletions crates/stackable-versioned-macros/src/attrs/item/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,20 @@ use crate::{attrs::item::CommonItemAttributes, codegen::VersionDefinition, utils
forward_attrs,
and_then = FieldAttributes::validate
)]
pub(crate) struct FieldAttributes {
pub struct FieldAttributes {
#[darling(flatten)]
pub(crate) common: CommonItemAttributes,
pub common: CommonItemAttributes,

// The ident (automatically extracted by darling) cannot be moved into the
// shared item attributes because for struct fields, the type is
// `Option<Ident>`, while for enum variants, the type is `Ident`.
pub(crate) ident: Option<Ident>,
pub ident: Option<Ident>,

// This must be named `attrs` for darling to populate it accordingly, and
// cannot live in common because Vec<Attribute> is not implemented for
// FromMeta.
/// The original attributes for the field.
pub(crate) attrs: Vec<Attribute>,
pub attrs: Vec<Attribute>,
}

impl FieldAttributes {
Expand All @@ -56,7 +56,7 @@ impl FieldAttributes {
Ok(self)
}

pub(crate) fn validate_versions(&self, versions: &[VersionDefinition]) -> Result<()> {
pub fn validate_versions(&self, versions: &[VersionDefinition]) -> Result<()> {
self.common.validate_versions(versions)
}
}
Loading