forked from loco-rs/loco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironment.rs
85 lines (76 loc) · 2.41 KB
/
environment.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
81
82
83
84
85
//! Defines the application environment.
//! By given the environment you can also load the application configuration
//!
//! # Example:
//!
//! ```rust
//! use std::str::FromStr;
//! use loco_rs::environment::Environment;
//!
//! pub fn load(environment: &str) {
//! let environment = Environment::from_str(environment).unwrap_or(Environment::Any(environment.to_string()));
//! let config = environment.load().expect("failed to load environment");
//! }
//! ```
use std::{path::Path, str::FromStr};
use serde::{Deserialize, Serialize};
use serde_variant::to_variant_name;
use super::config::Config;
use crate::Result;
#[must_use]
pub fn resolve_from_env() -> Option<String> {
std::env::var("LOCO_ENV")
.or_else(|_| std::env::var("RAILS_ENV"))
.or_else(|_| std::env::var("NODE_ENV"))
.ok()
}
/// Application environment
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum Environment {
#[serde(rename = "production")]
Production,
#[serde(rename = "development")]
Development,
#[serde(rename = "test")]
Test,
Any(String),
}
impl Environment {
/// Load environment variables from local configuration
///
/// # Errors
///
/// Returns a [`ConfigError`] if an error occurs during loading
/// configuration file an parse into [`Config`] struct.
pub fn load(&self) -> Result<Config> {
Config::new(self)
}
/// Load environment variables from the given config path
///
/// # Errors
///
/// Returns a [`ConfigError`] if an error occurs during loading
/// configuration file an parse into [`Config`] struct.
pub fn load_from_folder(&self, path: &Path) -> Result<Config> {
Config::from_folder(self, path)
}
}
impl std::fmt::Display for Environment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
to_variant_name(self).expect("only enum supported").fmt(f)
}
}
impl FromStr for Environment {
type Err = &'static str;
fn from_str(input: &str) -> std::result::Result<Self, Self::Err> {
match input {
"production" => Ok(Self::Production),
"development" => Ok(Self::Development),
"test" => Ok(Self::Test),
_ => Err(
" error parsing environment: expected one of \"production\", \"development\", \
\"test\" or any environment that has config file",
),
}
}
}