ayun_environment/
lib.rs

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
mod instance;

use ayun_core::{Error, Result};
use std::str::FromStr;

#[derive(Debug, Default, Clone)]
pub enum Environment {
    #[default]
    Development,
    Production,
    Testing,
    Any(String),
}

impl Environment {
    fn try_from_args() -> Result<Self, Error> {
        let args: Vec<String> = std::env::args()
            .filter(|arg| arg.starts_with("--env="))
            .map(|arg| arg.replace("--env=", ""))
            .collect();

        let env = args
            .first()
            .map(|arg| arg.to_owned().into())
            .ok_or(Error::InvalidArgument(
                "No environment specified".to_string(),
            ))?;

        Ok(env)
    }

    fn try_from_assertion() -> Result<Self, Error> {
        match cfg!(debug_assertions) {
            true => Ok(Self::Development),
            false => Ok(Self::Production),
        }
    }
}

impl Environment {
    pub fn production(&self) -> bool {
        matches!(self, Self::Production)
    }
    pub fn development(&self) -> bool {
        matches!(self, Self::Development)
    }
    pub fn testing(&self) -> bool {
        matches!(self, Self::Testing)
    }
}

impl From<String> for Environment {
    fn from(env: String) -> Self {
        Self::from_str(&env).unwrap_or(Self::Any(env))
    }
}

impl FromStr for Environment {
    type Err = &'static str;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "production" => Ok(Self::Production),
            "development" => Ok(Self::Development),
            "test" => Ok(Self::Testing),
            s => Ok(Self::Any(s.to_string())),
        }
    }
}

impl std::fmt::Display for Environment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Environment::Development => "development".fmt(f),
            Environment::Production => "production".fmt(f),
            Environment::Testing => "testing".fmt(f),
            Environment::Any(s) => s.fmt(f),
        }
    }
}