eclipse-cli 0.13.2

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.
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`.
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)?;
    config::save_config_text(path, &edited).map_err(|e| e.to_string())?;
    let cfg = Config::load_with_profile(Some(path), profile, &config::process_env)
        .map_err(|e| format!("written, but the file no longer loads: {e}"))?;
    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()
    ))
}