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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//! Environment variable struct for better env management.
//!
//! Currently it's very opinionated and depends on having
//! `std` as it's fields defaults to `String` type, and
//! uses `std::env::var(<key>)`.
//!
//! You are also forced to specify a default-value for the
//! `ENV_VARIABLE` because IMHO that's important.
//!
//! Also lastly we just capitalize the field name for
//! env_variable name so make sure to set those up correctly.
//!
//! Key roadmap goal is,
//! Support custom aliases for env_var key.
//!
//! Note we don't support boolean or enum based env
//! variables yet, I hope to shortly but I don't really
//! need that so haven't thought about it much yet!
//!
//! ### Usage
//! ```rust
//! use env_struct::env_struct;
//! env_struct!{
//!     #[derive(Debug)]
//!     pub struct DummyEnv {
//!         pub path_to_something = "/path_to_something".into(),
//!         pub config_path = "/folder/config_path.toml".into(),
//!     }
//! };
//! ```

/// Macro for writing a `env_struct`
#[macro_export]
macro_rules! env_struct {
    (
        $(#[$outer:meta])*
        $vis:vis struct $struct_name:ident {
            $(
                $(#[$outer_field:meta])*
                $vis_ident:vis $field:ident = $fieldDef:expr,
            )*
        }
    ) => {
        $(#[$outer])*
        $vis struct $struct_name {
            $(
                $(#[$outer_field])*
                $vis_ident $field: String,
            )*
        }
        impl $struct_name {
            pub fn load_from_env() -> Self {
                let mut env = Self::default();
                $(
                    let _field = stringify!($field)
                            .chars()
                            .map(|x| char::to_ascii_uppercase(&x))
                            .collect::<String>();
                    if let Ok(s) = std::env::var(&_field) {
                        env.$field = s;
                    } else {
                        #[cfg(feature = "logging")]
                        {
                            use log;
                            let def: String = $fieldDef;
                            log::warn!("Failed to find `{}` in env, defaulting to {:?}", _field, def);
                        }
                    }
                )*
                env
            }
        }
        impl Default for $struct_name {
            fn default() -> Self {
                Self {
                    $(
                        $field: $fieldDef,
                    )*
                }
            }
        }
    };
    (
        $(#[$outer:meta])*
        $vis:vis struct $struct_name:ident {
            $(
                $(#[$outer_field:meta])*
                $vis_ident:vis $field:ident,
            )*
        }
    ) => {
        $(#[$outer])*
        $vis struct $struct_name {
            $(
                $(#[$outer_field])*
                $vis_ident $field: String,
            )*
        }
        impl $struct_name {
            pub fn try_load_from_env() -> Result<Self, String> {
                Ok(Self {
                    $(
                        $field: std::env::var(
                            stringify!($field)
                                .chars()
                                .map(|x| char::to_ascii_uppercase(&x))
                                .collect::<String>(),
                        ).map_err(|_| {
                            format!(
                                "Environment Variable `{}` Not Present!",
                                stringify!($field)
                                    .chars()
                                    .map(|x| char::to_ascii_uppercase(&x))
                                    .collect::<String>()
                            )
                        })?,
                    )*
                })
            }
        }
    };
}

#[cfg(test)]
mod tests {

    struct EnvTemp {
        flag: &'static str,
        original_content: Option<String>,
    }
    impl EnvTemp {
        fn set_var(flag: &'static str, val: &'static str) -> EnvTemp {
            let env = EnvTemp {
                flag,
                original_content: std::env::var(flag).ok(),
            };
            std::env::set_var(flag, val);
            env
        }
    }
    impl Drop for EnvTemp {
        fn drop(&mut self) {
            // reset_var
            if let Some(og) = &self.original_content {
                std::env::set_var(self.flag, og);
            } else {
                std::env::remove_var(self.flag);
            }
        }
    }

    #[test]
    fn test_with_default() {
        let hello_world = "Hello, world!";
        let temp_env = [EnvTemp::set_var("HELLO_NOT_MY_WORLD", hello_world)];
        env_struct! {
            /// Env Items
            struct Env {
                /// Hello World
                hello_not_my_world = "hello".into(),
                hello_some_world = "Hello, Some World!".into(),
            }
        }
        let env = Env::load_from_env();
        assert_eq!(env.hello_not_my_world, hello_world);
        assert_eq!(env.hello_some_world, "Hello, Some World!");
        drop(temp_env); // drop would be called without this as well
    }

    #[test]
    fn test_no_defaults_succeed() {
        let hello_sam = "Hello, Sam!";
        let welp_sam = "Welp, Sam!";
        let temp_env = [
            EnvTemp::set_var("HELLO_WORLD", hello_sam),
            EnvTemp::set_var("WELP_MY_WORLD", welp_sam),
        ];
        env_struct! {
            /// Env Items
            struct Env2 {
                /// Hello World
                hello_world,
                welp_my_world,
            }
        }
        let env = Env2::try_load_from_env().unwrap();
        assert_eq!(env.hello_world, hello_sam);
        assert_eq!(env.welp_my_world, welp_sam);
        drop(temp_env); // drop would be called without this as well
    }

    #[test]
    #[should_panic]
    fn test_no_defaults_failed() {
        let welp_sam = "Welp, Sam!";
        let temp_env = [EnvTemp::set_var("HELL_TO_WORLD", welp_sam)];
        env_struct! {
            struct Env {
                hell_to_world,
                welp_world,
            }
        }
        let env = Env::try_load_from_env().unwrap();
        _ = env.hell_to_world;
        _ = env.welp_world;
        drop(temp_env); // drop would be called without this as well
    }
}