mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Reading one raw text as the value of one key, and refusing it well.
//!
//! Every refusal on this path names the setting, the domain it belongs to and
//! the values that domain accepts, so a caller is never told only that they were
//! wrong.

use super::registry::{FALSE_WORDS, REGISTRY, TRUE_WORDS};
use super::types::{Domain, KeySpec, Value};
use crate::error::{Failure, Result};

/// Reads one raw text as the value of one key.
///
/// # Errors
///
/// Returns a configuration failure when the key is unknown or when the text
/// falls outside the key's domain, always naming the accepted values.
pub fn validate(name: &str, raw: &str) -> Result<Value> {
    let Some(entry) = super::spec(name) else {
        return Err(unknown_key(name));
    };

    match entry.domain {
        Domain::Boolean => read_boolean(entry, raw),
        Domain::PositiveInteger => read_integer(entry, raw, 1),
        Domain::NonNegativeInteger => read_integer(entry, raw, 0),
        Domain::IntegerInRange(low, high) => read_bounded(entry, raw, low, high),
        Domain::Enumeration(values) => read_word(entry, raw, values),
        Domain::Text => read_text(entry, raw),
    }
}

/// The failure for a name outside the registry.
///
/// A near miss is offered, because a caller who mistyped one character should
/// not have to read the whole registry to find it.
#[must_use]
pub fn unknown_key(name: &str) -> Failure {
    let failure =
        Failure::config("config.unknown_key", format!("`{name}`")).with_detail("detail", name);
    match nearest(name) {
        Some(candidate) => failure
            .with_detail("near", "yes")
            .with_detail("candidate", candidate)
            .with_hint(format!("did you mean `{candidate}`?")),
        None => failure
            .with_detail("near", "no")
            .with_hint("run `config list` to see every setting"),
    }
}

/// The registry entry closest to a mistyped name, when one is close enough.
fn nearest(name: &str) -> Option<&'static str> {
    REGISTRY
        .iter()
        .map(|entry| (entry.name, distance(entry.name, name)))
        .filter(|(_, gap)| *gap <= 3)
        .min_by_key(|(_, gap)| *gap)
        .map(|(candidate, _)| candidate)
}

/// Edit distance between two names, in characters.
fn distance(left: &str, right: &str) -> usize {
    let right: Vec<char> = right.chars().collect();
    let mut previous: Vec<usize> = (0..=right.len()).collect();
    for (row, source) in left.chars().enumerate() {
        let mut current = vec![row + 1];
        for (column, target) in right.iter().enumerate() {
            let cost = usize::from(source != *target);
            let value = (previous[column] + cost)
                .min(previous[column + 1] + 1)
                .min(current[column] + 1);
            current.push(value);
        }
        previous = current;
    }
    previous[right.len()]
}

/// The failure for a value outside a key's domain.
fn outside(entry: &KeySpec, raw: &str) -> Failure {
    Failure::config("config.value_outside_domain", format!("`{raw}`"))
        .with_detail("detail", raw)
        .with_detail("setting", entry.name)
        .with_detail("domain", entry.domain.token())
        .with_detail("accepted", entry.domain.accepted())
        .with_hint(format!("accepted: {}", entry.domain.described()))
}

fn read_boolean(entry: &KeySpec, raw: &str) -> Result<Value> {
    let folded = raw.trim().to_ascii_lowercase();
    if TRUE_WORDS.contains(&folded.as_str()) {
        return Ok(Value::Boolean(true));
    }
    if FALSE_WORDS.contains(&folded.as_str()) {
        return Ok(Value::Boolean(false));
    }
    Err(outside(entry, raw))
}

fn read_integer(entry: &KeySpec, raw: &str, floor: u64) -> Result<Value> {
    let parsed: u64 = raw.trim().parse().map_err(|_| outside(entry, raw))?;
    if parsed < floor {
        return Err(outside(entry, raw));
    }
    Ok(Value::Integer(parsed))
}

/// Reads a whole number and refuses it outside the range the key states.
///
/// The ceiling belongs here rather than at the place the value is used, so the
/// refusal reaches the caller while they are still looking at the order they
/// gave.
fn read_bounded(entry: &KeySpec, raw: &str, low: u64, high: u64) -> Result<Value> {
    let parsed: u64 = raw.trim().parse().map_err(|_| outside(entry, raw))?;
    if parsed < low || parsed > high {
        return Err(outside(entry, raw));
    }
    Ok(Value::Integer(parsed))
}

fn read_word(entry: &KeySpec, raw: &str, values: &'static [&'static str]) -> Result<Value> {
    let folded = raw.trim().to_ascii_lowercase();
    values
        .iter()
        .find(|candidate| **candidate == folded)
        .map_or_else(
            || Err(outside(entry, raw)),
            |found| Ok(Value::Enumeration(found)),
        )
}

fn read_text(entry: &KeySpec, raw: &str) -> Result<Value> {
    if raw.is_empty() {
        return Err(outside(entry, raw));
    }
    Ok(Value::Text(raw.to_owned()))
}