Skip to content

Commit

Permalink
support skip generate enum variant
Browse files Browse the repository at this point in the history
  • Loading branch information
cksac committed Sep 25, 2024
1 parent c696f46 commit 1de36a5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
14 changes: 13 additions & 1 deletion dummy_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@ use proc_macro::TokenStream;
#[darling(from_ident, attributes(dummy))]
struct DummyVariant {
ident: Ident,
#[darling(default)]
skip: bool,
fields: darling::ast::Fields<DummyField>,
}

impl From<Ident> for DummyVariant {
fn from(ident: Ident) -> Self {
DummyVariant {
ident,
skip: false,
fields: darling::ast::Style::Unit.into(),
}
}
Expand Down Expand Up @@ -118,11 +121,15 @@ pub fn derive_dummy(input: TokenStream) -> TokenStream {
darling::ast::Data::Enum(variants) => {
let variant_count = variants.len();
if variant_count > 0 {
let mut variant_opts = Vec::new();
let match_statements: Vec<_> = variants
.iter()
.enumerate()
.map(|(i, f)| {
let variant_name = &f.ident;
if !f.skip {
variant_opts.push(i);
}
match f.fields.style {
ast::Style::Unit => {
quote! {
Expand Down Expand Up @@ -174,10 +181,15 @@ pub fn derive_dummy(input: TokenStream) -> TokenStream {
})
.collect();

if variant_opts.is_empty() {
panic!("all variants are skipped");
}

let impl_dummy = quote! {
impl #impl_generics ::fake::Dummy<::fake::Faker> for #receiver_name #ty_generics #where_clause {
fn dummy_with_rng<R: ::fake::Rng + ?Sized>(_: &::fake::Faker, rng: &mut R) -> Self {
match rng.gen_range(0..#variant_count) {
let options = [#(#variant_opts),*];
match rand::seq::SliceRandom::choose(options.as_ref(), rng).unwrap() {
#(#match_statements)*
_ => {
unreachable!()
Expand Down
1 change: 1 addition & 0 deletions fake/examples/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub struct Item {
#[allow(dead_code)]
#[derive(Debug, Dummy)]
enum Message {
#[dummy(skip)]
Quit,
Move {
#[dummy(faker = "1..100")]
Expand Down

0 comments on commit 1de36a5

Please sign in to comment.