mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Choosing which language human messages are written in.
//!
//! Four layers decide, in this order: the mark on the command line, the value
//! written into the settings file, the language the host announces, and the
//! language built into this build. The first layer that names a language the
//! product actually carries wins.
//!
//! The host language is read through the platform's own locale mechanism,
//! which is a different thing from a variable this product defines. On Unix
//! that mechanism IS a set of process variables — `LANGUAGE`, `LC_ALL`,
//! `LC_MESSAGES` and `LANG`, in that order — and on Windows and macOS it is a
//! system call. The product names none of them and reads none of them itself.
//!
//! The distinction matters and the earlier wording here destroyed it. That
//! wording said the host language was read "never from a process variable",
//! which is false on the system this is most often built on, and it is the
//! shape of sentence that ends an audit rather than survives one: a reader
//! checking whether configuration leaks in through the environment finds the
//! denial, finds no `env::var` in this module, and stops. Both observations are
//! true and neither settles the question, because the reading was delegated one
//! layer down rather than not happening.
//!
//! What the product actually promises is narrower and still worth having: it
//! defines no environment variable of its own, so nothing here can be steered
//! by a name only this program knows. A caller who wants the language decided
//! rather than inherited passes `--lang` or stores `i18n.lang`, and either one
//! outranks the host.

use crate::error::{Failure, Result};
use unic_langid::LanguageIdentifier;

/// The languages this build carries messages for.
///
/// A tag absent from this list does not exist in the product, and asking for
/// one is refused with the whole list rather than served in another language.
pub const SUPPORTED: [&str; 2] = ["en", "pt-BR"];

/// The language used when no layer decides.
pub const BUILTIN: &str = "en";

/// Reads a host or caller tag as a language.
///
/// Hosts write the same language in several shapes: `pt_BR.UTF-8` from one
/// platform, `pt-BR` from another. Both name the same language, so both are
/// read the same way. Anything that is not a language at all yields nothing
/// rather than a failure, because the caller may not have asked for it.
///
/// # Examples
///
/// The three shapes a host may announce Brazilian Portuguese in all arrive at
/// the same language:
///
/// ```
/// use mariadb_cli::i18n::negotiate::parse;
///
/// let wanted = parse("pt-BR").expect("a language");
/// assert_eq!(parse("pt_BR").expect("a language"), wanted);
/// assert_eq!(parse("pt_BR.UTF-8").expect("a language"), wanted);
/// ```
///
/// What is not a language yields nothing rather than a failure:
///
/// ```
/// use mariadb_cli::i18n::negotiate::parse;
///
/// assert!(parse("").is_none());
/// assert!(parse("!!").is_none());
/// ```
#[must_use]
pub fn parse(raw: &str) -> Option<LanguageIdentifier> {
    let head = raw
        .split(['.', '@'])
        .next()
        .unwrap_or(raw)
        .replace('_', "-");
    if head.is_empty() {
        return None;
    }
    head.parse().ok()
}

/// The language the host announces, when it announces one this build can read.
///
/// Returns nothing rather than failing: a host that says nothing about its
/// language is normal, not broken.
#[must_use]
pub fn system() -> Option<LanguageIdentifier> {
    sys_locale::get_locale().as_deref().and_then(parse)
}

/// Every language this build carries, as identifiers.
#[must_use]
pub fn supported() -> Vec<LanguageIdentifier> {
    SUPPORTED.iter().filter_map(|tag| parse(tag)).collect()
}

/// The carried language closest to the one asked for.
///
/// An exact match wins. Failing that, the region is dropped and the base
/// language decides, so a caller in one region of a language is served in that
/// language rather than in another language entirely.
#[must_use]
pub fn best_match(wanted: &LanguageIdentifier) -> Option<LanguageIdentifier> {
    let carried = supported();
    carried
        .iter()
        .find(|candidate| *candidate == wanted)
        .or_else(|| {
            carried
                .iter()
                .find(|candidate| candidate.language == wanted.language)
        })
        .cloned()
}

/// The failure a tag outside the carried list produces.
fn unsupported(code: &'static str, raw: &str) -> Failure {
    Failure::usage(code, format!("`{raw}`"))
        .with_detail("detail", raw)
        .with_detail("languages", SUPPORTED.join(", "))
        .with_hint(format!("carried languages: {}", SUPPORTED.join(", ")))
}

/// Resolves the language in force for one invocation.
///
/// # Errors
///
/// Returns a usage failure when the mark on the command line names a language
/// this build does not carry, and a configuration failure when the value
/// written into the settings file does, so the caller learns which layer is at
/// fault. A host announcing an unknown language is never a failure: the
/// built-in language serves instead.
pub fn negotiate(requested: Option<&str>, stored: Option<&str>) -> Result<LanguageIdentifier> {
    if let Some(raw) = requested {
        return parse(raw)
            .as_ref()
            .and_then(best_match)
            .ok_or_else(|| unsupported("i18n.unsupported_language", raw));
    }

    if let Some(raw) = stored {
        return parse(raw).as_ref().and_then(best_match).ok_or_else(|| {
            Failure::config("i18n.unsupported_stored_language", format!("`{raw}`"))
                .with_detail("detail", raw)
                .with_detail("languages", SUPPORTED.join(", "))
                .with_hint(format!("carried languages: {}", SUPPORTED.join(", ")))
        });
    }

    Ok(system()
        .as_ref()
        .and_then(best_match)
        .or_else(|| parse(BUILTIN))
        .unwrap_or_default())
}

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

    #[test]
    fn the_carried_list_is_read_as_whole_languages() {
        assert_eq!(supported().len(), SUPPORTED.len());
    }

    #[test]
    fn a_host_writes_the_same_language_in_several_shapes() {
        let dotted = parse("pt_BR.UTF-8").expect("a language");
        let dashed = parse("pt-BR").expect("a language");
        assert_eq!(dotted, dashed);
    }

    #[test]
    fn something_that_is_not_a_language_yields_nothing_without_failing() {
        assert!(parse("").is_none());
        assert!(parse("!!!").is_none());
    }

    #[test]
    fn a_region_this_build_does_not_carry_falls_back_to_the_base_language() {
        let wanted = parse("pt-PT").expect("a language");
        let served = best_match(&wanted).expect("the base language serves");
        assert_eq!(served.to_string(), "pt-BR");
    }

    #[test]
    fn a_language_with_no_region_reaches_the_carried_region() {
        let wanted = parse("pt").expect("a language");
        assert_eq!(best_match(&wanted).expect("carried").to_string(), "pt-BR");
    }

    #[test]
    fn a_language_this_build_does_not_carry_matches_nothing() {
        let wanted = parse("de-DE").expect("a language");
        assert!(best_match(&wanted).is_none());
    }

    #[test]
    fn the_mark_on_the_command_line_outranks_the_stored_value() {
        let chosen = negotiate(Some("en"), Some("pt-BR")).expect("carried");
        assert_eq!(chosen.to_string(), "en");
    }

    #[test]
    fn the_stored_value_decides_when_no_mark_was_given() {
        let chosen = negotiate(None, Some("pt-BR")).expect("carried");
        assert_eq!(chosen.to_string(), "pt-BR");
    }

    #[test]
    fn a_language_this_build_lacks_is_refused_as_the_callers_mistake() {
        let failure = negotiate(Some("klingon"), None).expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Usage);
        assert_eq!(failure.exit_number().code(), 2);
        assert!(failure.hint().is_some_and(|hint| hint.contains("pt-BR")));
    }

    #[test]
    fn a_broken_stored_value_is_told_apart_from_a_broken_mark() {
        let failure = negotiate(None, Some("klingon")).expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Config);
    }

    #[test]
    fn nothing_asked_for_always_yields_a_language() {
        let chosen = negotiate(None, None).expect("never fails");
        assert!(SUPPORTED.contains(&chosen.to_string().as_str()));
    }
}