Skip to content

Commit

Permalink
Merge pull request #17 from sfackler/set-mod
Browse files Browse the repository at this point in the history
Support custom module names
  • Loading branch information
sfackler committed Jan 27, 2024
2 parents 59efa08 + c74aab9 commit 0148532
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[workspace]
resolver = "2"
members = ["staged-builder", "staged-builder-internals"]

[patch.crates-io]
Expand Down
15 changes: 11 additions & 4 deletions staged-builder-internals/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ use syn::{
/// returning the constructed value.
/// * `crate` - Indicates the path to the `staged_builder` crate root. Useful when reexporting the macro from another
/// crate. Defaults to `::staged_builder`.
/// * `mod` - The name of the submodule that will contain the generated builder types. Defaults to the struct's name
/// converted to `snake_case`.
///
/// # Field options
///
Expand Down Expand Up @@ -234,7 +236,7 @@ fn expand(input: DeriveInput) -> Result<TokenStream, Error> {
let fields = resolve_fields(&overrides, fields)?;

let vis = &input.vis;
let module_name = module_name(&input);
let module_name = module_name(&overrides, &input);

let builder_impl = builder_impl(&input, &overrides, &fields);

Expand Down Expand Up @@ -266,8 +268,11 @@ fn expand(input: DeriveInput) -> Result<TokenStream, Error> {
Ok(tokens)
}

fn module_name(input: &DeriveInput) -> Ident {
Ident::new(&input.ident.to_string().to_snake_case(), input.ident.span())
fn module_name(overrides: &StructOverrides, input: &DeriveInput) -> Ident {
overrides
.mod_
.clone()
.unwrap_or_else(|| Ident::new(&input.ident.to_string().to_snake_case(), input.ident.span()))
}

fn builder_impl(
Expand All @@ -278,7 +283,7 @@ fn builder_impl(
let name = &input.ident;
let vis = &input.vis;

let module_name = module_name(input);
let module_name = module_name(overrides, input);
let builder_name = initial_stage(fields).unwrap_or_else(final_name);
let private = overrides.private();

Expand Down Expand Up @@ -675,6 +680,8 @@ struct StructOverrides {
validate: bool,
#[struct_meta(name = "crate")]
crate_: Option<Path>,
#[struct_meta(name = "mod")]
mod_: Option<Ident>,
}

impl StructOverrides {
Expand Down
12 changes: 12 additions & 0 deletions staged-builder/tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,15 @@ fn custom() {
};
assert_eq!(actual, expected);
}

#[staged_builder]
#[builder(mod = my_custom_mod)]
struct CustomMod {
_foo: i32,
}

#[test]
fn custom_mod() {
CustomMod::builder()._foo(1).build();
my_custom_mod::Builder::default()._foo(1).build();
}

0 comments on commit 0148532

Please sign in to comment.