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
#![cfg_attr(feature = "doc", feature(external_doc))]
#![doc(html_logo_url = "https://reign.rs/images/media/reign.png")]
#![doc(html_root_url = "https://docs.rs/reign_boot/0.2.1")]
#![cfg_attr(feature = "doc", doc(include = "../README.md"))]

use dotenv::from_filename;
use serde::Deserialize;
use std::env;

// TODO:(config) Have a config struct so that it loads envs and all panics happen during boot

fn build_env_file_heirarchy(environment: String) -> Vec<String> {
    let mut heirarchy: Vec<String> = environment.split('.').map(String::from).collect();
    let length = heirarchy.len();

    for i in 0..length {
        for j in i + 1..length {
            heirarchy[i] = format!("{}.{}", heirarchy[j], heirarchy[i]);
        }
    }

    heirarchy.reverse();
    heirarchy
}

fn load_env_files() {
    let environment = env::var("REIGN_ENV").unwrap_or_else(|_| "development".to_string());

    from_filename(".env").ok();
    from_filename(".env.local").ok();

    for item in build_env_file_heirarchy(environment) {
        from_filename(&format!(".env.{}", item)).ok();
        from_filename(&format!(".env.{}.local", item)).ok();
    }
}

pub fn boot<T>() -> T
where
    T: for<'de> Deserialize<'de>,
{
    load_env_files();

    // TODO:(log) Allow custom loggers by adding an option to exclude this call
    env_logger::from_env(env_logger::Env::default().default_filter_or("info"))
        .format_timestamp(None)
        .init();

    // TODO:(env) default value
    envy::from_env::<T>().unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_env_file_heirarchy() {
        assert_eq!(
            build_env_file_heirarchy(String::from("joe.qa.staging")),
            ["staging", "staging.qa", "staging.qa.joe"]
        );
    }
}