mikros_macros/
lib.rs

1mod env;
2mod lifecycle;
3
4use proc_macro::TokenStream;
5use syn::{parse_macro_input, DeriveInput};
6
7/// A macro to add a derive functionality that allows to initialize structure
8/// members with values from environment variables.
9///
10/// `Env` macro provides a struct member attribute `env` with the following
11/// sub-attributes:
12///
13/// - variable: required attribute which sets the variable name that will be
14///             used to set the member.
15/// - default: required attribute to set the default value in case the variable
16///             is not found.
17/// ```ignore
18/// use mikros_macros::Env;
19///
20/// #[derive(Env, Debug)]
21/// #[env(suffix_delimiter = "_")]
22/// pub struct Example {
23///     #[env(variable = "VAR_NAME", default = "value")]
24///     name: String,
25///
26///     #[env(variable = "VAR_AGE", default = "42")]
27///     age: i32,
28///
29///     #[env(variable = "VAR_OPTIONAL", default = "None")]
30///     opt: Option<String>,
31///
32///     // A member that won't be loaded from environment values
33///     no_env_loaded: bool,
34/// }
35///
36/// pub fn foo() {
37///     let e = Example::from_env();
38///     println!("{e}");
39/// }
40/// ```
41#[proc_macro_derive(Env, attributes(env))]
42pub fn derive_env_impl(input: TokenStream) -> TokenStream {
43    let input = parse_macro_input!(input as DeriveInput);
44    let gen = env::generate(input);
45    TokenStream::from(gen)
46}
47
48/// Lifecycle implements the `mikros::service::lifecycle::Lifecycle` trait for
49/// a given structure.
50#[proc_macro_derive(Lifecycle)]
51pub fn derive_lifecycle_impl(input: TokenStream) -> TokenStream {
52    let input = parse_macro_input!(input as DeriveInput);
53    let gen = lifecycle::generate(input);
54    TokenStream::from(gen)
55}