1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use proc_macro::TokenStream;
use quote::quote;
use syn;

#[cfg(feature="file_loader")]
fn impl_configuration_trait(name: &syn::Ident) -> proc_macro2::TokenStream {
    quote! {
        impl Configuration for #name where Self: serde::de::DeserializeOwned {
            fn load() -> #name {
                let mut config = #name::default();
                config.load_from_env();
                config
            }

            fn load_from_file<P: AsRef<std::path::Path>>(p: P)
                                                         -> Result<#name, ConfigurationError> {
                use std::io::prelude::*;

                let mut file = std::fs::File::open(p)
                    .map_err(|_| ConfigurationError("Could not open TOML config file."))?;

                let mut contents = String::new();
                file.read_to_string(&mut contents)
                    .map_err(|_| ConfigurationError("Could not read TOML config file contents."))?;

                let mut c : #name = toml::from_str(&contents)
                    .map_err(|_| ConfigurationError("Could not deserialize TOML config file."))?;

                c.load_from_env();

                Ok(c)
            }
        }
    }
}

#[cfg(not(feature="file_loader"))]
fn impl_configuration_trait(name: &syn::Ident) -> proc_macro2::TokenStream {
    quote! {
        impl Configuration for #name {
            fn load() -> #name {
                let mut config = #name::default();
                config.load_from_env();
                config
            }

            fn load_from_file<P: AsRef<std::path::Path>>(p: P) -> Result<#name, ConfigurationError> {
                Err(ConfigurationError("load_from_file requires the 'file_loader' feature"))
            }
        }
    }
}

fn impl_configurs(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;

    let mut defaults = Vec::new();
    let mut envs = Vec::new();

    if let syn::Data::Struct(ref st) = ast.data {
        for fld in &st.fields {
            for attr in &fld.attrs {
                if let Ok(
                    syn::Meta::NameValue(
                        syn::MetaNameValue { path, lit: syn::Lit::Str(lit_str), .. }
                    )
                ) = attr.parse_meta() {
                    let identifier = fld.ident.as_ref().unwrap().to_owned();
                    let attribute_name = path.get_ident().unwrap().to_string();
                    let value = lit_str.to_owned();

                    if attribute_name == "default" {
                        defaults.push(quote! {
                            #identifier: #value.parse().expect(&format!(
                                "Could not parse default value for {}", stringify!(#identifier))
                            ),
                        });
                    } else if attribute_name == "env" {
                        envs.push(quote! {
                            if let Ok(val) = std::env::var(#value) {
                                self.#identifier = val.parse().expect(
                                    &format!("Could not parse '{}'", val)
                                );
                            }
                        });
                    }
                } else if let Ok(syn::Meta::Path(path)) = attr.parse_meta() {
                    let identifier = fld.ident.as_ref().unwrap().to_owned();
                    let attribute_name = path.get_ident().unwrap().to_string();
                    let ty = &fld.ty;

                    if attribute_name == "default" {
                        defaults.push(quote! {
                            #identifier: #ty::default(),
                        });

                        envs.push(quote! {
                            self.#identifier.load_from_env();
                        });
                    }
                }
            }
        }
    }

    let configuration_impl = impl_configuration_trait(&name);

    let gen = quote! {
        impl LoadableFromEnvironment for #name {
            fn load_from_env(&mut self) -> () {
                #(#envs)*
            }
        }

        impl std::default::Default for #name {
            fn default() -> Self {
                #name {
                    #(#defaults)*
                }
            }
        }

        #configuration_impl
    };

    gen.into()
}

#[proc_macro_derive(Configuration, attributes(env, default))]
pub fn configurs_derive(input: TokenStream) -> TokenStream {
    // Construct a representation of Rust code as a syntax tree
    // that we can manipulate
    let ast = syn::parse(input).unwrap();

    // Build the trait implementation
    impl_configurs(&ast)
}

#[cfg(test)]
mod tests {}