mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Deciding what the auxiliary channel does, from the settings and the marks.
//!
//! Every value here comes from a stored key or from a mark on the command line.
//! Reading one from the process environment would put a setting of this product
//! outside the configuration surface, where `config list` cannot show it and
//! `config doctor` cannot check it.
//!
//! The destination of the diagnostic files is derived from the configuration
//! location rather than stored as a key of its own. A second key naming a
//! directory would be a second thing to keep in step with the first, and the
//! configuration location already answers the question.

use super::tracing::{Diagnostics, Rotation};
use crate::cli::globals::GlobalFlags;
use crate::config::Config;
use crate::error::Result;

/// The folder, under the configuration location, that holds the diagnostics.
const DIAGNOSTIC_FOLDER: &str = "logs";

/// Builds what the auxiliary channel obeys for this invocation.
///
/// # Errors
///
/// Returns a configuration failure when a stored value is outside its domain,
/// or when the configuration location cannot be resolved.
pub fn resolve(config: &Config, flags: &GlobalFlags) -> Result<Diagnostics> {
    // The language is settled here, before anything else, because this is the
    // first moment in an invocation where both deciding layers are in hand: the
    // mark on the command line and the stored key. It belongs with the rest of
    // the auxiliary channel because it governs every word that channel writes,
    // and it goes first so that a broken setting further down is reported in
    // the language the reader asked for rather than in the built-in one.
    crate::i18n::install(
        flags.diagnostics.lang.as_deref(),
        stored_language(config)?.as_deref(),
    )?;

    let stored = crate::settings::word(config, "log.level")?;
    let level =
        super::tracing::level_for(flags.diagnostics.quiet, flags.diagnostics.verbose, &stored);

    let directory = crate::config::paths::config_dir(flags.diagnostics.config_dir.as_deref())?
        .join(DIAGNOSTIC_FOLDER);

    Ok(Diagnostics {
        level,
        to_file: crate::settings::boolean(config, "log.to_file")?,
        directory,
        // An unreadable word is not a reason to lose the invocation, so the
        // published default stands and the caller still gets its diagnostics.
        rotation: Rotation::parse(&crate::settings::word(config, "log.rotation")?)
            .unwrap_or(Rotation::Daily),
        retention: crate::settings::count(config, "log.retention")?,
        colour: colour_wanted(flags, std::io::IsTerminal::is_terminal(&std::io::stderr())),
    })
}

/// The language written into the settings file, when one was written.
///
/// The key carries no built-in, because the language nobody chose is the one
/// the host speaks and this build cannot know it in advance. Absence is
/// therefore an answer rather than a failure, which is why the ordinary word
/// reader — which demands a value — does not serve here.
///
/// # Errors
///
/// Returns a configuration failure when the stored value is outside the key's
/// domain.
fn stored_language(config: &Config) -> Result<Option<String>> {
    Ok(match config.resolve("i18n.lang")?.value {
        Some(crate::config::keys::Value::Text(value)) => Some(value),
        _ => None,
    })
}

/// Whether the auxiliary channel carries decoration.
///
/// Decoration is for a person reading a terminal. A channel being collected by
/// another program gets none, because escape sequences there are noise that
/// ends up in whatever file the collector writes.
fn colour_wanted(flags: &GlobalFlags, attended: bool) -> bool {
    !flags.diagnostics.no_color && attended
}

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

    fn flags_from(args: &[&str]) -> GlobalFlags {
        let command_line: Vec<String> = std::iter::once("mariadb-cli")
            .chain(args.iter().copied())
            .chain(["meta", "version"])
            .map(ToOwned::to_owned)
            .collect();
        crate::cli::Cli::try_parse_from(command_line)
            .expect("the sample invocation parses")
            .globals
    }

    fn empty() -> (tempfile::TempDir, Config) {
        let scratch = tempfile::tempdir().expect("scratch directory");
        let config = Config::load(Some(scratch.path())).expect("loads");
        (scratch, config)
    }

    /// Asking for silence must win outright, whatever is stored.
    #[test]
    fn asking_for_silence_leaves_no_level_at_all() {
        let (_scratch, config) = empty();
        assert!(resolve(&config, &flags_from(&["--quiet"]))
            .expect("resolves")
            .level
            .is_none());
    }

    /// Each repetition of the detail mark raises the level one step, so a
    /// caller can ask for more without knowing what is stored.
    #[test]
    fn asking_for_detail_raises_the_level() {
        let (_scratch, config) = empty();
        let quiet_by_default = resolve(&config, &flags_from(&[])).expect("resolves");
        let louder = resolve(&config, &flags_from(&["-vv"])).expect("resolves");
        assert_ne!(quiet_by_default.level, louder.level);
        assert_eq!(louder.level, Some(::tracing::Level::INFO));
    }

    /// The destination is derived from the configuration location, so there is
    /// no second setting that can drift away from the first.
    #[test]
    fn the_destination_sits_under_the_configuration_location() {
        let scratch = tempfile::tempdir().expect("scratch directory");
        let config = Config::load(Some(scratch.path())).expect("loads");
        let flags = flags_from(&["--config-dir", scratch.path().to_str().expect("utf8")]);
        let resolved = resolve(&config, &flags).expect("resolves");
        assert_eq!(resolved.directory, scratch.path().join(DIAGNOSTIC_FOLDER));
    }

    /// Nothing is written to a file unless the stored key asks for it.
    #[test]
    fn no_file_is_written_unless_it_was_asked_for() {
        let (_scratch, config) = empty();
        assert!(
            !resolve(&config, &flags_from(&[]))
                .expect("resolves")
                .to_file
        );
    }

    /// A channel being collected by another program gets no decoration, and
    /// asking for none removes it even from a terminal.
    #[test]
    fn decoration_is_for_a_person_and_never_for_a_collector() {
        assert!(!colour_wanted(&flags_from(&[]), false));
        assert!(colour_wanted(&flags_from(&[]), true));
        assert!(!colour_wanted(&flags_from(&["--no-color"]), true));
    }
}