Skip to main content

doido_cache/
environment.rs

1//! Runtime environment selection, driven by the `DOIDO_ENV` variable.
2//!
3//! Mirrors `doido-controller`'s environment so the cache layer can resolve the
4//! same `config/<env>.yml` file without depending on the controller crate.
5
6/// The application environment. Selects which `config/<env>.yml` file is read.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Environment {
9    Development,
10    Test,
11    Production,
12}
13
14impl Environment {
15    /// Reads the current environment from `DOIDO_ENV`.
16    ///
17    /// Recognized values are `development`, `test`, and `production`. An unset
18    /// or unrecognized value falls back to [`Environment::Development`].
19    pub fn get_env() -> Environment {
20        match std::env::var("DOIDO_ENV").as_deref() {
21            Ok("production") => Environment::Production,
22            Ok("test") => Environment::Test,
23            _ => Environment::Development,
24        }
25    }
26
27    /// Lowercase name used for the `config/<env>.yml` file and for display.
28    pub fn as_str(&self) -> &'static str {
29        match self {
30            Environment::Development => "development",
31            Environment::Test => "test",
32            Environment::Production => "production",
33        }
34    }
35}
36
37impl std::fmt::Display for Environment {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.write_str(self.as_str())
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn as_str_maps_each_variant() {
49        assert_eq!(Environment::Development.as_str(), "development");
50        assert_eq!(Environment::Test.as_str(), "test");
51        assert_eq!(Environment::Production.as_str(), "production");
52    }
53
54    #[test]
55    fn display_matches_as_str() {
56        assert_eq!(Environment::Production.to_string(), "production");
57    }
58}