Skip to main content

typed_env_vars/
lib.rs

1//! Typed Environment Variables
2//!
3//! A type-safe environment variable library for Rust that provides automatic type conversion
4//! and validation.
5//!
6//! # Features
7//!
8//! - **Type Safety**: Automatic type conversion with validation
9//! - **Rich Types**: Support for String, i32, i64, f64, bool, Vec, HashMap, URL
10//! - **Default Values**: Optional default values for missing variables
11//! - **Clear Errors**: Descriptive error messages for debugging
12//! - **Zero Dependencies**: No external dependencies required
13//!
14//! # Examples
15//!
16//! ```
17//! use typed_env_vars::EnvVar;
18//! use std::env;
19//!
20//! // Set environment variables for the example
21//! env::set_var("API_KEY", "secret-key-123");
22//!
23//! // Required string
24//! let api_key = EnvVar::string("API_KEY").unwrap();
25//!
26//! // Optional with default
27//! let port = EnvVar::int("PORT").unwrap_or(8000);
28//! let debug = EnvVar::bool("DEBUG").unwrap_or(false);
29//! ```
30
31use std::collections::HashMap;
32use std::env;
33use std::fmt;
34use std::num::{ParseFloatError, ParseIntError};
35use std::str::ParseBoolError;
36
37/// Error types for environment variable operations
38#[derive(Debug)]
39pub enum EnvVarError {
40    /// Environment variable not found
41    NotFound(String),
42    /// Type conversion error
43    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
112/// Type-safe environment variable accessor
113pub struct EnvVar;
114
115impl EnvVar {
116    /// Get string environment variable
117    ///
118    /// # Examples
119    ///
120    /// ```
121    /// use typed_env_vars::EnvVar;
122    /// use std::env;
123    ///
124    /// env::set_var("API_KEY", "secret-key-123");
125    ///
126    /// // Required string
127    /// let api_key = EnvVar::string("API_KEY").unwrap();
128    /// assert_eq!(api_key, "secret-key-123");
129    /// ```
130    pub fn string(key: &str) -> Result<String, EnvVarError> {
131        env::var(key).map_err(|_| EnvVarError::NotFound(key.to_string()))
132    }
133
134    /// Get integer environment variable (i32)
135    ///
136    /// # Examples
137    ///
138    /// ```
139    /// use typed_env_vars::EnvVar;
140    ///
141    /// let port = EnvVar::int("PORT").unwrap_or(8000);
142    /// ```
143    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    /// Get 64-bit integer environment variable
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use typed_env_vars::EnvVar;
159    ///
160    /// let max_size = EnvVar::int64("MAX_SIZE").unwrap_or(1000000);
161    /// ```
162    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    /// Get float environment variable (f64)
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// use typed_env_vars::EnvVar;
178    ///
179    /// let timeout = EnvVar::float("TIMEOUT").unwrap_or(30.0);
180    /// ```
181    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    /// Get boolean environment variable
192    ///
193    /// Accepts: true/false, yes/no, 1/0, on/off (case-insensitive)
194    ///
195    /// # Examples
196    ///
197    /// ```
198    /// use typed_env_vars::EnvVar;
199    ///
200    /// let debug = EnvVar::bool("DEBUG").unwrap_or(false);
201    /// ```
202    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    /// Get list environment variable
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// use typed_env_vars::EnvVar;
224    ///
225    /// // Comma-separated by default
226    /// let hosts = EnvVar::list("ALLOWED_HOSTS", ",").unwrap_or_default();
227    /// ```
228    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    /// Get map environment variable
242    ///
243    /// Format: KEY1=VALUE1,KEY2=VALUE2
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// use typed_env_vars::EnvVar;
249    ///
250    /// let flags = EnvVar::map("FEATURE_FLAGS", ",", "=").unwrap_or_default();
251    /// ```
252    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    /// Get dictionary environment variable.
289    ///
290    /// Alias for [`EnvVar::map`] to match the common cross-language vocabulary.
291    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    /// Get URL environment variable with validation
300    ///
301    /// # Examples
302    ///
303    /// ```
304    /// use typed_env_vars::EnvVar;
305    /// use std::env;
306    ///
307    /// env::set_var("DATABASE_URL", "https://example.com");
308    ///
309    /// let db_url = EnvVar::url("DATABASE_URL").unwrap();
310    /// assert_eq!(db_url, "https://example.com");
311    /// ```
312    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        // Generic URL validation: scheme://[user[:pass]@]host[:port][/path][?query][#frag].
320        // Kept zero-dependency while accepting any valid scheme (postgresql, redis, amqp, etc.).
321        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                // Host part is everything before the first path/query/fragment delimiter.
328                let host_part = rest
329                    .split(|c| c == '/' || c == '?' || c == '#')
330                    .next()
331                    .unwrap_or("");
332                if !host_part.is_empty() {
333                    // Strip optional userinfo (keep only what follows the last '@').
334                    let host_with_port = host_part
335                        .rsplit_once('@')
336                        .map(|(_, h)| h)
337                        .unwrap_or(host_part);
338                    // Strip optional port, but preserve bracketed IPv6 literals.
339                    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    /// Get enum environment variable
366    ///
367    /// The `values` map maps accepted string values to their typed enum values.
368    /// Matching is case-insensitive.
369    ///
370    /// # Examples
371    ///
372    /// ```
373    /// use typed_env_vars::EnvVar;
374    /// use std::collections::HashMap;
375    /// use std::env;
376    ///
377    /// #[derive(Clone, Debug, PartialEq)]
378    /// enum Environment {
379    ///     Development,
380    ///     Staging,
381    ///     Production,
382    /// }
383    ///
384    /// env::set_var("ENVIRONMENT", "staging");
385    ///
386    /// let mut values = HashMap::new();
387    /// values.insert("development".to_string(), Environment::Development);
388    /// values.insert("staging".to_string(), Environment::Staging);
389    /// values.insert("production".to_string(), Environment::Production);
390    ///
391    /// let env = EnvVar::enum_value("ENVIRONMENT", &values, None).unwrap();
392    /// assert_eq!(env, Environment::Staging);
393    /// ```
394    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    /// Get environment variable with custom converter
426    ///
427    /// # Examples
428    ///
429    /// ```
430    /// use typed_env_vars::EnvVar;
431    /// use std::env;
432    ///
433    /// env::set_var("RELEASE_DATE", "2024-01-15");
434    ///
435    /// let date = EnvVar::custom("RELEASE_DATE", |s| {
436    ///     // Custom parsing logic
437    ///     Ok(s.to_string())
438    /// }).unwrap();
439    /// assert_eq!(date, "2024-01-15");
440    /// ```
441    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}