env-reader 0.1.0

Read configuration from environment variables: blank is absent, every problem is reported at once, and a secret never prints.
Documentation
//! Turning a raw variable value into something typed.
//!
//! These are free functions taking values rather than variable names, so
//! they are testable without touching the process environment.
//! [`crate::Reader`] is what pairs them with a name.

/// A value if it is present, `None` if it is absent or blank.
///
/// **Blank is absent**, and every other reader in this crate goes through
/// this function. Leading and trailing whitespace is stripped; what is
/// left, if anything, is the value.
///
/// A templated deployment whose source was empty produces `PORT=` routinely
/// — an `.env` line with nothing after the `=`, a substituted variable that
/// resolved to nothing — and treating that as "configured, to the empty
/// string" produces failures a long way from their cause.
///
/// # Examples
///
/// ```
/// use env_reader::present;
///
/// assert_eq!(present(Some("orders")), Some("orders"));
/// assert_eq!(present(Some("  8080  ")), Some("8080"));
/// assert_eq!(present(Some("   ")), None);
/// assert_eq!(present(Some("")), None);
/// assert_eq!(present(None), None);
/// ```
#[must_use]
pub fn present(raw: Option<&str>) -> Option<&str> {
    raw.map(str::trim).filter(|value| !value.is_empty())
}

/// The spellings [`parse_bool`] accepts as true.
pub const TRUE_SPELLINGS: [&str; 4] = ["true", "1", "yes", "on"];

/// The spellings [`parse_bool`] accepts as false.
pub const FALSE_SPELLINGS: [&str; 4] = ["false", "0", "no", "off"];

/// Read a value as a boolean, strictly.
///
/// [`TRUE_SPELLINGS`] and [`FALSE_SPELLINGS`], in any case, after trimming.
/// Anything else — including an absent or blank value — is `None`, so the
/// caller decides between a default and an error rather than this function
/// guessing.
///
/// # Why strict is the default here
///
/// The tempting alternative is "anything not false-ish is true", and it is
/// a trap: `ENABLED=disabled`, `ENABLED=nope` and `ENABLED=flase` all come
/// out true, and the deployment that wrote them looks configured. See
/// [`parse_bool_lenient`] for when you nonetheless need that behaviour.
///
/// # Examples
///
/// ```
/// use env_reader::parse_bool;
///
/// assert_eq!(parse_bool(Some("false")), Some(false));
/// assert_eq!(parse_bool(Some("OFF")), Some(false));
/// assert_eq!(parse_bool(Some("  Yes ")), Some(true));
/// // Unrecognised is not silently true.
/// assert_eq!(parse_bool(Some("disabled")), None);
/// assert_eq!(parse_bool(Some("  ")), None);
/// ```
#[must_use]
pub fn parse_bool(raw: Option<&str>) -> Option<bool> {
    let value = present(raw)?.to_ascii_lowercase();

    if TRUE_SPELLINGS.contains(&value.as_str()) {
        Some(true)
    } else if FALSE_SPELLINGS.contains(&value.as_str()) {
        Some(false)
    } else {
        None
    }
}

/// Read a value as a boolean, leniently: anything not false-ish is true.
///
/// [`FALSE_SPELLINGS`] are false; **any other non-blank value is true**.
/// Deliberately lopsided, and not what [`parse_bool`] does.
///
/// This exists because deployments exist. A variable that has been set to
/// `disabled` or `enabled` or `y` for years is a value some running system
/// depends on, and a stricter reader would turn a working deployment into a
/// failing one at the worst possible moment. Reach for this when adopting
/// an existing estate, not when designing a new variable.
///
/// # Examples
///
/// ```
/// use env_reader::parse_bool_lenient;
///
/// assert_eq!(parse_bool_lenient(Some("false")), Some(false));
/// assert_eq!(parse_bool_lenient(Some("0")), Some(false));
/// assert_eq!(parse_bool_lenient(Some("true")), Some(true));
/// // The lopsided part.
/// assert_eq!(parse_bool_lenient(Some("disabled")), Some(true));
/// assert_eq!(parse_bool_lenient(Some("  ")), None);
/// ```
#[must_use]
pub fn parse_bool_lenient(raw: Option<&str>) -> Option<bool> {
    present(raw).map(|value| !FALSE_SPELLINGS.contains(&value.to_ascii_lowercase().as_str()))
}

/// Split a comma-separated value into its non-empty, trimmed elements.
///
/// An absent, blank, or all-separators value yields an empty vector;
/// whether that is acceptable is the caller's decision.
///
/// # Examples
///
/// ```
/// use env_reader::parse_csv;
///
/// assert_eq!(parse_csv(Some("245,212, 192 ,224")), ["245", "212", "192", "224"]);
/// // Empty elements are dropped, not preserved as empty strings.
/// assert_eq!(parse_csv(Some("a,,b,")), ["a", "b"]);
/// assert!(parse_csv(Some(" , , ")).is_empty());
/// assert!(parse_csv(None).is_empty());
/// ```
#[must_use]
pub fn parse_csv(raw: Option<&str>) -> Vec<String> {
    parse_separated(raw, ',')
}

/// [`parse_csv`], with a separator of your choosing.
///
/// For a `PATH`-shaped variable, or any list whose elements can contain a
/// comma.
///
/// # Examples
///
/// ```
/// use env_reader::parse_separated;
///
/// assert_eq!(parse_separated(Some("/usr/bin:/bin"), ':'), ["/usr/bin", "/bin"]);
/// assert_eq!(parse_separated(Some("a b  c"), ' '), ["a", "b", "c"]);
/// ```
#[must_use]
pub fn parse_separated(raw: Option<&str>, separator: char) -> Vec<String> {
    present(raw)
        .map(|value| {
            value
                .split(separator)
                .map(str::trim)
                .filter(|element| !element.is_empty())
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

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

    #[test]
    fn blank_is_the_same_as_absent() {
        assert_eq!(present(Some("")), None);
        assert_eq!(present(Some(" \t\n")), None);
        assert_eq!(present(None), None);
    }

    #[test]
    fn values_are_trimmed() {
        assert_eq!(present(Some("\t orders \n")), Some("orders"));
    }

    #[test]
    fn the_strict_reader_accepts_four_spellings_each_way() {
        for text in ["true", "TRUE", "True", "1", "yes", "YES", "on", "ON"] {
            assert_eq!(parse_bool(Some(text)), Some(true), "{text}");
        }
        for text in ["false", "FALSE", "False", "0", "no", "NO", "off", "OFF"] {
            assert_eq!(parse_bool(Some(text)), Some(false), "{text}");
        }
    }

    #[test]
    fn the_strict_reader_refuses_to_guess() {
        // The trap the lenient reader falls into, stated as a test.
        for text in ["disabled", "enabled", "nope", "flase", "y", "n", "2"] {
            assert_eq!(parse_bool(Some(text)), None, "{text}");
        }
    }

    #[test]
    fn the_lenient_reader_is_lopsided_on_purpose() {
        for text in ["false", "FALSE", "0", "no", "off"] {
            assert_eq!(parse_bool_lenient(Some(text)), Some(false), "{text}");
        }
        for text in ["true", "1", "yes", "on", "disabled", "nope", "flase"] {
            assert_eq!(parse_bool_lenient(Some(text)), Some(true), "{text}");
        }
    }

    #[test]
    fn a_blank_boolean_has_no_opinion_either_way() {
        // The caller supplies the default.
        assert_eq!(parse_bool(Some("  ")), None);
        assert_eq!(parse_bool(None), None);
        assert_eq!(parse_bool_lenient(Some("  ")), None);
        assert_eq!(parse_bool_lenient(None), None);
    }

    #[test]
    fn a_list_drops_empty_elements() {
        assert_eq!(parse_csv(Some("ADT_A05, ,ADT_A39,")), ["ADT_A05", "ADT_A39"]);
    }

    #[test]
    fn a_list_of_nothing_is_empty_not_one_empty_element() {
        // The trap `"".split(',')` sets: it yields one empty string.
        assert!(parse_csv(Some("")).is_empty());
        assert!(parse_csv(Some(",")).is_empty());
        assert!(parse_csv(None).is_empty());
    }

    #[test]
    fn a_list_can_use_another_separator() {
        assert_eq!(parse_separated(Some("/usr/bin:/bin:"), ':'), ["/usr/bin", "/bin"]);
    }
}