ayun_environment/
lib.rs

1mod instance;
2
3use ayun_core::{Error, Result};
4use std::str::FromStr;
5
6#[derive(Debug, Default, Clone)]
7pub enum Environment {
8    #[default]
9    Development,
10    Production,
11    Testing,
12    Any(String),
13}
14
15impl Environment {
16    fn try_from_args() -> Result<Self, Error> {
17        let args: Vec<String> = std::env::args()
18            .filter(|arg| arg.starts_with("--env="))
19            .map(|arg| arg.replace("--env=", ""))
20            .collect();
21
22        let env = args
23            .first()
24            .map(|arg| arg.to_owned().into())
25            .ok_or(Error::InvalidArgument(
26                "No environment specified".to_string(),
27            ))?;
28
29        Ok(env)
30    }
31
32    fn try_from_assertion() -> Result<Self, Error> {
33        match cfg!(debug_assertions) {
34            true => Ok(Self::Development),
35            false => Ok(Self::Production),
36        }
37    }
38}
39
40impl Environment {
41    pub fn production(&self) -> bool {
42        matches!(self, Self::Production)
43    }
44    pub fn development(&self) -> bool {
45        matches!(self, Self::Development)
46    }
47    pub fn testing(&self) -> bool {
48        matches!(self, Self::Testing)
49    }
50}
51
52impl From<String> for Environment {
53    fn from(env: String) -> Self {
54        Self::from_str(&env).unwrap_or(Self::Any(env))
55    }
56}
57
58impl FromStr for Environment {
59    type Err = &'static str;
60
61    fn from_str(input: &str) -> Result<Self, Self::Err> {
62        match input {
63            "production" => Ok(Self::Production),
64            "development" => Ok(Self::Development),
65            "test" => Ok(Self::Testing),
66            s => Ok(Self::Any(s.to_string())),
67        }
68    }
69}
70
71impl std::fmt::Display for Environment {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        match self {
74            Environment::Development => "development".fmt(f),
75            Environment::Production => "production".fmt(f),
76            Environment::Testing => "testing".fmt(f),
77            Environment::Any(s) => s.fmt(f),
78        }
79    }
80}