use std::fmt;
use std::sync::OnceLock;
pub const NOME_DA_VARIAVEL_DO_AMBIENTE: &str = "AMBIENTE";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Ambiente {
Localhost,
Sandbox,
Production,
}
impl Ambiente {
pub const TODOS_OS_AMBIENTES: [Ambiente; 3] = [Ambiente::Localhost, Ambiente::Sandbox, Ambiente::Production];
pub fn interpretar_nome_do_ambiente(nome_do_ambiente: &str) -> Option<Ambiente> {
match nome_do_ambiente.trim().to_ascii_uppercase().as_str() {
"LOCALHOST" => Some(Ambiente::Localhost),
"SANDBOX" => Some(Ambiente::Sandbox),
"PRODUCTION" => Some(Ambiente::Production),
_ => None,
}
}
pub fn nome_do_ambiente(&self) -> &'static str {
match self {
Ambiente::Localhost => "LOCALHOST",
Ambiente::Sandbox => "SANDBOX",
Ambiente::Production => "PRODUCTION",
}
}
}
impl fmt::Display for Ambiente {
fn fmt(&self, formatador: &mut fmt::Formatter<'_>) -> fmt::Result {
formatador.write_str(self.nome_do_ambiente())
}
}
static AMBIENTE_ATUAL: OnceLock<Ambiente> = OnceLock::new();
pub fn definir_ambiente_atual_pelo_codigo(ambiente: Ambiente) -> Result<(), Ambiente> {
AMBIENTE_ATUAL.set(ambiente).map_err(|_| ambiente_atual())
}
pub fn ambiente_atual() -> Ambiente {
*AMBIENTE_ATUAL.get_or_init(|| {
ler_ambiente_da_variavel_de_ambiente().unwrap_or_else(|mensagem_de_erro| panic!("termo_core: {mensagem_de_erro}"))
})
}
fn ler_ambiente_da_variavel_de_ambiente() -> Result<Ambiente, String> {
let valor_da_variavel = std::env::var(NOME_DA_VARIAVEL_DO_AMBIENTE).map_err(|_| {
format!("defina a variável {NOME_DA_VARIAVEL_DO_AMBIENTE} com LOCALHOST, SANDBOX ou PRODUCTION")
})?;
Ambiente::interpretar_nome_do_ambiente(&valor_da_variavel).ok_or_else(|| {
format!(
"a variável {NOME_DA_VARIAVEL_DO_AMBIENTE} vale \"{valor_da_variavel}\", mas só aceita LOCALHOST, SANDBOX ou PRODUCTION"
)
})
}
#[cfg(test)]
mod testes {
use super::*;
#[test]
fn interpreta_o_nome_do_ambiente_sem_diferenciar_maiusculas_e_espacos() {
assert_eq!(Ambiente::interpretar_nome_do_ambiente(" sandbox "), Some(Ambiente::Sandbox));
assert_eq!(Ambiente::interpretar_nome_do_ambiente("PRODUCTION"), Some(Ambiente::Production));
assert_eq!(Ambiente::interpretar_nome_do_ambiente("Localhost"), Some(Ambiente::Localhost));
assert_eq!(Ambiente::interpretar_nome_do_ambiente("producao"), None);
}
}