server_env_config/
env.rs

1//! The [`Environment`] enum represents possible deployment environments for an application.
2
3use anyhow::{Context, Result};
4use std::env;
5use std::fmt::Debug;
6use std::str::FromStr;
7use strum_macros::{Display, EnumString};
8
9/// Possible deployment environments for an application.
10#[derive(Debug, Default, Display, PartialEq, EnumString, Clone)]
11#[strum(serialize_all = "snake_case")]
12pub enum Environment {
13    #[default]
14    Local,
15    Test,
16    Stage,
17    Production,
18}
19
20impl Environment {
21    /// Get the value from the environment variable `APP_ENV`.
22    /// It raise an error if the string doesn't match a possible environment.
23    /// # Examples
24    /// ```
25    /// use std::env;
26    /// use server_env_config::env::Environment;
27    ///
28    /// env::set_var("APP_ENV", "production");
29    /// assert!(matches!(Environment::init(), Ok(Environment::Production)));
30    /// env::set_var("APP_ENV", "Not a environment");
31    /// assert!(Environment::init().is_err());
32    /// env::remove_var("APP_ENV"); // if not set, local environment is the default
33    /// assert!(matches!(Environment::init(), Ok(Environment::Local)));
34    /// ```
35    pub fn init() -> Result<Self> {
36        let app_env = env::var("APP_ENV");
37        match app_env {
38            Err(_) => Ok(Environment::default()),
39            Ok(env) => Environment::from_str(env.as_str())
40                .with_context(|| format!("APP_ENV invalid value \"{env}\"")),
41        }
42    }
43}