1use std::collections::HashMap;
32use std::env;
33use std::fmt;
34use std::num::{ParseFloatError, ParseIntError};
35use std::str::ParseBoolError;
36
37#[derive(Debug)]
39pub enum EnvVarError {
40 NotFound(String),
42 TypeError {
44 key: String,
45 value: String,
46 expected_type: String,
47 details: Option<String>,
48 },
49}
50
51impl fmt::Display for EnvVarError {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 match self {
54 EnvVarError::NotFound(key) => {
55 write!(f, "Required environment variable '{}' is not set", key)
56 }
57 EnvVarError::TypeError {
58 key,
59 value,
60 expected_type,
61 details,
62 } => {
63 write!(
64 f,
65 "Environment variable '{}' has value '{}' which cannot be converted to {}",
66 key, value, expected_type
67 )?;
68 if let Some(d) = details {
69 write!(f, ": {}", d)?;
70 }
71 Ok(())
72 }
73 }
74 }
75}
76
77impl std::error::Error for EnvVarError {}
78
79impl From<ParseIntError> for EnvVarError {
80 fn from(err: ParseIntError) -> Self {
81 EnvVarError::TypeError {
82 key: String::new(),
83 value: String::new(),
84 expected_type: "integer".to_string(),
85 details: Some(err.to_string()),
86 }
87 }
88}
89
90impl From<ParseFloatError> for EnvVarError {
91 fn from(err: ParseFloatError) -> Self {
92 EnvVarError::TypeError {
93 key: String::new(),
94 value: String::new(),
95 expected_type: "float".to_string(),
96 details: Some(err.to_string()),
97 }
98 }
99}
100
101impl From<ParseBoolError> for EnvVarError {
102 fn from(err: ParseBoolError) -> Self {
103 EnvVarError::TypeError {
104 key: String::new(),
105 value: String::new(),
106 expected_type: "bool".to_string(),
107 details: Some(err.to_string()),
108 }
109 }
110}
111
112pub struct EnvVar;
114
115impl EnvVar {
116 pub fn string(key: &str) -> Result<String, EnvVarError> {
131 env::var(key).map_err(|_| EnvVarError::NotFound(key.to_string()))
132 }
133
134 pub fn int(key: &str) -> Result<i32, EnvVarError> {
144 let raw = Self::string(key)?;
145 raw.parse::<i32>().map_err(|_| EnvVarError::TypeError {
146 key: key.to_string(),
147 value: raw.clone(),
148 expected_type: "i32".to_string(),
149 details: None,
150 })
151 }
152
153 pub fn int64(key: &str) -> Result<i64, EnvVarError> {
163 let raw = Self::string(key)?;
164 raw.parse::<i64>().map_err(|_| EnvVarError::TypeError {
165 key: key.to_string(),
166 value: raw.clone(),
167 expected_type: "i64".to_string(),
168 details: None,
169 })
170 }
171
172 pub fn float(key: &str) -> Result<f64, EnvVarError> {
182 let raw = Self::string(key)?;
183 raw.parse::<f64>().map_err(|_| EnvVarError::TypeError {
184 key: key.to_string(),
185 value: raw.clone(),
186 expected_type: "f64".to_string(),
187 details: None,
188 })
189 }
190
191 pub fn bool(key: &str) -> Result<bool, EnvVarError> {
203 let raw = Self::string(key)?;
204 let normalized = raw.to_lowercase().trim().to_string();
205
206 match normalized.as_str() {
207 "true" | "yes" | "1" | "on" | "t" | "y" => Ok(true),
208 "false" | "no" | "0" | "off" | "f" | "n" => Ok(false),
209 _ => Err(EnvVarError::TypeError {
210 key: key.to_string(),
211 value: raw,
212 expected_type: "bool".to_string(),
213 details: Some("Valid values: true, false, yes, no, 1, 0, on, off".to_string()),
214 }),
215 }
216 }
217
218 pub fn list(key: &str, separator: &str) -> Result<Vec<String>, EnvVarError> {
229 let raw = Self::string(key)?;
230 if raw.trim().is_empty() {
231 return Ok(Vec::new());
232 }
233
234 Ok(raw
235 .split(separator)
236 .map(|s| s.trim().to_string())
237 .filter(|s| !s.is_empty())
238 .collect())
239 }
240
241 pub fn map(
253 key: &str,
254 item_separator: &str,
255 kv_separator: &str,
256 ) -> Result<HashMap<String, String>, EnvVarError> {
257 let raw = Self::string(key)?;
258 if raw.trim().is_empty() {
259 return Ok(HashMap::new());
260 }
261
262 let mut result = HashMap::new();
263 for item in raw.split(item_separator) {
264 let trimmed = item.trim();
265 if trimmed.is_empty() {
266 continue;
267 }
268
269 let parts: Vec<&str> = trimmed.splitn(2, kv_separator).collect();
270 if parts.len() != 2 {
271 return Err(EnvVarError::TypeError {
272 key: key.to_string(),
273 value: raw,
274 expected_type: "map".to_string(),
275 details: Some(format!(
276 "Expected format: KEY1{}VALUE1{}KEY2{}VALUE2",
277 kv_separator, item_separator, kv_separator
278 )),
279 });
280 }
281
282 result.insert(parts[0].trim().to_string(), parts[1].trim().to_string());
283 }
284
285 Ok(result)
286 }
287
288 pub fn dict(
292 key: &str,
293 item_separator: &str,
294 kv_separator: &str,
295 ) -> Result<HashMap<String, String>, EnvVarError> {
296 Self::map(key, item_separator, kv_separator)
297 }
298
299 pub fn url(key: &str) -> Result<String, EnvVarError> {
313 let value = Self::string(key)?;
314
315 if value.is_empty() {
316 return Ok(value);
317 }
318
319 if let Some((scheme, rest)) = value.split_once("://") {
322 if !scheme.is_empty()
323 && scheme
324 .chars()
325 .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
326 {
327 let host_part = rest
329 .split(|c| c == '/' || c == '?' || c == '#')
330 .next()
331 .unwrap_or("");
332 if !host_part.is_empty() {
333 let host_with_port = host_part
335 .rsplit_once('@')
336 .map(|(_, h)| h)
337 .unwrap_or(host_part);
338 let host = if host_with_port.starts_with('[') {
340 match host_with_port.find(']') {
341 Some(end) => &host_with_port[..=end],
342 None => "",
343 }
344 } else {
345 host_with_port
346 .split_once(':')
347 .map(|(h, _)| h)
348 .unwrap_or(host_with_port)
349 };
350 if !host.is_empty() {
351 return Ok(value);
352 }
353 }
354 }
355 }
356
357 Err(EnvVarError::TypeError {
358 key: key.to_string(),
359 value,
360 expected_type: "URL".to_string(),
361 details: Some("Value must be a valid URL with a scheme and host".to_string()),
362 })
363 }
364
365 pub fn enum_value<T: Clone>(
395 key: &str,
396 values: &HashMap<String, T>,
397 default: Option<T>,
398 ) -> Result<T, EnvVarError> {
399 match env::var(key) {
400 Ok(raw) if raw.trim().is_empty() => Err(EnvVarError::TypeError {
401 key: key.to_string(),
402 value: raw,
403 expected_type: "enum".to_string(),
404 details: Some("Empty value is not a valid enum".to_string()),
405 }),
406 Ok(raw) => {
407 let normalized = raw.to_lowercase().trim().to_string();
408 for (k, v) in values {
409 if k.to_lowercase().trim() == normalized {
410 return Ok(v.clone());
411 }
412 }
413 let valid: Vec<String> = values.keys().cloned().collect();
414 Err(EnvVarError::TypeError {
415 key: key.to_string(),
416 value: raw,
417 expected_type: "enum".to_string(),
418 details: Some(format!("Valid values: {}", valid.join(", "))),
419 })
420 }
421 Err(_) => default.ok_or_else(|| EnvVarError::NotFound(key.to_string())),
422 }
423 }
424
425 pub fn custom<T, F>(key: &str, converter: F) -> Result<T, EnvVarError>
442 where
443 F: FnOnce(&str) -> Result<T, Box<dyn std::error::Error>>,
444 {
445 let raw = Self::string(key)?;
446 converter(&raw).map_err(|e| EnvVarError::TypeError {
447 key: key.to_string(),
448 value: raw,
449 expected_type: "custom".to_string(),
450 details: Some(e.to_string()),
451 })
452 }
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458
459 #[test]
460 fn test_string() {
461 env::set_var("TEST_STRING", "hello");
462 assert_eq!(EnvVar::string("TEST_STRING").unwrap(), "hello");
463 env::remove_var("TEST_STRING");
464 }
465
466 #[test]
467 fn test_string_not_found() {
468 env::remove_var("MISSING_VAR");
469 assert!(matches!(
470 EnvVar::string("MISSING_VAR"),
471 Err(EnvVarError::NotFound(_))
472 ));
473 }
474
475 #[test]
476 fn test_int() {
477 env::set_var("TEST_INT", "42");
478 assert_eq!(EnvVar::int("TEST_INT").unwrap(), 42);
479 env::remove_var("TEST_INT");
480 }
481
482 #[test]
483 fn test_int_invalid() {
484 env::set_var("TEST_INT", "not_a_number");
485 assert!(matches!(
486 EnvVar::int("TEST_INT"),
487 Err(EnvVarError::TypeError { .. })
488 ));
489 env::remove_var("TEST_INT");
490 }
491
492 #[test]
493 fn test_float() {
494 env::set_var("TEST_FLOAT", "3.14");
495 assert_eq!(EnvVar::float("TEST_FLOAT").unwrap(), 3.14);
496 env::remove_var("TEST_FLOAT");
497 }
498
499 #[test]
500 fn test_bool() {
501 let true_values = vec!["true", "True", "TRUE", "yes", "YES", "1", "on", "ON"];
502 for val in true_values {
503 env::set_var("TEST_BOOL", val);
504 assert_eq!(EnvVar::bool("TEST_BOOL").unwrap(), true);
505 }
506
507 let false_values = vec!["false", "False", "FALSE", "no", "NO", "0", "off", "OFF"];
508 for val in false_values {
509 env::set_var("TEST_BOOL", val);
510 assert_eq!(EnvVar::bool("TEST_BOOL").unwrap(), false);
511 }
512
513 env::remove_var("TEST_BOOL");
514 }
515
516 #[test]
517 fn test_bool_invalid() {
518 env::set_var("TEST_BOOL_INVALID", "maybe");
519 assert!(matches!(
520 EnvVar::bool("TEST_BOOL_INVALID"),
521 Err(EnvVarError::TypeError { .. })
522 ));
523 env::remove_var("TEST_BOOL_INVALID");
524 }
525
526 #[test]
527 fn test_list() {
528 env::set_var("TEST_LIST_1", "a,b,c");
529 let result = EnvVar::list("TEST_LIST_1", ",").unwrap();
530 assert_eq!(result, vec!["a", "b", "c"]);
531 env::remove_var("TEST_LIST_1");
532 }
533
534 #[test]
535 fn test_list_with_whitespace() {
536 env::set_var("TEST_LIST_2", "a, b , c");
537 let result = EnvVar::list("TEST_LIST_2", ",").unwrap();
538 assert_eq!(result, vec!["a", "b", "c"]);
539 env::remove_var("TEST_LIST_2");
540 }
541
542 #[test]
543 fn test_map() {
544 env::set_var("TEST_MAP", "key1=value1,key2=value2");
545 let result = EnvVar::map("TEST_MAP", ",", "=").unwrap();
546 assert_eq!(result.get("key1"), Some(&"value1".to_string()));
547 assert_eq!(result.get("key2"), Some(&"value2".to_string()));
548 env::remove_var("TEST_MAP");
549 }
550
551 #[test]
552 fn test_url() {
553 env::set_var("TEST_URL_VALID", "https://example.com");
554 assert_eq!(
555 EnvVar::url("TEST_URL_VALID").unwrap(),
556 "https://example.com"
557 );
558 env::remove_var("TEST_URL_VALID");
559 }
560
561 #[test]
562 fn test_url_database_scheme() {
563 env::set_var("TEST_URL_PG", "postgresql://localhost:5432/mydb");
564 assert_eq!(
565 EnvVar::url("TEST_URL_PG").unwrap(),
566 "postgresql://localhost:5432/mydb"
567 );
568 env::remove_var("TEST_URL_PG");
569 }
570
571 #[test]
572 fn test_url_invalid() {
573 env::set_var("TEST_URL_INVALID", "not-a-url");
574 assert!(matches!(
575 EnvVar::url("TEST_URL_INVALID"),
576 Err(EnvVarError::TypeError { .. })
577 ));
578 env::remove_var("TEST_URL_INVALID");
579 }
580
581 #[test]
582 fn test_dict_alias() {
583 env::set_var("TEST_DICT", "key1=value1,key2=value2");
584 let result = EnvVar::dict("TEST_DICT", ",", "=").unwrap();
585 assert_eq!(result.get("key1"), Some(&"value1".to_string()));
586 assert_eq!(result.get("key2"), Some(&"value2".to_string()));
587 env::remove_var("TEST_DICT");
588 }
589
590 #[test]
591 fn test_enum_value() {
592 #[derive(Clone, Debug, PartialEq)]
593 enum Environment {
594 Development,
595 Staging,
596 }
597
598 let mut values = HashMap::new();
599 values.insert("development".to_string(), Environment::Development);
600 values.insert("staging".to_string(), Environment::Staging);
601
602 env::set_var("TEST_ENUM", "staging");
603 assert_eq!(
604 EnvVar::enum_value("TEST_ENUM", &values, None).unwrap(),
605 Environment::Staging
606 );
607 env::remove_var("TEST_ENUM");
608
609 assert_eq!(
610 EnvVar::enum_value("MISSING_ENUM", &values, Some(Environment::Development)).unwrap(),
611 Environment::Development
612 );
613 }
614}