eclipse-cli 0.13.2

Command-line interface for eclipse
//! `eclipse config docs` — the manual for the file, rendered from the settings catalogue.
//!
//! The shipped `config.toml` carries settings and no prose, which is only a kindness if the prose
//! exists somewhere a person can read it. That somewhere is this module, and the point of it is
//! where the words come *from*: [`settings::about`] and [`settings::choices`] are the same two
//! tables the settings window, `config keys` and the dashboard already read, so a key cannot be
//! explained one way in a document and another way in the program. There is no second copy to
//! drift, and nothing here is written by hand except the page around them.
//!
//! Three shapes, one source:
//!
//! - `html` — a self-contained page for a person: one section per table, one row per key, the
//!   default, what it accepts, and when a change takes effect. No fonts, no scripts, no requests;
//!   it opens from the filesystem.
//! - `json` — for a model, or for `jq`: the same rows as objects.
//! - `text` — the same rows for a pipe or a terminal, which is what `explain` prints for one key.
//!
//! `config init` writes the page beside the config (`<config dir>/docs/configuration.html`), so a
//! first install has a manual without being asked, and `config docs` rewrites it whenever the
//! binary has moved on. The environment variables get a section too: they are settings with a
//! different spelling, and a `.env` shipped as nine bare names is a puzzle without it.

use eclipse_core::config::{self, Config};
use eclipse_core::config::{Applies, Kind, Setting};

/// One row of the manual: a setting, or an environment variable.
struct Row {
    name: String,
    kind: &'static str,
    default: String,
    accepts: String,
    about: String,
    restart: bool,
}

fn kind_word(kind: Kind) -> &'static str {
    match kind {
        Kind::Str => "text",
        Kind::Integer => "number",
        Kind::Float => "decimal",
        Kind::Bool => "true / false",
        Kind::List => "list",
        Kind::Datetime => "date",
    }
}

fn rows(cfg: &Config) -> Vec<Row> {
    cfg.settings()
        .into_iter()
        .map(|s: Setting| Row {
            accepts: if s.choices.is_empty() {
                String::new()
            } else {
                s.choices.join(" · ")
            },
            default: s.rendered_default().unwrap_or_else(|| "—".to_string()),
            about: s.about.to_string(),
            restart: s.applies == Applies::RestartProcess,
            kind: kind_word(s.kind),
            name: s.path(),
        })
        .collect()
}

/// The variables, in the order the shipped `.env` lists them, then the rest by class.
fn env_rows() -> Vec<Row> {
    let mut out = Vec::new();
    for (names, class) in [
        (config::ENV_TEMPLATE, "in `.env`"),
        (config::ENV_SHELL_ONLY, "in the shell only"),
        (config::ENV_INTERNAL, "set by this tool"),
    ] {
        for name in names {
            out.push(Row {
                name: (*name).to_string(),
                kind: "text",
                default: "—".to_string(),
                accepts: class.to_string(),
                about: config::env_about(name).to_string(),
                restart: false,
            });
        }
    }
    out
}

/// The manual as text: one line per key, grouped by section, wrapping the description under it.
pub fn text(cfg: &Config) -> String {
    let mut out = String::new();
    let mut section = String::new();
    for row in rows(cfg) {
        let (table, _) = row.name.split_once('.').unwrap_or((&row.name, ""));
        if table != section {
            out.push_str(&format!("\n[{table}]\n"));
            section = table.to_string();
        }
        out.push_str(&format!("  {:<40} {}", row.name, row.kind));
        if row.default != "—" {
            out.push_str(&format!("  default {} ", row.default));
        }
        if row.restart {
            out.push_str("  (restart the background process)");
        }
        out.push('\n');
        if !row.about.is_empty() {
            for line in wrap(&row.about, 84) {
                out.push_str(&format!("      {line}\n"));
            }
        }
        if !row.accepts.is_empty() {
            out.push_str(&format!("      accepts: {}\n", row.accepts));
        }
    }
    out.push_str("\n[environment]  (.env, or the shell — the shell wins)\n");
    for row in env_rows() {
        out.push_str(&format!("  {:<28} {}\n", row.name, row.accepts));
        if !row.about.is_empty() {
            for line in wrap(&row.about, 84) {
                out.push_str(&format!("      {line}\n"));
            }
        }
    }
    out
}

/// One key, or one variable, explained: what `eclipse config explain <name>` prints.
pub fn explain(cfg: &Config, wanted: &str) -> Result<String, String> {
    if let Some(setting) = cfg.settings().into_iter().find(|s| s.path() == wanted) {
        let mut out = format!("{wanted} — {}\n", kind_word(setting.kind));
        if !setting.about.is_empty() {
            out.push_str(&format!("  {}\n", setting.about));
        }
        match setting.rendered_default() {
            Some(value) => out.push_str(&format!("  default: {value}\n")),
            None => out.push_str("  default: none — unset until you set it\n"),
        }
        out.push_str(&format!("  now:     {}\n", setting.rendered()));
        if !setting.choices.is_empty() {
            out.push_str(&format!("  accepts: {}\n", setting.choices.join(" · ")));
        }
        out.push_str(&format!(
            "  takes effect: {}\n  change it:    eclipse config set {wanted} <value>\n",
            setting.applies.as_str()
        ));
        if setting.secret {
            out.push_str("  a secret: set it in .env and refer to it as ${NAME}\n");
        }
        return Ok(out);
    }
    if let Some(row) = env_rows().into_iter().find(|r| r.name == wanted) {
        return Ok(format!(
            "{wanted} — environment variable ({})\n  {}\n",
            row.accepts, row.about
        ));
    }
    Err(format!(
        "`{wanted}` is not a setting this build reads. `eclipse config docs` lists them all; \
         `eclipse config keys` lists the ones in the loaded file."
    ))
}

/// The manual as JSON: an array of objects, one per key and variable.
pub fn json(cfg: &Config) -> String {
    let mut out = String::from("[\n");
    let mut all: Vec<(String, Row)> = rows(cfg)
        .into_iter()
        .map(|r| ("config".to_string(), r))
        .collect();
    all.extend(env_rows().into_iter().map(|r| ("env".to_string(), r)));
    for (index, (source, row)) in all.iter().enumerate() {
        out.push_str(&format!(
            "  {{\"source\":\"{source}\",\"name\":{},\"kind\":{},\"default\":{},\"accepts\":{},\"restart\":{},\"about\":{}}}{}\n",
            json_string(&row.name),
            json_string(row.kind),
            json_string(&row.default),
            json_string(&row.accepts),
            row.restart,
            json_string(&row.about),
            if index + 1 == all.len() { "" } else { "," }
        ));
    }
    out.push_str("]\n");
    out
}

/// The manual as one self-contained page.
pub fn html(cfg: &Config, version: &str) -> String {
    let mut out = String::with_capacity(64 * 1024);
    out.push_str(
        "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
         <title>eclipse — configuration</title>\n<style>\n\
         :root{color-scheme:light dark;--fg:#1a1a1a;--muted:#5c5c5c;--line:#d8d8d8;--bg:#fff;--card:#f6f6f4;--accent:#8a4b09}\n\
         @media (prefers-color-scheme:dark){:root{--fg:#e8e6e1;--muted:#a09a90;--line:#3a3a38;--bg:#151514;--card:#1e1e1c;--accent:#e0a35c}}\n\
         *{box-sizing:border-box}\n\
         body{margin:0;padding:2rem 1.25rem 5rem;background:var(--bg);color:var(--fg);\
         font:16px/1.55 ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif}\n\
         main{max-width:60rem;margin:0 auto}\n\
         h1{font-size:1.6rem;margin:0 0 .35rem}\n\
         h2{font-size:1.1rem;margin:2.5rem 0 .5rem;padding-bottom:.3rem;border-bottom:1px solid var(--line)}\n\
         p.lead{color:var(--muted);margin:.2rem 0 1.5rem}\n\
         code,kbd{font:.92em/1.4 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}\n\
         .convention{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:.9rem 1.1rem;margin:1.5rem 0}\n\
         .convention ul{margin:.4rem 0 0;padding-left:1.1rem}\n\
         table{width:100%;border-collapse:collapse;margin:.4rem 0 0}\n\
         th,td{text-align:left;vertical-align:top;padding:.5rem .6rem;border-bottom:1px solid var(--line);font-size:.94rem}\n\
         th{font-weight:600;color:var(--muted);font-size:.82rem;text-transform:uppercase;letter-spacing:.04em}\n\
         td.key{white-space:nowrap;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:.9rem}\n\
         td.def{white-space:nowrap;color:var(--muted);font-family:ui-monospace,Menlo,Consolas,monospace;font-size:.88rem}\n\
         .tag{display:inline-block;margin-left:.35rem;padding:0 .35rem;border:1px solid var(--line);border-radius:4px;\
         font-size:.72rem;color:var(--muted);vertical-align:middle}\n\
         .when{display:block;color:var(--accent);font-size:.8rem;margin-top:.15rem}\n\
         nav ol{columns:2;margin:.4rem 0;padding-left:1.2rem}\n\
         a{color:var(--accent)}\n\
         footer{margin-top:3rem;color:var(--muted);font-size:.85rem}\n\
         </style>\n</head>\n<body>\n<main>\n",
    );
    out.push_str(&format!(
        "<h1>Configuration</h1>\n<p class=\"lead\">Every setting this build reads, and every \
         environment variable it looks at. Generated from the binary itself — eclipse {},\
         config_version {} — so this page and the program cannot disagree.</p>\n",
        escape(version),
        config::CONFIG_VERSION
    ));
    out.push_str(
        "<div class=\"convention\"><strong>How the file reads.</strong>\n<ul>\
         <li><code>key = value</code> — the setting is in use at that value.</li>\
         <li><code>key = \"\"</code> — not in use. An empty value is the same as an absent one.</li>\
         <li><code># key =</code> — not in use, and no value could say so (a number, a colour). \
         Uncomment it and give it a value, or run <code>eclipse config set</code> and it is done for you.</li>\
         <li><code># eclipse config set provider.model qwen3.8-27b</code> — the way to change one key \
         without touching the rest of the file, comments and order included.</li>\
         </ul></div>\n",
    );

    // Table of contents, then a section per config table, then the environment.
    let all_rows = rows(cfg);
    let mut sections: Vec<&str> = Vec::new();
    for row in &all_rows {
        let table = row.name.split('.').next().unwrap_or("");
        if !sections.contains(&table) {
            sections.push(table);
        }
    }
    out.push_str("<nav><strong>Sections</strong><ol>\n");
    for table in &sections {
        out.push_str(&format!(
            "<li><a href=\"#{}\">{}</a></li>\n",
            escape(table),
            escape(table)
        ));
    }
    out.push_str("<li><a href=\"#environment\">environment</a></li>\n</ol></nav>\n");

    for table in sections {
        out.push_str(&format!(
            "\n<h2 id=\"{}\">[{}]</h2>\n<table>\n<thead><tr><th>key</th><th>default</th>\
             <th>accepts</th><th>what it does</th></tr></thead>\n<tbody>\n",
            escape(table),
            escape(table)
        ));
        for row in all_rows
            .iter()
            .filter(|r| r.name.starts_with(&format!("{table}.")))
        {
            let key = row
                .name
                .strip_prefix(&format!("{table}."))
                .unwrap_or(&row.name);
            out.push_str(&format!(
                "<tr><td class=\"key\">{}</td><td class=\"def\">{}</td><td>{}</td><td>{}{}</td></tr>\n",
                escape(key),
                escape(&row.default),
                escape(&row.accepts),
                escape(&row.about),
                if row.restart {
                    "<span class=\"when\">takes effect when the dashboard restarts</span>"
                } else {
                    ""
                }
            ));
        }
        out.push_str("</tbody>\n</table>\n");
    }

    out.push_str(
        "\n<h2 id=\"environment\">environment</h2>\n<p class=\"lead\">The shell wins over \
         <code>.env</code>, and an empty value is not set.</p>\n<table>\n<thead><tr>\
         <th>variable</th><th>where</th><th>what it does</th></tr></thead>\n<tbody>\n",
    );
    for row in env_rows() {
        out.push_str(&format!(
            "<tr><td class=\"key\">{}</td><td class=\"def\">{}</td><td>{}</td></tr>\n",
            escape(&row.name),
            escape(&row.accepts),
            escape(&row.about)
        ));
    }
    out.push_str("</tbody>\n</table>\n");
    out.push_str(
        "<footer><p>The file is at <code>eclipse config path</code>; what this machine has set is \
         <code>eclipse config show</code>; a key nothing reads is <code>eclipse config check</code>.</p>\
         </footer>\n</main>\n</body>\n</html>\n",
    );
    out
}

/// The directory the manual lives in, beside the config.
fn docs_dir(config_path: &std::path::Path) -> std::path::PathBuf {
    config_path
        .parent()
        .unwrap_or(std::path::Path::new("."))
        .join("docs")
}

/// Where the page lives for this install.
pub fn page_path(config_path: &std::path::Path) -> std::path::PathBuf {
    docs_dir(config_path).join("configuration.html")
}

/// The same manual as plain text, written beside the page.
///
/// Two readers, two files: a person opens the HTML, and the agent that has to answer "what does
/// `memory_budget_chars` accept" pages through something without markup in it. One `text` renderer
/// already existed for `--format text`; writing it to disk costs nothing and means a model never has
/// to run a program to read the documentation for that program.
pub fn text_path(config_path: &std::path::Path) -> std::path::PathBuf {
    docs_dir(config_path).join("configuration.txt")
}

/// Write the manual beside the config — the page and its text twin. Best effort by design: a manual
/// that cannot be written must never fail the command that asked for it, so the caller decides what
/// to say.
pub fn write_page(
    config_path: &std::path::Path,
    cfg: &Config,
    version: &str,
) -> std::io::Result<std::path::PathBuf> {
    let path = page_path(config_path);
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    std::fs::write(&path, html(cfg, version))?;
    std::fs::write(text_path(config_path), text(cfg))?;
    Ok(path)
}

/// JSON string escaping, which is not HTML escaping: `&quot;` inside a JSON string is five wrong
/// characters, and a `\` or a quote in a description would break the document a model parses.
fn json_string(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for c in text.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

fn escape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            '\n' => out.push(' '),
            _ => out.push(c),
        }
    }
    out
}

/// Greedy wrap for the terminal, so a long description is readable in an 80-column window.
fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let mut line = String::new();
    for word in text.split_whitespace() {
        if !line.is_empty() && line.len() + 1 + word.len() > width {
            lines.push(std::mem::take(&mut line));
        }
        if !line.is_empty() {
            line.push(' ');
        }
        line.push_str(word);
    }
    if !line.is_empty() {
        lines.push(line);
    }
    lines
}