envigil 0.1.1

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
Documentation
//! Ready-made parser functions for common types.
//!
//! Each function has the signature `Fn(&str) -> Result<T, String>`
//! and can be passed directly to [`VarBuilder::new`](crate::VarBuilder::new).
//!
//! # Examples
//!
//! ```
//! use envigil::parse;
//!
//! assert_eq!(parse::secs("30").unwrap(), std::time::Duration::from_secs(30));
//! assert_eq!(parse::flag("yes").unwrap(), true);
//! assert_eq!(parse::list("a, b, c").unwrap(), vec!["a", "b", "c"]);
//! ```

use std::time::Duration;

/// Parse an integer number of seconds into a [`Duration`].
///
/// # Examples
///
/// ```
/// use envigil::parse;
/// use std::time::Duration;
///
/// assert_eq!(parse::secs("30").unwrap(), Duration::from_secs(30));
/// assert!(parse::secs("abc").is_err());
/// assert!(parse::secs("-1").is_err());
/// ```
pub fn secs(raw: &str) -> Result<Duration, String> {
    raw.trim()
        .parse::<u64>()
        .map(Duration::from_secs)
        .map_err(|e| format!("invalid number of seconds: {e}"))
}

/// Parse an integer number of milliseconds into a [`Duration`].
///
/// # Examples
///
/// ```
/// use envigil::parse;
/// use std::time::Duration;
///
/// assert_eq!(parse::millis("500").unwrap(), Duration::from_millis(500));
/// assert!(parse::millis("abc").is_err());
/// ```
pub fn millis(raw: &str) -> Result<Duration, String> {
    raw.trim()
        .parse::<u64>()
        .map(Duration::from_millis)
        .map_err(|e| format!("invalid number of milliseconds: {e}"))
}

/// Parse a boolean flag.
///
/// Accepted values (case-insensitive):
/// - **true:** `true`, `1`, `yes`, `on`
/// - **false:** `false`, `0`, `no`, `off`
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// assert_eq!(parse::flag("true").unwrap(), true);
/// assert_eq!(parse::flag("YES").unwrap(), true);
/// assert_eq!(parse::flag("0").unwrap(), false);
/// assert_eq!(parse::flag("off").unwrap(), false);
/// assert!(parse::flag("maybe").is_err());
/// ```
pub fn flag(raw: &str) -> Result<bool, String> {
    match raw.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Ok(true),
        "false" | "0" | "no" | "off" => Ok(false),
        other => Err(format!(
            "expected true/false, 1/0, yes/no, or on/off; got {other:?}"
        )),
    }
}

/// Parse a comma-separated list, trimming whitespace around items.
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// assert_eq!(
///     parse::list("a, b, c").unwrap(),
///     vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
/// );
/// assert_eq!(parse::list("").unwrap(), Vec::<String>::new());
/// ```
pub fn list(raw: &str) -> Result<Vec<String>, String> {
    list_sep(',')(raw)
}

/// Parse a list separated by an arbitrary character.
///
/// Returns a closure suitable for [`VarBuilder::new`](crate::VarBuilder::new).
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// let parser = parse::list_sep(';');
/// assert_eq!(
///     parser("x; y; z").unwrap(),
///     vec!["x".to_owned(), "y".to_owned(), "z".to_owned()]
/// );
/// ```
pub fn list_sep(sep: char) -> impl Fn(&str) -> Result<Vec<String>, String> {
    move |raw| {
        if raw.trim().is_empty() {
            return Ok(Vec::new());
        }
        Ok(raw.split(sep).map(|s| s.trim().to_owned()).collect())
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- secs --

    #[test]
    fn secs_valid() {
        assert_eq!(secs("30").unwrap(), Duration::from_secs(30));
        assert_eq!(secs(" 10 ").unwrap(), Duration::from_secs(10));
        assert_eq!(secs("0").unwrap(), Duration::from_secs(0));
    }

    #[test]
    fn secs_invalid() {
        assert!(secs("abc").is_err());
        assert!(secs("-1").is_err());
        assert!(secs("1.5").is_err());
    }

    // -- millis --

    #[test]
    fn millis_valid() {
        assert_eq!(millis("500").unwrap(), Duration::from_millis(500));
        assert_eq!(millis("0").unwrap(), Duration::from_millis(0));
    }

    #[test]
    fn millis_invalid() {
        assert!(millis("abc").is_err());
        assert!(millis("-1").is_err());
    }

    // -- flag --

    #[test]
    fn flag_true_variants() {
        for v in ["true", "1", "yes", "on", "TRUE", "Yes", "ON"] {
            assert!(flag(v).unwrap(), "input: {v}");
        }
    }

    #[test]
    fn flag_false_variants() {
        for v in ["false", "0", "no", "off", "FALSE", "No", "OFF"] {
            assert!(!flag(v).unwrap(), "input: {v}");
        }
    }

    #[test]
    fn flag_invalid() {
        assert!(flag("maybe").is_err());
        assert!(flag("2").is_err());
        assert!(flag("").is_err());
    }

    #[test]
    fn flag_trims_whitespace() {
        assert!(flag(" true ").unwrap());
    }

    // -- list --

    #[test]
    fn list_basic() {
        assert_eq!(
            list("a,b,c").unwrap(),
            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
        );
    }

    #[test]
    fn list_trims_whitespace() {
        assert_eq!(
            list(" a , b , c ").unwrap(),
            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
        );
    }

    #[test]
    fn list_empty_string() {
        assert_eq!(list("").unwrap(), Vec::<String>::new());
        assert_eq!(list("   ").unwrap(), Vec::<String>::new());
    }

    #[test]
    fn list_single_item() {
        assert_eq!(list("solo").unwrap(), vec!["solo".to_owned()]);
    }

    // -- list_sep --

    #[test]
    fn list_sep_semicolon() {
        let parser = list_sep(';');
        assert_eq!(
            parser("x; y; z").unwrap(),
            vec!["x".to_owned(), "y".to_owned(), "z".to_owned()]
        );
    }

    #[test]
    fn list_sep_pipe() {
        let parser = list_sep('|');
        assert_eq!(parser("a|b").unwrap(), vec!["a".to_owned(), "b".to_owned()]);
    }

    #[test]
    fn list_sep_empty() {
        let parser = list_sep(';');
        assert_eq!(parser("").unwrap(), Vec::<String>::new());
    }
}