configurant 0.8.14

Schema-first configuration: declare values in a TOML schema, layer defaults, file, environment and command line, validate with named errors, explain where each value came from. No generated code; secrets never printed.
Documentation
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Named errors. No variant carries a secret's value: where a value would be shown for a secret
//! key, the text is `<redacted>`.

use std::fmt;

use crate::schema::Bound;

/// Where a value (or an offending input) came from.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Origin {
    /// The default declared in the schema.
    Default,
    /// A configuration file, by the name it was given.
    File(String),
    /// An environment variable, by name.
    Env(String),
    /// A command-line flag (or argument position).
    Cli(String),
    /// A secret source (`configurant-secrets`), as the schema declares it: `<source>:<reference>`. Never the value.
    Source(String),
    /// A lookup by key (`Config::get`, `explain`), not a source of values.
    Lookup,
    /// A change made by a front end through [`crate::edit::Session`].
    Edit,
}

impl fmt::Display for Origin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Origin::Default => f.write_str("the schema default"),
            Origin::File(n) => write!(f, "file `{n}`"),
            Origin::Env(n) => write!(f, "environment variable `{n}`"),
            Origin::Cli(n) => write!(f, "command-line `{n}`"),
            Origin::Source(declared) => match declared.split_once(':') {
                Some((name, reference)) => {
                    write!(f, "secret source `{name}` (reference `{reference}`)")
                }
                None => write!(f, "secret source `{declared}`"),
            },
            Origin::Lookup => f.write_str("this lookup"),
            Origin::Edit => f.write_str("this edit"),
        }
    }
}

/// One refused input.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// The schema does not declare this name.
    #[error("unknown key `{key}` from {origin}{}", suggest(.suggestion))]
    UnknownKey {
        /// The unknown key, environment variable or flag.
        key: String,
        /// A declared name close to it, if there is one.
        suggestion: Option<String>,
        /// Where the unknown name was given.
        origin: Origin,
    },
    /// The input is not of the type the schema declares.
    #[error("`{key}` from {origin}: expected {expected}, found {found}")]
    WrongType {
        /// Dotted key concerned.
        key: String,
        /// What was wanted, such as a type name.
        expected: &'static str,
        /// What was given (a type name or the quoted text); `<redacted>` for a secret's text.
        found: String,
        /// Where the input came from.
        origin: Origin,
    },
    /// A number is below `min` or above `max`.
    #[error("`{key}` from {origin}: {found} is outside {}", range(*.min, *.max))]
    OutOfRange {
        /// Dotted key concerned.
        key: String,
        /// The refused number as shown; `<redacted>` for a secret.
        found: String,
        /// Lowest allowed value (inclusive), if the schema sets one.
        min: Option<Bound>,
        /// Highest allowed value (inclusive), if the schema sets one.
        max: Option<Bound>,
        /// Where the input came from.
        origin: Origin,
    },
    /// An enum value that is not one of the schema's choices.
    #[error("`{key}` from {origin}: {found} is not one of {}", .choices.join(", "))]
    NotAllowed {
        /// Dotted key concerned.
        key: String,
        /// The refused value as shown; `<redacted>` for a secret.
        found: String,
        /// The values the schema allows.
        choices: Vec<String>,
        /// Where the input came from.
        origin: Origin,
    },
    /// A secret was given by a file, or an edit tried to set one.
    #[error("`{key}` is a secret and may not come from {origin}; use its environment variable")]
    SecretInForbiddenSource {
        /// The secret's dotted key.
        key: String,
        /// Where the attempt came from.
        origin: Origin,
    },
    /// A value the schema requires was set by no layer.
    #[error("`{key}` is required and no origin set it")]
    MissingRequired {
        /// Dotted key of the value, table, map or row field.
        key: String,
    },
    /// A typed read of a declared key that has no value.
    #[error("`{key}` has no value (no default and no origin set it)")]
    NotSet {
        /// The key that was read.
        key: String,
    },
    /// A command-line flag that takes a value was given none.
    #[error("flag `{flag}` needs a value")]
    MissingCliValue {
        /// The flag as typed.
        flag: String,
    },
    /// An argument that does not start with `--`; it is not echoed, as it could be a secret.
    #[error("unexpected command-line argument at position {index}")]
    UnexpectedArgument {
        /// Position among the arguments, counting from 0.
        index: usize,
    },
    /// The configuration file could not be read as TOML, or is too large.
    #[error("configuration file `{name}`: {reason}")]
    FileParse {
        /// The name the file was given.
        name: String,
        /// The parser's message, with the line number when known.
        reason: String,
    },
    /// The value's `provider` names a module the loader does not have.
    #[error("`{key}` takes its value from module `{module}`, which is not registered")]
    ModuleMissing {
        /// Dotted key concerned.
        key: String,
        /// The module the schema names.
        module: String,
    },
    /// The file's `config_version` is older than the schema's.
    #[error(
        "configuration file `{name}` is at config version {found}, this schema is at {current}; run `configurant migrate`"
    )]
    FileOutdated {
        /// The name the file was given.
        name: String,
        /// The version the file records.
        found: u32,
        /// The version the schema is at.
        current: u32,
    },
    /// The file's `config_version` is newer than the schema's.
    #[error(
        "configuration file `{name}` is at config version {found}, newer than this schema's {current}"
    )]
    FileNewer {
        /// The name the file was given.
        name: String,
        /// The version the file records.
        found: u32,
        /// The version the schema is at.
        current: u32,
    },
    /// A mounted fragment's section of the file is at an older version.
    #[error(
        "configuration file `{name}` has `{mount}` at config version {found}, the fragment is at {current}; run `configurant migrate`"
    )]
    MountFileOutdated {
        /// The name the file was given.
        name: String,
        /// The name the fragment is mounted as.
        mount: String,
        /// The version that section records.
        found: u32,
        /// The version the fragment is at.
        current: u32,
    },
    /// A mounted fragment's section of the file is at a newer version.
    #[error(
        "configuration file `{name}` has `{mount}` at config version {found}, newer than the fragment's {current}"
    )]
    MountFileNewer {
        /// The name the file was given.
        name: String,
        /// The name the fragment is mounted as.
        mount: String,
        /// The version that section records.
        found: u32,
        /// The version the fragment is at.
        current: u32,
    },
    /// A map entry whose key is the empty string.
    #[error("map `{key}` from {origin} has an empty key")]
    EmptyMapKey {
        /// Dotted key of the map.
        key: String,
        /// Where the map came from.
        origin: Origin,
    },
    /// An edit tried to set a table or map.
    #[error("`{key}` is an array of tables or a map, which only the configuration file can set")]
    FileOnly {
        /// Dotted key of the table or map.
        key: String,
    },
    /// The loaded values do not fit the type given to `Config::deserialize`.
    #[error("the configuration does not fit the target type: {reason}")]
    Deserialize {
        /// The deserializer's message, withheld if it quoted a secret.
        reason: String,
    },
    /// A provider module's own rule refused the value.
    #[error("`{key}` from {origin} was rejected by module `{module}`: {reason}")]
    ModuleRejected {
        /// Dotted key concerned.
        key: String,
        /// Name of the module that refused it.
        module: String,
        /// The module's message; `<redacted>` for a secret.
        reason: String,
        /// Where the value came from.
        origin: Origin,
    },
}

fn suggest(s: &Option<String>) -> String {
    s.as_ref()
        .map(|s| format!(" (did you mean `{s}`?)"))
        .unwrap_or_default()
}

fn range(min: Option<Bound>, max: Option<Bound>) -> String {
    match (min, max) {
        (Some(a), Some(b)) => format!("{a}..={b}"),
        (Some(a), None) => format!(">= {a}"),
        (None, Some(b)) => format!("<= {b}"),
        (None, None) => "the allowed range".into(),
    }
}

/// Every error found in one load (the loader does not stop at the first).
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub struct Errors(pub Vec<ConfigError>);

impl fmt::Display for Errors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, e) in self.0.iter().enumerate() {
            if i > 0 {
                f.write_str("\n")?;
            }
            write!(f, "{e}")?;
        }
        Ok(())
    }
}