eclipse-cli 0.13.4

Command-line interface for eclipse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! `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"),
        }
        // Through the same reader `/settings` uses: a secret prints as `(set)` or `(not set)`, so
        // this page answers "did my key take" without ever holding the key (`#595`).
        out.push_str(&format!(
            "  now:     {}\n",
            crate::settings_cli::shown(&setting)
        ));
        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
}

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

    /// Not credential-shaped on purpose: a literal that looks like a key is unreadable in a
    /// transcript of this file, and this test is about a word that must not appear.
    const SECRET_VALUE: &str = "value-to-hide";

    fn cfg(body: &str) -> Config {
        eclipse_core::config::parse_text(&format!("[provider]\n{body}")).expect("a config")
    }

    /// `#595` was filed as "`explain` prints a secret's live value". It does not — `Setting::rendered`
    /// is the redaction and every surface goes through it — but what the page printed instead was
    /// `«redacted»`, which cannot tell a key that is set from one that is not, while `/settings`
    /// said `(set)`. Two surfaces, two answers about the same field, and this is the one a person
    /// reads to decide whether the key took.
    #[test]
    fn explaining_a_secret_says_whether_it_is_set_and_never_prints_it() {
        let cfg = cfg(&format!("api_key = \"{SECRET_VALUE}\"\nmodel = \"m\"\n"));
        let text = explain(&cfg, "provider.api_key").expect("the key is in the catalogue");
        assert!(
            !text.contains(SECRET_VALUE),
            "the value reached the page: {text}"
        );
        assert!(
            text.contains("now:     (set)"),
            "it says the key is there without saying what it is: {text}"
        );
        assert!(
            text.contains("a secret"),
            "and says where a secret belongs: {text}"
        );
    }

    /// The other half of the same answer: an unset secret is a fact about the install, and
    /// `«redacted»` for a key nobody has set is the least useful thing the line could say.
    #[test]
    fn explaining_a_secret_that_is_unset_says_it_is_not_set() {
        let cfg = cfg("model = \"m\"\n");
        let text = explain(&cfg, "provider.api_key").expect("the key is in the catalogue");
        assert!(
            text.contains("now:     (not set)"),
            "an unset key says so: {text}"
        );
    }

    /// ...and a value that is not a secret is still printed, so the two above are about the
    /// redaction and not about a page that has stopped showing anything.
    #[test]
    fn explaining_an_ordinary_key_still_prints_its_value() {
        let cfg = cfg(&format!(
            "api_key = \"{SECRET_VALUE}\"\nmodel = \"readable-model\"\n"
        ));
        let text = explain(&cfg, "provider.model").expect("the key is in the catalogue");
        assert!(text.contains("readable-model"), "{text}");
    }
}