oomtop-config 0.2.0

oomtop configuration: layered config, themes, keymaps, JSON Schema, comment-preserving writes
Documentation
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! Comment-preserving writes (UX §12.8, §12.9 `oomtop config set`): edits go through `toml_edit`, so user
//! comments, key order and formatting survive. The result is validated before it is written, and files are
//! replaced atomically (write to a temp file in the same directory, then rename).

use crate::layered::{closest, line_of};
use crate::model::Config;
use crate::paths::ConfigPaths;
use crate::ConfigError;
use std::path::{Path, PathBuf};
use toml_edit::{DocumentMut, InlineTable, Item, Table, TableLike, Value};

/// Which file a setting is saved to (`--layer user|host|dropin:<name>`, the settings screen's `s`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Layer {
    /// `config.toml`.
    User,
    /// `config.d/host-<hostname>.toml`.
    Host,
    /// `config.d/<name>.toml`.
    Dropin(String),
    /// An explicit file (`--config PATH`).
    File(PathBuf),
}

impl Layer {
    /// Parses `user`, `host` or `dropin:<name>`.
    pub fn parse(s: &str) -> Result<Layer, ConfigError> {
        let err = |m: String| ConfigError {
            path: None,
            line: None,
            message: m,
        };
        match s {
            "user" | "config" => Ok(Layer::User),
            "host" => Ok(Layer::Host),
            other => match other.strip_prefix("dropin:") {
                Some(name) => {
                    let stem = name.strip_suffix(".toml").unwrap_or(name);
                    let ok = !stem.is_empty()
                        && !stem.starts_with("host-")
                        && !stem.starts_with('.')
                        && stem
                            .chars()
                            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
                    if ok {
                        Ok(Layer::Dropin(stem.to_string()))
                    } else {
                        Err(err(format!(
                            "invalid drop-in name {name:?}: use letters, digits, '-', '_' (not host-*)"
                        )))
                    }
                }
                None => Err(err(format!(
                    "unknown layer {other:?}: expected user, host or dropin:<name>"
                ))),
            },
        }
    }

    /// The file this layer lives in.
    pub fn path(&self, paths: &ConfigPaths, hostname: &str) -> PathBuf {
        match self {
            Layer::User => paths.config_toml.clone(),
            Layer::Host => paths.host_file(hostname),
            Layer::Dropin(n) => paths.dropin(n),
            Layer::File(p) => p.clone(),
        }
    }
}

/// Parses a value literal ("2", "true", "\"x\"", "[\"a\"]"); anything else becomes a string.
pub fn edit_value(raw: &str) -> Value {
    raw.parse::<Value>().unwrap_or_else(|_| Value::from(raw))
}

fn plain(message: impl Into<String>) -> ConfigError {
    ConfigError {
        path: None,
        line: None,
        message: message.into(),
    }
}

fn parse_doc(text: &str) -> Result<DocumentMut, ConfigError> {
    text.parse().map_err(|e: toml_edit::TomlError| ConfigError {
        path: None,
        line: e.span().map(|s| line_of(text, s.start)),
        message: e.message().to_string(),
    })
}

fn split_key(key: &str) -> Result<Vec<&str>, ConfigError> {
    let parts: Vec<&str> = key.split('.').collect();
    if parts.is_empty() || parts.iter().any(|p| p.trim().is_empty()) {
        return Err(plain(format!("invalid key {key:?}")));
    }
    Ok(parts)
}

enum Target<'a> {
    Table(&'a mut Table),
    Inline(&'a mut InlineTable),
}

/// Descends to (creating as needed) the table that holds the last key part. Missing intermediate tables that
/// only hold sub-tables are created implicit, so no empty `[header]` is written for them.
fn descend<'a>(target: Target<'a>, sections: &[&str]) -> Result<Target<'a>, ConfigError> {
    let Some((first, rest)) = sections.split_first() else {
        return Ok(target);
    };
    match target {
        Target::Table(t) => {
            if t.get(first).is_none_or(Item::is_none) {
                let mut nt = Table::new();
                nt.set_implicit(!rest.is_empty());
                t.insert(first, Item::Table(nt));
            }
            match t.get_mut(first) {
                Some(Item::Table(nt)) => descend(Target::Table(nt), rest),
                Some(Item::Value(Value::InlineTable(it))) => descend(Target::Inline(it), rest),
                _ => Err(plain(format!("{first} is not a table"))),
            }
        }
        Target::Inline(it) => {
            if it.get(first).is_none() {
                it.insert(*first, Value::InlineTable(InlineTable::new()));
            }
            match it.get_mut(first) {
                Some(Value::InlineTable(x)) => descend(Target::Inline(x), rest),
                _ => Err(plain(format!("{first} is not a table"))),
            }
        }
    }
}

/// Sets `key` (dotted) in TOML `text`, returning the new text. Existing comments/decor are kept; values inside
/// inline tables are edited in place.
pub fn set_in_text(text: &str, key: &str, raw_value: &str) -> Result<String, ConfigError> {
    let mut last_err = None;
    let mut candidates = vec![edit_value(raw_value)];
    if !matches!(candidates[0], Value::String(_)) {
        // e.g. `appearance.color 256` is the string "256", not an integer
        candidates.push(Value::from(raw_value));
    }
    let mut rule_err = None;
    for v in candidates {
        match set_value_in_text(text, key, v) {
            Ok(out) => return Ok(out),
            // a value of the right type that breaks a rule ("general.refresh_ms: must be ≥ 250 ms") says
            // more than the type error of the string fallback
            Err(e) if e.message.starts_with(&format!("{key}: ")) => rule_err = rule_err.or(Some(e)),
            Err(e) => last_err = Some(e),
        }
    }
    Err(rule_err.or(last_err).unwrap_or_else(|| plain("no value")))
}

/// True when the document ends in a comment block that belongs to no table: the whole `config init` template
/// while nothing is uncommented yet, or its commented-out remainder after the last real table.
fn has_trailing_comments(doc: &DocumentMut) -> bool {
    doc.trailing().as_str().is_some_and(|t| !t.trim().is_empty())
}

fn set_value_in_text(text: &str, key: &str, v: Value) -> Result<String, ConfigError> {
    let doc = parse_doc(text)?;
    let parts = split_key(key)?;
    // A brand-new section in a file that ends in comments: `toml_edit` would print the new table *before*
    // that trailing block (on a fresh `config init` file: above the header, glued to it). Append it after
    // the comments instead, separated by a blank line, so the file keeps its order.
    if parts.len() >= 2 && !text.is_empty() && has_trailing_comments(&doc) && !doc.contains_key(parts[0]) {
        let section = set_value_in_doc(DocumentMut::new(), key, v)?;
        let out = format!("{}\n\n{section}", text.trim_end());
        validate_text(&out)?;
        return Ok(out);
    }
    let out = set_value_in_doc(doc, key, v)?;
    validate_text(&out)?;
    Ok(out)
}

fn set_value_in_doc(mut doc: DocumentMut, key: &str, mut v: Value) -> Result<String, ConfigError> {
    let parts = split_key(key)?;
    let (leaf, sections) = parts.split_last().ok_or_else(|| plain("empty key"))?;
    let target = descend(Target::Table(doc.as_table_mut()), sections)?;
    match target {
        Target::Table(table) => match table.get_mut(leaf) {
            Some(Item::Value(existing)) => {
                *v.decor_mut() = existing.decor().clone();
                *existing = v;
            }
            Some(Item::None) | None => {
                table.insert(leaf, Item::Value(v));
            }
            Some(_) => return Err(plain(format!("{key} is a table; set one of its keys instead"))),
        },
        Target::Inline(it) => match it.get_mut(leaf) {
            Some(existing) => {
                if existing.is_inline_table() {
                    return Err(plain(format!("{key} is a table; set one of its keys instead")));
                }
                *v.decor_mut() = existing.decor().clone();
                *existing = v;
            }
            None => {
                it.insert(*leaf, v);
                it.fmt();
            }
        },
    }
    Ok(doc.to_string())
}

/// Removes `key` from TOML `text` (comments elsewhere are kept). Returns `Ok(None)` when the key is not set.
pub fn unset_in_text(text: &str, key: &str) -> Result<Option<String>, ConfigError> {
    let mut doc = parse_doc(text)?;
    let parts = split_key(key)?;
    let (leaf, sections) = parts.split_last().ok_or_else(|| plain("empty key"))?;
    let mut table: &mut dyn TableLike = doc.as_table_mut();
    for s in sections {
        match table.get_mut(s).and_then(Item::as_table_like_mut) {
            Some(t) => table = t,
            None => return Ok(None),
        }
    }
    if table.remove(leaf).is_none() {
        return Ok(None);
    }
    let out = doc.to_string();
    validate_text(&out)?;
    Ok(Some(out))
}

/// Every settable dotted key (leaves of the defaults, plus map sections whose keys are user-defined).
pub fn known_keys() -> Vec<String> {
    let t = match toml::Value::try_from(Config::default()) {
        Ok(toml::Value::Table(t)) => t,
        _ => return Vec::new(),
    };
    crate::layered::leaves(&t).into_iter().map(|(k, _)| k).collect()
}

/// Validates a single layer's text — syntax, types and the [`crate::semantic`] rules (ranges, names, formats)
/// — with file:line on errors. Every write goes through this, so `oomtop config set` and the settings screen
/// can never store a value that `oomtop config validate` would reject.
pub fn validate_text(text: &str) -> Result<(), ConfigError> {
    crate::layered::parse_layer(Path::new(""), text)
        .map(|_| ())
        .map_err(|mut e| {
            e.path = None;
            e
        })
}

/// Resolves a symlinked config file to its target (dotfile managers such as stow/chezmoi/home-manager link
/// `~/.config/oomtop/config.toml` into a repo), so an atomic replace edits the real file instead of replacing
/// the link with a plain copy. Relative link targets resolve against the link's directory.
pub(crate) fn resolve_symlinks(path: &Path) -> PathBuf {
    let mut p = path.to_path_buf();
    for _ in 0..16 {
        match std::fs::symlink_metadata(&p) {
            Ok(m) if m.file_type().is_symlink() => match std::fs::read_link(&p) {
                Ok(target) if target.is_absolute() => p = target,
                Ok(target) => p = p.parent().map(|d| d.join(&target)).unwrap_or(target),
                Err(_) => break,
            },
            _ => break,
        }
    }
    p
}

/// Writes `text` to `path` atomically (temp file in the same directory, fsync, rename), creating parent
/// directories. A symlinked `path` keeps its link: the link's target is replaced.
pub fn write_atomic(path: &Path, text: &str) -> Result<(), ConfigError> {
    use std::io::Write;
    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let target = resolve_symlinks(path);
    let dir = target
        .parent()
        .filter(|d| !d.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    std::fs::create_dir_all(dir).map_err(|e| ConfigError::io(path, &e))?;
    let name = target
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "config.toml".into());
    let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let tmp = dir.join(format!(".{name}.tmp-{}-{seq}", std::process::id()));
    let written = std::fs::File::create(&tmp).and_then(|mut f| {
        f.write_all(text.as_bytes())?;
        f.sync_all()
    });
    if let Err(e) = written {
        let _ = std::fs::remove_file(&tmp);
        return Err(ConfigError::io(&tmp, &e));
    }
    if let Ok(meta) = std::fs::metadata(&target) {
        let _ = std::fs::set_permissions(&tmp, meta.permissions());
    }
    std::fs::rename(&tmp, &target).map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        ConfigError::io(path, &e)
    })
}

fn with_path(path: &Path, mut e: ConfigError) -> ConfigError {
    e.path = Some(path.to_path_buf());
    e
}

/// Sets `key` in the file at `path` (created if missing), preserving comments.
pub fn set_value(path: &Path, key: &str, raw_value: &str) -> Result<(), ConfigError> {
    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(ConfigError::io(path, &e)),
    };
    let out = set_in_text(&text, key, raw_value).map_err(|e| with_path(path, suggest(key, e)))?;
    write_atomic(path, &out)
}

/// Removes `key` from the file at `path`; `Ok(false)` when it was not set there.
pub fn unset_value(path: &Path, key: &str) -> Result<bool, ConfigError> {
    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(ConfigError::io(path, &e)),
    };
    match unset_in_text(&text, key).map_err(|e| with_path(path, e))? {
        Some(out) => write_atomic(path, &out).map(|_| true),
        None => Ok(false),
    }
}

/// [`set_value`] plus the checks that need the config directory: a theme or layout that does not exist is
/// refused before anything is written (`oomtop config set appearance.theme nope`).
pub fn set_value_checked(
    paths: &ConfigPaths,
    path: &Path,
    key: &str,
    raw_value: &str,
) -> Result<(), ConfigError> {
    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(ConfigError::io(path, &e)),
    };
    let out = set_in_text(&text, key, raw_value).map_err(|e| with_path(path, suggest(key, e)))?;
    let cfg: Config = toml::from_str(&out).map_err(|e| with_path(path, plain(e.message())))?;
    if let Some(p) = crate::semantic::fs_problems(&cfg, paths)
        .into_iter()
        .find(|p| p.key == key || key.starts_with(&format!("{}.", p.key)))
    {
        return Err(ConfigError {
            path: Some(path.to_path_buf()),
            line: crate::layered::find_line(&out, &p.key),
            message: p.message,
        });
    }
    write_atomic(path, &out)
}

/// Sets `key` in a layer, returning the file written.
pub fn set_in_layer(
    paths: &ConfigPaths,
    hostname: &str,
    layer: &Layer,
    key: &str,
    raw_value: &str,
) -> Result<PathBuf, ConfigError> {
    let path = layer.path(paths, hostname);
    set_value_checked(paths, &path, key, raw_value)?;
    Ok(path)
}

fn suggest(key: &str, mut e: ConfigError) -> ConfigError {
    if e.message.contains("unknown field") && !e.message.contains("did you mean") {
        let keys = known_keys();
        if let Some(c) = closest(key, keys.iter().map(String::as_str)) {
            e.message.push_str(&format!(" — did you mean `{c}`?"));
        }
    }
    e
}

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

    #[test]
    fn preserves_comments_and_order() {
        let text = "# my settings\n[appearance]\n# the theme\ntheme = \"mono\"   # trailing\ndensity = \"compact\"\n\n[general]\nrefresh_ms = 2000\n";
        let out = set_in_text(text, "appearance.theme", "ember").unwrap();
        assert_eq!(
            out,
            "# my settings\n[appearance]\n# the theme\ntheme = \"ember\"   # trailing\ndensity = \"compact\"\n\n[general]\nrefresh_ms = 2000\n"
        );
        let out = set_in_text(&out, "format.decimals", "2").unwrap();
        assert!(out.ends_with("[format]\ndecimals = 2\n"), "{out}");
        assert!(set_in_text(text, "general.refresh_ms", "\"fast\"").is_err());
        assert!(set_in_text(text, "nope.key", "1").is_err());
        assert!(set_in_text(text, "appearance", "1").is_err());
    }

    #[test]
    fn string_fallback_and_nested_tables() {
        let out = set_in_text("", "appearance.color", "256").unwrap();
        assert_eq!(out, "[appearance]\ncolor = \"256\"\n");
        let out = set_in_text("", "personalization.weights.affinity", "0.8").unwrap();
        assert_eq!(out, "[personalization.weights]\naffinity = 0.8\n");
        let out = set_in_text("adapters = { enabled = false }\n", "adapters.timeout_ms", "300").unwrap();
        assert_eq!(out, "adapters = { enabled = false, timeout_ms = 300 }\n");
        let out = set_in_text(
            "[adapters]\nports = { ollama = 1 }\n",
            "adapters.ports.ollama",
            "11434",
        )
        .unwrap();
        assert_eq!(out, "[adapters]\nports = { ollama = 11434 }\n");
        let out = set_in_text("", "aliases.llm", "kind:model,agent").unwrap();
        assert_eq!(out, "[aliases]\nllm = \"kind:model,agent\"\n");
    }

    #[test]
    fn unset_keeps_rest() {
        let text = "# top\n[appearance]\ntheme = \"mono\" # t\n# keep me\ndensity = \"compact\"\n";
        let out = unset_in_text(text, "appearance.theme").unwrap().unwrap();
        assert_eq!(out, "# top\n[appearance]\n# keep me\ndensity = \"compact\"\n");
        assert_eq!(unset_in_text(text, "general.mouse").unwrap(), None);
    }

    #[test]
    fn layers_and_files() {
        let d = tempfile::tempdir().unwrap();
        let paths = ConfigPaths::new(d.path());
        assert_eq!(Layer::parse("user").unwrap(), Layer::User);
        assert_eq!(
            Layer::parse("dropin:50-ui").unwrap(),
            Layer::Dropin("50-ui".into())
        );
        assert!(Layer::parse("dropin:host-x").is_err());
        assert!(Layer::parse("dropin:../x").is_err());
        assert!(Layer::parse("site").is_err());
        let p = set_in_layer(&paths, "air", &Layer::Host, "general.refresh_ms", "3000").unwrap();
        assert_eq!(p, d.path().join("config.d/host-air.toml"));
        assert_eq!(
            std::fs::read_to_string(&p).unwrap(),
            "[general]\nrefresh_ms = 3000\n"
        );
        let p = set_in_layer(
            &paths,
            "air",
            &Layer::Dropin("50-ui".into()),
            "appearance.theme",
            "mint",
        )
        .unwrap();
        assert_eq!(p, d.path().join("config.d/50-ui.toml"));
        assert!(unset_value(&p, "appearance.theme").unwrap());
        assert!(!unset_value(&p, "appearance.theme").unwrap());
        let e = set_value(&paths.config_toml, "appearance.thme", "x").unwrap_err();
        assert!(e.message.contains("did you mean `theme`?"), "{e}");
        assert_eq!(e.line, Some(2));
        assert_eq!(e.path.as_deref(), Some(paths.config_toml.as_path()));
        assert!(!paths.config_toml.exists(), "invalid edits never write");
    }

    #[cfg(unix)]
    #[test]
    fn symlinked_dotfile_keeps_its_link() {
        // regression: rename() over a symlink replaced the link with a plain file (breaks stow/chezmoi repos)
        let d = tempfile::tempdir().unwrap();
        let repo = d.path().join("dotfiles/oomtop");
        std::fs::create_dir_all(&repo).unwrap();
        let real = repo.join("config.toml");
        std::fs::write(&real, "# mine\n[appearance]\ntheme = \"mono\"\n").unwrap();
        let cfg = d.path().join("cfg");
        std::fs::create_dir_all(&cfg).unwrap();
        let link = cfg.join("config.toml");
        std::os::unix::fs::symlink("../dotfiles/oomtop/config.toml", &link).unwrap();
        set_value(&link, "appearance.theme", "ember").unwrap();
        assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
        assert_eq!(
            std::fs::read_to_string(&real).unwrap(),
            "# mine\n[appearance]\ntheme = \"ember\"\n"
        );
        assert!(unset_value(&link, "appearance.theme").unwrap());
        assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
        assert_eq!(std::fs::read_to_string(&real).unwrap(), "# mine\n[appearance]\n");
        // no temp files anywhere
        assert_eq!(std::fs::read_dir(&repo).unwrap().count(), 1);
        assert_eq!(std::fs::read_dir(&cfg).unwrap().count(), 1);
    }

    #[test]
    fn new_section_goes_after_the_template_comments() {
        // regression: on a fresh `config init` file the new table was printed above the header comment,
        // glued to it
        let template = crate::template::init_template();
        let out = set_in_text(&template, "appearance.theme", "ember").unwrap();
        assert!(
            out.starts_with(&template),
            "the template is untouched and stays first"
        );
        assert_eq!(&out[template.len()..], "\n[appearance]\ntheme = \"ember\"\n");
        // a second new section follows the first; an existing one is edited in place
        let out2 = set_in_text(&out, "general.mouse", "false").unwrap();
        assert!(
            out2.ends_with("\n[appearance]\ntheme = \"ember\"\n\n[general]\nmouse = false\n"),
            "{}",
            &out2[template.len()..]
        );
        let out3 = set_in_text(&out2, "appearance.density", "compact").unwrap();
        assert!(
            out3.ends_with(
                "[appearance]\ntheme = \"ember\"\ndensity = \"compact\"\n\n[general]\nmouse = false\n"
            ),
            "{}",
            &out3[template.len()..]
        );
        assert!(out3.starts_with(&template));
        // a real table followed by commented-out template text: the new table goes after the comments
        let text = "[general]\nmouse = false\n\n## Theme and look\n# [appearance]\n# theme = \"terminal\"\n";
        let out = set_in_text(text, "personalization.weights.affinity", "0.8").unwrap();
        assert_eq!(
            out,
            format!("{text}\n[personalization.weights]\naffinity = 0.8\n")
        );
        // comment-only file without a final newline
        let out = set_in_text("# mine", "format.decimals", "2").unwrap();
        assert_eq!(out, "# mine\n\n[format]\ndecimals = 2\n");
    }

    #[test]
    fn writes_are_validated_semantically() {
        // regression: `config set` only type-checked ("validated before writing"); all of these were written
        let d = tempfile::tempdir().unwrap();
        let paths = ConfigPaths::new(d.path());
        let p = &paths.config_toml;
        for (key, value, want) in [
            ("general.refresh_ms", "0", "general.refresh_ms: must be ≥ 250 ms"),
            (
                "headroom.min_margin",
                "banana",
                "headroom.min_margin: must be a size",
            ),
            (
                "headroom.margin_pct",
                "nan",
                "headroom.margin_pct: must be between 0 and 100",
            ),
            (
                "headroom.margin_pct",
                "-50",
                "headroom.margin_pct: must be between 0 and 100",
            ),
            (
                "format.decimals",
                "200",
                "format.decimals: must be between 0 and 3",
            ),
            (
                "keys.preset",
                "bogus",
                "keys.preset: unknown key preset \"bogus\"",
            ),
            (
                "appearance.header",
                "[\"meter\",\"headline\"]",
                "did you mean \"meters\"?",
            ),
            (
                "adapters.timeout_ms",
                "60000",
                "adapters.timeout_ms: must be between 10 and 2000 ms",
            ),
            ("serve.listen", "localhost", "serve.listen: must be host:port"),
            ("layout.name", "../x", "is not a layout name"),
        ] {
            let e = set_value(p, key, value).unwrap_err();
            assert!(e.message.contains(want), "{key} = {value}: {e}");
            assert!(e.line.is_some(), "{key}: {e}");
        }
        assert!(!p.exists(), "invalid edits never write");
        // the settings screen and the CLI both end up in `set_value`; valid values still go through
        set_value(p, "serve.listen", "localhost:9469").unwrap();
        set_value(p, "format.decimals", "3").unwrap();
        set_value(p, "appearance.color", "256").unwrap();
        // with the config directory known, a theme or layout that does not exist is refused too
        let e = set_value_checked(&paths, p, "appearance.theme", "nonexistent").unwrap_err();
        assert_eq!(
            e.to_string(),
            format!("{}:9: theme \"nonexistent\" not found", p.display())
        );
        let e = set_value_checked(&paths, p, "layout.name", "gone").unwrap_err();
        assert!(e.message.contains("no layout \"gone\""), "{e}");
        assert!(!std::fs::read_to_string(p).unwrap().contains("nonexistent"));
        set_value_checked(&paths, p, "appearance.theme", "ember").unwrap();
        std::fs::create_dir_all(&paths.themes).unwrap();
        std::fs::write(paths.theme_file("mine"), "inherits = \"mono\"\n").unwrap();
        set_in_layer(&paths, "air", &Layer::User, "appearance.theme", "mine").unwrap();
        assert!(std::fs::read_to_string(p).unwrap().contains("theme = \"mine\""));
        // an unrelated key is not held hostage by a theme that is already missing
        std::fs::remove_file(paths.theme_file("mine")).unwrap();
        set_value_checked(&paths, p, "general.mouse", "false").unwrap();
    }

    #[test]
    fn unset_reports_unreadable_files() {
        let d = tempfile::tempdir().unwrap();
        assert!(!unset_value(&d.path().join("missing.toml"), "a.b").unwrap());
        // a directory is not readable as a file: an error, not "not set"
        assert!(unset_value(d.path(), "appearance.theme").is_err());
    }

    #[test]
    fn writes_file() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("sub/config.toml");
        set_value(&p, "appearance.theme", "none").unwrap();
        assert_eq!(
            std::fs::read_to_string(&p).unwrap(),
            "[appearance]\ntheme = \"none\"\n"
        );
        let leftovers: Vec<_> = std::fs::read_dir(d.path().join("sub")).unwrap().collect();
        assert_eq!(leftovers.len(), 1, "no temp files left behind");
    }
}