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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
use super::*;
/// Layering and typed extraction methods for [`EnvConfig`].
impl EnvConfig {
/// Creates an empty [`EnvConfig`] without reading process environment variables.
///
/// # Returns
///
/// - `Self` - Empty configuration map.
pub fn new() -> Self {
Self::default()
}
/// Creates an [`EnvConfig`] populated from the current process environment (`std::env::vars`).
///
/// # Returns
///
/// - `Self` - Snapshot of process environment variables.
pub fn from_process_env() -> Self {
let mut cfg: Self = Self::new();
cfg.merge_process_env();
cfg
}
/// Creates an [`EnvConfig`] by parsing `.env` text directly.
///
/// # Arguments
///
/// - `&str` - Raw `.env` content.
///
/// # Returns
///
/// - `Result<Self, EnvError>` - Populated config or syntax error.
pub fn from_dotenv_str(content: &str) -> Result<Self, EnvError> {
let parsed: BTreeMap<String, String> = parse_dotenv(content)?;
Ok(Self {
values: parsed,
prefix: String::new(),
})
}
/// Sets an automatic key prefix applied to all subsequent lookups (e.g. `"APP_"`).
///
/// # Arguments
///
/// - `S` - Key prefix string.
///
/// # Returns
///
/// - `Self` - Updated configuration.
pub fn with_prefix<S>(self, prefix: S) -> Self
where
S: Into<String>,
{
Self {
prefix: prefix.into(),
..self
}
}
/// Merges all key-value pairs from a `.env` file on disk into `self` (overwriting existing keys).
///
/// # Arguments
///
/// - `&Path` - Path to `.env` file.
///
/// # Returns
///
/// - `Result<&mut Self, EnvError>` - Mutable reference to `self` or I/O / syntax error.
pub fn merge_dotenv_file(&mut self, path: &Path) -> Result<&mut Self, EnvError> {
let content: String =
fs::read_to_string(path).map_err(|e: io::Error| EnvError::Io(e.to_string()))?;
let parsed: BTreeMap<String, String> = parse_dotenv(&content)?;
let Self { values, .. } = self;
values.extend(parsed);
Ok(self)
}
/// Merges current OS environment variables on top of loaded `.env` defaults.
///
/// # Returns
///
/// - `&mut Self` - Mutable reference for chaining.
pub fn merge_process_env(&mut self) -> &mut Self {
let Self { values, .. } = self;
for (k, v) in env::vars() {
values.insert(k, v);
}
self
}
/// Inserts or overrides a single key-value pair.
///
/// # Arguments
///
/// - `K` - Environment variable name.
/// - `V` - Environment variable value.
///
/// # Returns
///
/// - `&mut Self` - Mutable reference for chaining.
pub fn set<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: Into<String>,
V: Into<String>,
{
let Self { values, .. } = self;
values.insert(key.into(), value.into());
self
}
/// Resolves a key with any configured prefix and returns its borrowed value.
///
/// # Arguments
///
/// - `&str` - Unprefixed key name.
///
/// # Returns
///
/// - `Option<&str>` - Borrowed value if present.
pub fn get(&self, key: &str) -> Option<&str> {
let Self { values, prefix } = self;
if prefix.is_empty() {
values.get(key).map(String::as_str)
} else {
let full: String = format!("{prefix}{key}");
values.get(&full).map(String::as_str)
}
}
/// Returns a required non-empty string value or [`EnvError::MissingKey`].
///
/// # Arguments
///
/// - `&str` - Key name.
///
/// # Returns
///
/// - `Result<String, EnvError>` - Owned value or missing-key error.
pub fn require(&self, key: &str) -> Result<String, EnvError> {
match self.get(key) {
Some(v) if !v.is_empty() => Ok(v.to_owned()),
_ => Err(EnvError::MissingKey(key.to_owned())),
}
}
/// Returns a wrapped [`SecretString`] for a required secret key.
///
/// # Arguments
///
/// - `&str` - Secret key name.
///
/// # Returns
///
/// - `Result<SecretString, EnvError>` - Secret wrapper or missing-key error.
pub fn require_secret(&self, key: &str) -> Result<SecretString, EnvError> {
Ok(SecretString::new(self.require(key)?))
}
/// Returns a string value or `default` when absent or empty.
///
/// # Arguments
///
/// - `&str` - Key name.
/// - `&str` - Fallback string.
///
/// # Returns
///
/// - `String` - Resolved value or fallback.
pub fn get_or(&self, key: &str, default: &str) -> String {
match self.get(key) {
Some(v) if !v.is_empty() => v.to_owned(),
_ => default.to_owned(),
}
}
/// Parses a key into any [`FromStr`] type, returning `default` when absent.
///
/// # Arguments
///
/// - `&str` - Key name.
/// - `T` - Fallback value when key is absent.
///
/// # Returns
///
/// - `Result<T, EnvError>` - Parsed value, fallback, or parse error.
pub fn parse_or<T>(&self, key: &str, default: T) -> Result<T, EnvError>
where
T: FromStr,
T::Err: fmt::Display,
{
let Some(raw) = self.get(key) else {
return Ok(default);
};
if raw.is_empty() {
return Ok(default);
}
raw.parse::<T>().map_err(|e: T::Err| EnvError::ParseError {
key: key.to_owned(),
detail: e.to_string(),
})
}
/// Parses a boolean value (`true/false/1/0/yes/no/on/off`, case-insensitive).
///
/// # Arguments
///
/// - `&str` - Key name.
/// - `bool` - Fallback value when key is absent.
///
/// # Returns
///
/// - `Result<bool, EnvError>` - Parsed boolean or parse error.
pub fn get_bool_or(&self, key: &str, default: bool) -> Result<bool, EnvError> {
let Some(raw) = self.get(key) else {
return Ok(default);
};
let lower: String = raw.trim().to_ascii_lowercase();
match lower.as_str() {
"" => Ok(default),
TRUE_STR | "1" | "yes" | "on" => Ok(true),
FALSE_STR | "0" | "no" | "off" => Ok(false),
_ => Err(EnvError::ParseError {
key: key.to_owned(),
detail: ERR_INVALID_BOOL.to_owned(),
}),
}
}
/// Parses a human duration (`250ms`, `5s`, `2m`, `1h`, or bare milliseconds integer).
///
/// # Arguments
///
/// - `&str` - Key name.
/// - `Duration` - Fallback duration when absent.
///
/// # Returns
///
/// - `Result<Duration, EnvError>` - Parsed duration or parse error.
pub fn get_duration_or(&self, key: &str, default: Duration) -> Result<Duration, EnvError> {
let Some(raw) = self.get(key) else {
return Ok(default);
};
let trimmed: &str = raw.trim();
if trimmed.is_empty() {
return Ok(default);
}
let parsed: Option<Duration> = if let Some(ms) = trimmed.strip_suffix("ms") {
ms.trim().parse::<u64>().ok().map(Duration::from_millis)
} else if let Some(s) = trimmed.strip_suffix('s') {
s.trim().parse::<u64>().ok().map(Duration::from_secs)
} else if let Some(m) = trimmed.strip_suffix('m') {
m.trim()
.parse::<u64>()
.ok()
.map(|v: u64| Duration::from_secs(v.saturating_mul(60)))
} else if let Some(h) = trimmed.strip_suffix('h') {
h.trim()
.parse::<u64>()
.ok()
.map(|v: u64| Duration::from_secs(v.saturating_mul(3600)))
} else {
trimmed.parse::<u64>().ok().map(Duration::from_millis)
};
parsed.ok_or_else(|| EnvError::ParseError {
key: key.to_owned(),
detail: ERR_INVALID_DURATION.to_owned(),
})
}
/// Splits a comma-separated environment value into trimmed non-empty strings.
///
/// # Arguments
///
/// - `&str` - Key name.
///
/// # Returns
///
/// - `Vec<String>` - List of trimmed entries (empty if key is absent).
pub fn get_list(&self, key: &str) -> Vec<String> {
let Some(raw) = self.get(key) else {
return Vec::new();
};
raw.split(',')
.map(|part: &str| part.trim())
.filter(|part: &&str| !part.is_empty())
.map(str::to_owned)
.collect()
}
/// Returns the total number of stored entries.
///
/// # Returns
///
/// - `usize` - Entry count.
#[inline(always)]
pub fn len(&self) -> usize {
let Self { values, .. } = self;
values.len()
}
/// Returns whether zero entries are stored.
///
/// # Returns
///
/// - `bool` - `true` when empty.
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}