1
Fork 0
mirror of https://github.com/Steffo99/micronfig.git synced 2024-11-22 08:04:20 +00:00

Add optional and more tests

This commit is contained in:
Steffo 2024-01-04 15:30:38 +01:00
parent 3824bd2b0f
commit 8e4eedf91f
Signed by: steffo
GPG key ID: 2A24051445686895
33 changed files with 195 additions and 105 deletions

View file

@ -2,7 +2,7 @@ extern crate proc_macro;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::{quote, ToTokens}; use quote::{quote, ToTokens};
use syn::parse::{Parse, ParseStream}; use syn::parse::{Parse, ParseStream};
use syn::{Ident, parse_macro_input, Token, Type}; use syn::{Ident, parse_macro_input, Token, Type, TypePath};
use syn::punctuated::Punctuated; use syn::punctuated::Punctuated;
@ -11,6 +11,7 @@ type Config = Punctuated<ConfigItem, Token![,]>;
#[derive(Clone)] #[derive(Clone)]
struct ConfigItem { struct ConfigItem {
identifier: Ident, identifier: Ident,
optional: bool,
types: Vec<ConfigPair>, types: Vec<ConfigPair>,
} }
@ -28,28 +29,38 @@ enum Conversion {
} }
const VALID_INITIAL_TYPES: [&'static str; 2] = ["String", "std::string::String"];
impl Parse for ConfigItem { impl Parse for ConfigItem {
fn parse(input: ParseStream) -> syn::Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
let identifier = input.parse::<Ident>()?; let identifier = input.parse::<Ident>()?;
if input.lookahead1().peek(Token![:]) { let optional = input.lookahead1().peek(Token![?]);
input.parse::<Token![:]>()?; if optional {
let string_type = input.parse::<Type>()?; input.parse::<Token![?]>()
if string_type.to_token_stream().to_string() != "String" { .expect("this token to be parsed correctly, as it has been previously peeked");
return Err(syn::Error::new_spanned(string_type, "first type of a conversion chain should always be `String`"))
}
let mut types = vec![];
while let Ok(typ) = input.parse::<ConfigPair>() {
types.push(typ)
}
Ok(Self { identifier, types })
}
else {
let types = vec![];
Ok(Self { identifier, types })
} }
let types = match input.lookahead1().peek(Token![:]) {
true => {
input.parse::<Token![:]>()
.expect("this token to be parsed correctly, as it has been previously peeked");
let string_type = input.parse::<TypePath>()?;
if !VALID_INITIAL_TYPES.contains(&&*string_type.to_token_stream().to_string()) {
return Err(syn::Error::new_spanned(string_type, "first type of a conversion chain should always be `String` or `std::string::String`, type aliases are not allowed"))
}
let mut types = Vec::new();
while let Ok(typ) = input.parse::<ConfigPair>() {
types.push(typ)
}
types
},
false => Vec::new(),
};
Ok(Self { identifier, optional, types })
} }
} }
@ -95,73 +106,95 @@ pub fn config(input: TokenStream) -> TokenStream {
} }
}; };
let items = input.iter().map(|item: &ConfigItem| { let items_code = input.iter().map(|item: &ConfigItem| {
let identifier = &item.identifier; let identifier = &item.identifier;
let identifier_string = identifier.to_string(); let identifier_string = identifier.to_string();
let mut conversion_code = quote! {}; let type_final = match item.types.last() {
for ConfigPair { r#type, conversion } in item.types.iter() {
let typ = r#type;
conversion_code = match conversion {
Conversion::From => quote! {
#conversion_code
let value: Option<#typ> = value.map(Into::into);
},
Conversion::TryFrom => quote! {
#conversion_code
let value: Option<#typ> = value
.map(|v| v.try_into())
.map(|v| v.expect(&format!("to be able to convert {}", #identifier_string))
);
},
Conversion::FromStr => quote! {
#conversion_code
let value: Option<#typ> = value
.map(|v| v.parse())
.map(|v| v.expect(&format!("to be able to parse {}", #identifier_string))
);
},
};
};
let last_type = match item.types.last() {
Some(pair) => { Some(pair) => {
let typ = pair.r#type.clone(); let typ = pair.r#type.clone();
quote! { #typ } quote! { #typ }
}, },
None => { None => {
quote! { String } quote! { std::string::String }
},
};
let type_final_option = match item.optional {
true => quote! { std::option::Option<#type_final> },
false => quote! { #type_final },
};
let conversion_code = item.types.iter().map(
|ConfigPair { r#type, conversion }| {
let typ = r#type;
match (conversion, item.optional) {
(Conversion::From, true) => quote! {
let value: Option<#typ> = value
.map(std::convert::Into::into);
},
(Conversion::TryFrom, true) => quote! {
let value: Option<#typ> = value
.map(std::convert::TryInto::try_into)
.map(|v| v.expect(&format!("to be able to convert {}", #identifier_string))
);
},
(Conversion::FromStr, true) => quote! {
let value: Option<#typ> = value
.map(str::parse)
.map(|v| v.expect(&format!("to be able to parse {}", #identifier_string))
);
},
(Conversion::From, false) => quote! {
let value: #typ = value
.into();
},
(Conversion::TryFrom, false) => quote! {
let value: #typ = value
.try_into()
.expect(&format!("to be able to convert {}", #identifier_string));
},
(Conversion::FromStr, false) => quote! {
let value: #typ = value
.parse()
.expect(&format!("to be able to parse {}", #identifier_string));
},
}
}
).reduce(|acc, new| {
quote! { #acc #new }
});
let require_code = match item.optional {
true => quote! {},
false => quote! {
let value: String = value
.expect(&format!("to be have {} set", #identifier_string));
}, },
}; };
quote! { quote! {
#[allow(non_snake_case)] #[allow(non_snake_case)]
mod #identifier { mod #identifier {
pub(super) static _lock: std::sync::OnceLock<Option<#last_type>> = std::sync::OnceLock::new(); pub(super) static _lock: std::sync::OnceLock<#type_final_option> = std::sync::OnceLock::new();
} }
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub(crate) fn #identifier() -> &'static Option<#last_type> { pub(crate) fn #identifier() -> &'static #type_final_option {
#identifier::_lock.get_or_init(|| { #identifier::_lock.get_or_init(|| {
let key: std::ffi::OsString = #identifier_string.into(); let key: std::ffi::OsString = #identifier_string.into();
let value: Option<String> = _cache().get(&key); let value: Option<String> = _cache().get(&key);
#require_code
#conversion_code #conversion_code
value value
}) })
} }
} }
}).reduce(|acc, new| {
quote! { #acc #new }
}); });
let mut items_code = quote! {};
for code in items {
items_code = quote! {
#items_code
#code
};
}
let quote = quote! { let quote = quote! {
#cache_code #cache_code
#items_code #items_code

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "1");
assert_eq!(GARASAUTO(), &1u8);
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "1");
assert_eq!(GARASAUTO(), &1u128);
} }

View file

@ -0,0 +1,32 @@
use std::str::FromStr;
#[derive(Debug)]
pub struct CommaSeparatedStrings(Vec<String>);
impl FromStr for CommaSeparatedStrings {
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self(s.split(',').collect())
}
}
micronfig::config! {
DATA_DRAGON_LOCALE: String,
DATA_DRAGON_SET_CODES: String > crate::CommaSeparatedStrings,
POROXY_KEY: String,
POROXY_SALT: String,
SERENITY_DEV_GUILD_ID?: String > u64,
}
fn main() {
std::env::set_var("DATA_DRAGON_LOCALE", "it_IT");
std::env::set_var("DATA_DRAGON_SET_CODES", "set1,set2abc");
std::env::set_var("POROXY_KEY", "abcdef");
std::env::set_var("POROXY_SALT", "abcdef");
std::env::remove_var("SERENITY_DEV_GUILD_ID");
assert_eq!(DATA_DRAGON_LOCALE(), "it_IT");
assert_eq!(DATA_DRAGON_SET_CODES(), CommaSeparatedStrings(vec!["set1", "set2abc"]));
assert_eq!(POROXY_KEY, "abcdef");
assert_eq!(POROXY_SALT, "abcdef");
assert_eq!(SERENITY_DEV_GUILD_ID, &None);
}

View file

@ -1,4 +1,4 @@
#[derive(std::fmt::Debug)] #[derive(std::fmt::Debug, Eq)]
struct MyCustomStruct(String); struct MyCustomStruct(String);
impl From<String> for MyCustomStruct { impl From<String> for MyCustomStruct {
@ -12,5 +12,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "baba");
assert_eq!(GARASAUTO(), &MyCustomStruct("baba"));
} }

View file

@ -1,4 +1,4 @@
#[derive(std::fmt::Debug)] #[derive(std::fmt::Debug, Eq)]
struct MyCustomStruct(String); struct MyCustomStruct(String);
impl std::str::FromStr for MyCustomStruct { impl std::str::FromStr for MyCustomStruct {
@ -14,5 +14,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "keke");
assert_eq!(GARASAUTO(), &MyCustomStruct("keke"));
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "-1");
assert_eq!(GARASAUTO(), &(-1i64));
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "./garas");
assert_eq!(GARASAUTO(), std::path::PathBuf::from("./garas"));
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "1");
assert_eq!(GARASAUTO(), &1u64);
} }

View file

@ -1,9 +0,0 @@
micronfig::config! {
GARAS: String,
AUTO: String,
BUS: String,
}
fn main() {
println!("{:?} {:?} {:?}", GARAS(), AUTO(), BUS())
}

View file

@ -5,5 +5,10 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?} {:?} {:?}", GARAS(), AUTO(), BUS()) std::env::set_var("GARAS", "garas");
std::env::set_var("AUTO", "auto");
std::env::set_var("BUS", "bus");
assert_eq!(GARAS(), "garas");
assert_eq!(AUTO(), "auto");
assert_eq!(BUS(), "bus");
} }

View file

@ -5,5 +5,10 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?} {:?} {:?}", GARAS(), AUTO(), BUS()) std::env::set_var("GARAS", "garas");
std::env::set_var("AUTO", "auto");
std::env::set_var("BUS", "bus");
assert_eq!(GARAS(), "garas");
assert_eq!(AUTO(), "auto");
assert_eq!(BUS(), "bus");
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "sagramoto");
assert_eq!(GARASAUTO(), "sagramoto");
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "fieraereo");
assert_eq!(GARASAUTO(), "fieraereo");
} }

View file

@ -1,4 +1,4 @@
#[derive(std::fmt::Debug)] #[derive(std::fmt::Debug, Eq)]
struct MyCustomStruct(String); struct MyCustomStruct(String);
impl std::convert::TryFrom<String> for MyCustomStruct { impl std::convert::TryFrom<String> for MyCustomStruct {
@ -14,5 +14,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "me");
assert_eq!(GARASAUTO(), &MyCustomStruct("me"));
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "1");
println!("{:#?}", GARASAUTO());
} }

View file

@ -5,7 +5,7 @@ error: expected `,`
| ^ | ^
error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope
--> tests/sources/wrong_conversion_longfatarrow.rs:6:19 --> tests/sources/wrong_conversion_longfatarrow.rs:7:19
| |
6 | println!("{:?}", GARASAUTO()) 7 | println!("{:?}", GARASAUTO())
| ^^^^^^^^^ not found in this scope | ^^^^^^^^^ not found in this scope

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "1");
println!("{:#?}", GARASAUTO());
} }

View file

@ -5,7 +5,7 @@ error: expected `,`
| ^ | ^
error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope
--> tests/sources/wrong_conversion_longthinarrow.rs:6:19 --> tests/sources/wrong_conversion_longthinarrow.rs:7:19
| |
6 | println!("{:?}", GARASAUTO()) 7 | println!("{:?}", GARASAUTO())
| ^^^^^^^^^ not found in this scope | ^^^^^^^^^ not found in this scope

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "1");
println!("{:#?}", GARASAUTO());
} }

View file

@ -5,7 +5,7 @@ error: expected `,`
| ^ | ^
error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope
--> tests/sources/wrong_conversion_tildearrow.rs:6:19 --> tests/sources/wrong_conversion_tildearrow.rs:7:19
| |
6 | println!("{:?}", GARASAUTO()) 7 | println!("{:?}", GARASAUTO())
| ^^^^^^^^^ not found in this scope | ^^^^^^^^^ not found in this scope

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "1");
println!("{:#?}", GARASAUTO())
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "!");
println!("{:#?}", GARASAUTO());
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "1");
println!("{:#?}", GARASAUTO());
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "-1");
println!("{:#?}", GARASAUTO());
} }

View file

@ -1,11 +1,11 @@
error: first type of a conversion chain should always be `String` error: first type of a conversion chain should always be `String` or `std::string::String`, type aliases are not allowed
--> tests/sources/wrong_start.rs:2:13 --> tests/sources/wrong_start.rs:2:13
| |
2 | GARASAUTO: i64, 2 | GARASAUTO: i64,
| ^^^ | ^^^
error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope
--> tests/sources/wrong_start.rs:6:19 --> tests/sources/wrong_start.rs:7:19
| |
6 | println!("{:?}", GARASAUTO()) 7 | println!("{:?}", GARASAUTO())
| ^^^^^^^^^ not found in this scope | ^^^^^^^^^ not found in this scope

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "garasauto");
println!("{:#?}", GARASAUTO());
} }

View file

@ -1,11 +1,11 @@
error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime error: expected identifier
--> tests/sources/wrong_syntax_colon.rs:2:13 --> tests/sources/wrong_syntax_colon.rs:2:13
| |
2 | GARASAUTO: , 2 | GARASAUTO: ,
| ^ | ^
error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope
--> tests/sources/wrong_syntax_colon.rs:6:19 --> tests/sources/wrong_syntax_colon.rs:7:19
| |
6 | println!("{:?}", GARASAUTO()) 7 | println!("{:?}", GARASAUTO())
| ^^^^^^^^^ not found in this scope | ^^^^^^^^^ not found in this scope

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "garasauto");
println!("{:#?}", GARASAUTO());
} }

View file

@ -5,7 +5,7 @@ error: expected `,`
| ^^^^^^ | ^^^^^^
error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope error[E0425]: cannot find function, tuple struct or tuple variant `GARASAUTO` in this scope
--> tests/sources/wrong_syntax_type.rs:6:19 --> tests/sources/wrong_syntax_type.rs:7:19
| |
6 | println!("{:?}", GARASAUTO()) 7 | println!("{:?}", GARASAUTO())
| ^^^^^^^^^ not found in this scope | ^^^^^^^^^ not found in this scope

View file

@ -5,5 +5,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "./auto");
println!("{:#?}", GARASAUTO());
} }

View file

@ -3,5 +3,6 @@ micronfig::config! {
} }
fn main() { fn main() {
println!("{:?}", GARASAUTO()) std::env::set_var("GARASAUTO", "./bus");
println!("{:#?}", GARASAUTO());
} }

View file

@ -19,15 +19,18 @@ macro_rules! fail {
pass!(chain_single_down); pass!(chain_single_down);
pass!(chain_single_up); pass!(chain_single_up);
pass!(empty); pass!(empty);
pass!(example_patchedporobot);
pass!(from_single_custom); pass!(from_single_custom);
pass!(parse_single_custom); pass!(parse_single_custom);
pass!(parse_single_i64); pass!(parse_single_i64);
pass!(parse_single_pathbuf); pass!(parse_single_pathbuf);
pass!(parse_single_u64); pass!(parse_single_u64);
pass!(parse_single_u64_optional);
pass!(string_multi_explicit); pass!(string_multi_explicit);
pass!(string_multi_implicit); pass!(string_multi_implicit);
pass!(string_multi_mixed); pass!(string_multi_mixed);
pass!(string_single_explicit); pass!(string_single_explicit);
pass!(string_single_expliciter);
pass!(string_single_implicit); pass!(string_single_implicit);
pass!(tryfrom_single_custom); pass!(tryfrom_single_custom);