Skip to content

Commit

Permalink
Support --enum-extra-derives (#1934)
Browse files Browse the repository at this point in the history
* feat: Support `--enum-extra-derives`

* test: Enum extra derives

* style: Don't format derives

* fix: Put `quote!` inside a function with `#[rustfmt::skip]`
  • Loading branch information
TmLev committed Nov 8, 2023
1 parent d6835b1 commit 0dbfb42
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 15 deletions.
7 changes: 7 additions & 0 deletions sea-orm-cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,13 @@ pub enum GenerateSubcommands {
)]
model_extra_attributes: Vec<String>,

#[arg(
long,
value_delimiter = ',',
help = "Add extra derive macros to generated enums (comma separated), e.g. `--enum-extra-derives 'ts_rs::Ts','CustomDerive'`"
)]
enum_extra_derives: Vec<String>,

#[arg(
long,
default_value = "false",
Expand Down
2 changes: 2 additions & 0 deletions sea-orm-cli/src/commands/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub async fn run_generate_command(
lib,
model_extra_derives,
model_extra_attributes,
enum_extra_derives,
seaography,
} => {
if verbose {
Expand Down Expand Up @@ -180,6 +181,7 @@ pub async fn run_generate_command(
serde_skip_hidden_column,
model_extra_derives,
model_extra_attributes,
enum_extra_derives,
seaography,
);
let output = EntityTransformer::transform(table_stmts)?.generate(&writer_context);
Expand Down
50 changes: 46 additions & 4 deletions sea-orm-codegen/src/entity/active_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ pub struct ActiveEnum {
}

impl ActiveEnum {
pub fn impl_active_enum(&self, with_serde: &WithSerde, with_copy_enums: bool) -> TokenStream {
pub fn impl_active_enum(
&self,
with_serde: &WithSerde,
with_copy_enums: bool,
extra_derives: &TokenStream,
) -> TokenStream {
let enum_name = &self.enum_name.to_string();
let enum_iden = format_ident!("{}", enum_name.to_upper_camel_case());
let values: Vec<String> = self.values.iter().map(|v| v.to_string()).collect();
Expand All @@ -24,15 +29,15 @@ impl ActiveEnum {
}
});

let extra_derive = with_serde.extra_derive();
let serde_derive = with_serde.extra_derive();
let copy_derive = if with_copy_enums {
quote! { , Copy }
} else {
quote! {}
};

quote! {
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum #copy_derive #extra_derive)]
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum #copy_derive #serde_derive #extra_derives)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = #enum_name)]
pub enum #enum_iden {
#(
Expand All @@ -46,6 +51,8 @@ impl ActiveEnum {

#[cfg(test)]
mod tests {
use crate::entity::writer::bonus_derive;

use super::*;
use pretty_assertions::assert_eq;
use sea_query::{Alias, IntoIden};
Expand All @@ -72,7 +79,7 @@ mod tests {
.map(|variant| Alias::new(variant).into_iden())
.collect(),
}
.impl_active_enum(&WithSerde::None, true)
.impl_active_enum(&WithSerde::None, true, &quote! {})
.to_string(),
quote!(
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Copy)]
Expand Down Expand Up @@ -105,4 +112,39 @@ mod tests {
.to_string()
)
}

#[test]
fn test_enum_extra_derives() {
assert_eq!(
ActiveEnum {
enum_name: Alias::new("media_type").into_iden(),
values: vec!["UNKNOWN", "BITMAP",]
.into_iter()
.map(|variant| Alias::new(variant).into_iden())
.collect(),
}
.impl_active_enum(
&WithSerde::None,
true,
&bonus_derive(["specta::Type", "ts_rs::TS"])
)
.to_string(),
build_generated_enum(),
);

#[rustfmt::skip]
fn build_generated_enum() -> String {
quote!(
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Copy, specta :: Type, ts_rs :: TS)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "media_type")]
pub enum MediaType {
#[sea_orm(string_value = "UNKNOWN")]
Unknown,
#[sea_orm(string_value = "BITMAP")]
Bitmap,
}
)
.to_string()
}
}
}
30 changes: 19 additions & 11 deletions sea-orm-codegen/src/entity/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub struct EntityWriterContext {
pub(crate) serde_skip_deserializing_primary_key: bool,
pub(crate) model_extra_derives: TokenStream,
pub(crate) model_extra_attributes: TokenStream,
pub(crate) enum_extra_derives: TokenStream,
pub(crate) seaography: bool,
}

Expand Down Expand Up @@ -79,19 +80,19 @@ impl WithSerde {
}
}

/// Converts model_extra_derives argument to token stream
fn bonus_derive<T, I>(model_extra_derives: I) -> TokenStream
/// Converts *_extra_derives argument to token stream
pub(crate) fn bonus_derive<T, I>(extra_derives: I) -> TokenStream
where
T: Into<String>,
I: IntoIterator<Item = T>,
{
model_extra_derives
.into_iter()
.map(Into::<String>::into)
.fold(TokenStream::default(), |acc, derive| {
extra_derives.into_iter().map(Into::<String>::into).fold(
TokenStream::default(),
|acc, derive| {
let tokens: TokenStream = derive.parse().unwrap();
quote! { #acc, #tokens }
})
},
)
}

/// convert attributes argument to token stream
Expand Down Expand Up @@ -143,6 +144,7 @@ impl EntityWriterContext {
serde_skip_hidden_column: bool,
model_extra_derives: Vec<String>,
model_extra_attributes: Vec<String>,
enum_extra_derives: Vec<String>,
seaography: bool,
) -> Self {
Self {
Expand All @@ -156,6 +158,7 @@ impl EntityWriterContext {
serde_skip_hidden_column,
model_extra_derives: bonus_derive(model_extra_derives),
model_extra_attributes: bonus_attributes(model_extra_attributes),
enum_extra_derives: bonus_derive(enum_extra_derives),
seaography,
}
}
Expand All @@ -168,9 +171,11 @@ impl EntityWriter {
files.push(self.write_index_file(context.lib));
files.push(self.write_prelude());
if !self.enums.is_empty() {
files.push(
self.write_sea_orm_active_enums(&context.with_serde, context.with_copy_enums),
);
files.push(self.write_sea_orm_active_enums(
&context.with_serde,
context.with_copy_enums,
&context.enum_extra_derives,
));
}
WriterOutput { files }
}
Expand Down Expand Up @@ -283,6 +288,7 @@ impl EntityWriter {
&self,
with_serde: &WithSerde,
with_copy_enums: bool,
extra_derives: &TokenStream,
) -> OutputFile {
let mut lines = Vec::new();
Self::write_doc_comment(&mut lines);
Expand All @@ -291,7 +297,9 @@ impl EntityWriter {
let code_blocks = self
.enums
.values()
.map(|active_enum| active_enum.impl_active_enum(with_serde, with_copy_enums))
.map(|active_enum| {
active_enum.impl_active_enum(with_serde, with_copy_enums, extra_derives)
})
.collect();
Self::write(&mut lines, code_blocks);
OutputFile {
Expand Down

0 comments on commit 0dbfb42

Please sign in to comment.