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
//! What can be wrong with a configuration, and how it reads.

use std::fmt;

/// One thing wrong with one variable.
///
/// Each variant names the variable, because the first thing anyone does
/// with a configuration error is search the deployment for that name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// A required variable is unset or blank.
    Missing {
        /// The variable's name.
        name: String,
    },

    /// A variable is set to something that is not the shape it must be.
    Invalid {
        /// The variable's name.
        name: String,
        /// What was expected, as a noun phrase: `a positive integer`.
        expected: String,
        /// What was there.
        ///
        /// Quoted in the message. Configuration values are operational
        /// rather than sensitive — and the one kind that is not should be
        /// read through [`crate::Secret`], which never reaches this type.
        got: String,
    },

    /// Two or more variables are individually fine but cannot be combined.
    Conflict {
        /// The whole sentence, because a conflict is about a relationship
        /// and there is no single name to lead with.
        message: String,
    },
}

impl Error {
    /// A required variable is unset or blank.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::Error;
    ///
    /// let error = Error::missing("DATABASE_URL");
    /// assert_eq!(error.to_string(), "missing required configuration: DATABASE_URL");
    /// ```
    #[must_use]
    pub fn missing(name: impl Into<String>) -> Self {
        Self::Missing { name: name.into() }
    }

    /// A variable holds something of the wrong shape.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::Error;
    ///
    /// let error = Error::invalid("PORT", "a whole number", "two");
    /// assert_eq!(
    ///     error.to_string(),
    ///     r#"invalid configuration: PORT must be a whole number, got "two""#
    /// );
    /// ```
    #[must_use]
    pub fn invalid(
        name: impl Into<String>,
        expected: impl Into<String>,
        got: impl Into<String>,
    ) -> Self {
        Self::Invalid {
            name: name.into(),
            expected: expected.into(),
            got: got.into(),
        }
    }

    /// Variables that cannot be combined as configured.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::Error;
    ///
    /// let error = Error::conflict("Cannot specify both QUEUE_NAME and TOPIC_NAME.");
    /// assert!(error.to_string().starts_with("Cannot specify both"));
    /// ```
    #[must_use]
    pub fn conflict(message: impl Into<String>) -> Self {
        Self::Conflict {
            message: message.into(),
        }
    }

    /// The variable this is about, when it is about one.
    ///
    /// [`Error::Conflict`] concerns a relationship between variables and so
    /// names none.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::Error;
    ///
    /// assert_eq!(Error::missing("PORT").name(), Some("PORT"));
    /// assert_eq!(Error::conflict("either, not both").name(), None);
    /// ```
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        match self {
            Self::Missing { name } | Self::Invalid { name, .. } => Some(name),
            Self::Conflict { .. } => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Missing { name } => {
                write!(formatter, "missing required configuration: {name}")
            }
            Self::Invalid {
                name,
                expected,
                got,
            } => write!(
                formatter,
                "invalid configuration: {name} must be {expected}, got {got:?}"
            ),
            Self::Conflict { message } => formatter.write_str(message),
        }
    }
}

impl std::error::Error for Error {}

/// Every problem found while reading a configuration.
///
/// Constructed by [`crate::Reader::finish`]. It is never empty: a reader
/// with no problems returns `Ok` instead.
///
/// It renders one problem per line, so a process's last words are the whole
/// list rather than the first item of it.
///
/// # Examples
///
/// ```
/// use env_reader::Reader;
///
/// let mut reader = Reader::from_pairs([("PORT", "two")]);
/// let _: String = reader.required_string("SERVICE_NAME");
/// let _: u16 = reader.integer_or("PORT", 8080);
///
/// let errors = reader.finish().unwrap_err();
/// assert_eq!(errors.len(), 2);
/// assert_eq!(
///     errors.to_string(),
///     "missing required configuration: SERVICE_NAME\n\
///      invalid configuration: PORT must be a whole number, got \"two\""
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Errors(Vec<Error>);

impl Errors {
    /// Wrap a non-empty list of problems.
    ///
    /// # Panics
    ///
    /// Panics if `errors` is empty. An empty error is not a thing this type
    /// can represent, and a caller that has none should be returning `Ok`.
    #[must_use]
    pub fn new(errors: Vec<Error>) -> Self {
        assert!(!errors.is_empty(), "Errors must hold at least one problem");
        Self(errors)
    }

    /// How many problems there are.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::{Error, Errors};
    ///
    /// let errors = Errors::new(vec![Error::missing("PORT")]);
    /// assert_eq!(errors.len(), 1);
    /// assert!(!errors.is_empty());
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Always false; see [`Errors::new`].
    ///
    /// Present because clippy asks for it beside [`Errors::len`], and
    /// because a caller writing `if errors.is_empty()` deserves an answer
    /// rather than a compile error.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The problems, in the order they were found.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::{Error, Errors};
    ///
    /// let errors = Errors::new(vec![Error::missing("A"), Error::missing("B")]);
    /// let names: Vec<_> = errors.iter().filter_map(Error::name).collect();
    /// assert_eq!(names, ["A", "B"]);
    /// ```
    pub fn iter(&self) -> std::slice::Iter<'_, Error> {
        self.0.iter()
    }

    /// The problems, consuming this.
    #[must_use]
    pub fn into_inner(self) -> Vec<Error> {
        self.0
    }
}

impl fmt::Display for Errors {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        for error in &self.0 {
            if !first {
                writeln!(formatter)?;
            }
            write!(formatter, "{error}")?;
            first = false;
        }
        Ok(())
    }
}

impl std::error::Error for Errors {}

impl<'a> IntoIterator for &'a Errors {
    type Item = &'a Error;
    type IntoIter = std::slice::Iter<'a, Error>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl IntoIterator for Errors {
    type Item = Error;
    type IntoIter = std::vec::IntoIter<Error>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

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

    #[test]
    fn a_missing_variable_names_itself() {
        assert_eq!(
            Error::missing("DATABASE_URL").to_string(),
            "missing required configuration: DATABASE_URL"
        );
    }

    #[test]
    fn an_invalid_value_is_quoted_so_whitespace_is_visible() {
        // `got: "2576 "` and `got: "2576"` are different diagnoses, and the
        // quoting is the only thing that shows which one happened.
        assert_eq!(
            Error::invalid("PORT", "a whole number", "2576 ").to_string(),
            r#"invalid configuration: PORT must be a whole number, got "2576 ""#
        );
    }

    #[test]
    fn problems_render_one_per_line() {
        let errors = Errors::new(vec![
            Error::missing("A"),
            Error::invalid("B", "a whole number", "x"),
        ]);
        let text = errors.to_string();
        assert_eq!(text.lines().count(), 2);
        assert!(text.starts_with("missing required configuration: A\n"));
    }

    #[test]
    fn a_conflict_names_no_single_variable() {
        assert_eq!(Error::conflict("either, not both").name(), None);
        assert_eq!(Error::missing("A").name(), Some("A"));
        assert_eq!(Error::invalid("B", "x", "y").name(), Some("B"));
    }

    #[test]
    #[should_panic(expected = "at least one problem")]
    fn an_empty_error_list_is_not_representable() {
        let _ = Errors::new(Vec::new());
    }
}