(codegen) Improve enum field name generation
Introduce a to_upper_snake_case() helper to properly convert enum names to GraphQL compatible names. Previously, "SomeEnum" would be converted to "SOMEENUM" and not "SOME_ENUM".
This commit is contained in:
parent
f858f416b8
commit
6ff3f1fba4
2 changed files with 36 additions and 1 deletions
juniper_codegen/src
|
@ -124,7 +124,7 @@ pub fn impl_enum(ast: &syn::DeriveInput) -> Tokens {
|
||||||
// Build value.
|
// Build value.
|
||||||
let name = var_attrs
|
let name = var_attrs
|
||||||
.name
|
.name
|
||||||
.unwrap_or(variant.ident.as_ref().to_uppercase());
|
.unwrap_or(::util::to_upper_snake_case(variant.ident.as_ref()));
|
||||||
let descr = match var_attrs.description {
|
let descr = match var_attrs.description {
|
||||||
Some(s) => quote!{ Some(#s.to_string()) },
|
Some(s) => quote!{ Some(#s.to_string()) },
|
||||||
None => quote!{ None },
|
None => quote!{ None },
|
||||||
|
|
|
@ -80,3 +80,38 @@ fn test_to_camel_case() {
|
||||||
assert_eq!(&to_camel_case("a")[..], "a");
|
assert_eq!(&to_camel_case("a")[..], "a");
|
||||||
assert_eq!(&to_camel_case("")[..], "");
|
assert_eq!(&to_camel_case("")[..], "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn to_upper_snake_case(s: &str) -> String {
|
||||||
|
let mut last_lower = false;
|
||||||
|
let mut upper = String::new();
|
||||||
|
for c in s.chars() {
|
||||||
|
if c == '_' {
|
||||||
|
last_lower = false;
|
||||||
|
}
|
||||||
|
else if c.is_lowercase() {
|
||||||
|
last_lower = true;
|
||||||
|
} else if c.is_uppercase() {
|
||||||
|
if last_lower {
|
||||||
|
upper.push('_');
|
||||||
|
}
|
||||||
|
last_lower = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for u in c.to_uppercase() {
|
||||||
|
upper.push(u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
upper
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_to_upper_snake_case() {
|
||||||
|
assert_eq!(to_upper_snake_case("abc"), "ABC");
|
||||||
|
assert_eq!(to_upper_snake_case("a_bc"), "A_BC");
|
||||||
|
assert_eq!(to_upper_snake_case("ABC"), "ABC");
|
||||||
|
assert_eq!(to_upper_snake_case("A_BC"), "A_BC");
|
||||||
|
assert_eq!(to_upper_snake_case("SomeInput"), "SOME_INPUT");
|
||||||
|
assert_eq!(to_upper_snake_case("someInput"), "SOME_INPUT");
|
||||||
|
assert_eq!(to_upper_snake_case("someINpuT"), "SOME_INPU_T");
|
||||||
|
assert_eq!(to_upper_snake_case("some_INpuT"), "SOME_INPU_T");
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue