eclipse-cli 0.13.4

Command-line interface for eclipse
//! The settings list and the one-key write, in text, for both front ends.
//!
//! The full-screen interface and the plain REPL answer `/settings` and `/set` with the same words
//! from the same functions, and both go through `Config::settings` and `config::set_in_text`. That
//! is the whole point of the module: a key catalogue with three readers and three opinions is a
//! key catalogue nobody can trust.

use eclipse_core::config::{self, Config};
use std::path::Path;

/// Every key this build reads, with the value in effect and whether it is the file's answer or the
/// default. `None` for the profile means the base config.
pub fn table(path: &Path, profile: Option<&str>) -> String {
    let cfg = match Config::load_with_profile(Some(path), profile, &config::process_env) {
        Ok(cfg) => cfg,
        Err(e) => return format!("{} does not load: {e}", path.display()),
    };
    let mut out = format!(
        "{} — profile {}, {} key(s)\n",
        path.display(),
        cfg.profile_name(),
        cfg.settings().len()
    );
    for s in cfg.settings() {
        out.push_str(&format!(
            "  {} = {}{}\n",
            s.path(),
            shown(&s),
            if s.is_default() { "  (default)" } else { "" }
        ));
    }
    out.push_str(
        "\n/set <key> <value> writes one; `eclipse config keys` prints this outside the interface",
    );
    out
}

/// A setting as a person may see it. A secret's value never goes to a terminal that is being
/// screenshared, or into a transcript that is being mailed: what is useful to know is whether it
/// is set.
///
/// The one answer for both readers — `/settings` and `config explain` — because the two disagreed:
/// the same key read `(set)` in the interface and `«redacted»` on the page, and only one of those
/// says whether the key took.
pub(crate) fn shown(s: &config::Setting) -> String {
    if s.secret {
        return if s.value.is_some() {
            "(set)".to_string()
        } else {
            "(not set)".to_string()
        };
    }
    s.rendered()
}

/// Write one key, then read the file back and say what it now says.
///
/// `value` is what a person typed: read as TOML when it parses and as a string when it does not,
/// which is the rule `config set` follows because the two share `parse_value`.
///
/// Nothing is written until a copy of the edited file has *loaded*. `set_in_text` already parses the
/// text it produces, but `parse_text` runs none of the checks the loader runs — `validate_routes`,
/// `context.validate`, `validate_bots` — so an edit the next start would refuse was saved over the
/// file that worked, and the refusal arrived as "written, but the file no longer loads" with the
/// working config already gone (`#596`, `#540`). The guard that cannot go stale is the loader
/// itself, so the text is loaded from a copy.
pub fn set_one(
    path: &Path,
    profile: Option<&str>,
    key: &str,
    value: &str,
) -> Result<String, String> {
    let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
    let typed = config::parse_value(value);
    let edited = config::set_in_text(&text, key, &typed)?;
    let cfg = load_before_saving(path, &edited, |p| {
        Ok(Config::load_with_profile(
            Some(p),
            profile,
            &config::process_env,
        )?)
    })?;
    config::save_config_text(path, &edited).map_err(|e| e.to_string())?;
    let setting = cfg
        .setting(key)
        .ok_or_else(|| format!("`{key}` was written but nothing in this build reads it"))?;
    Ok(format!(
        "{} = {}\n{}",
        setting.path(),
        shown(&setting),
        setting.applies.as_str()
    ))
}

/// Load `edited` as the next run would, from a copy beside the file, and take the copy away again.
///
/// The caller supplies the load, because "as the next run would" differs by entry point: `config set`
/// also pins `--route`/`ECLIPSE_ROUTE` (`load_config`), and a guard that skipped that would pass a
/// file the command itself then refuses.
///
/// The copy is written `0600` like the file itself because it holds the same secrets, and its name
/// carries a counter as well as the pid: the dashboard answers several `/set` calls from one
/// process, and two writers sharing a scratch name would delete each other's mid-load (`#337`).
pub(crate) fn load_before_saving(
    path: &Path,
    edited: &str,
    load: impl FnOnce(&Path) -> anyhow::Result<Config>,
) -> Result<Config, String> {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let staged = path.with_extension(format!("toml.check-{}-{n}", std::process::id()));
    config::save_config_text(&staged, edited).map_err(|e| format!("{}: {e}", staged.display()))?;
    let loaded = load(&staged);
    let _ = std::fs::remove_file(&staged);
    loaded.map_err(|e| format!("that would not load, so nothing was saved: {e:#}"))
}

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

    fn written(text: &str) -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, text).unwrap();
        (dir, path)
    }

    /// `#596`: the file was saved before anything proved it loads. `set_in_text` parses the text it
    /// produces, but `parse_text` does not run the checks the *loader* runs — `validate_routes`
    /// among them — so `provider.fallback = ["nope"]` was accepted, written, and only refused by the
    /// next start, with the working file already gone (`#540`). Nothing is written until a copy of
    /// it has loaded the way the next run will load it.
    #[test]
    fn an_edit_the_loader_refuses_is_not_saved() {
        let before = "[provider]\nmodel = \"m\"\n";
        let (_dir, path) = written(before);
        let err = set_one(&path, None, "provider.fallback", "[\"nope\"]").unwrap_err();
        assert!(
            err.contains("nothing was saved"),
            "the refusal says the file is untouched: {err}"
        );
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            before,
            "and it is: the config still holds what it held"
        );
    }

    /// ...and an edit that does load is written and read back, so the check above is not a writer
    /// that refuses everything.
    #[test]
    fn an_edit_that_loads_is_written_and_read_back() {
        let (_dir, path) = written("[provider]\nmodel = \"m\"\n");
        let said = set_one(&path, None, "provider.model", "other-model").unwrap();
        assert!(said.contains("other-model"), "{said}");
        assert!(
            std::fs::read_to_string(&path)
                .unwrap()
                .contains("model = \"other-model\""),
            "the file holds it"
        );
    }
}