oomtop-config 0.2.1

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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! Live reload (UX §12.2, §11 test 9): all config files are watched and reloaded on save, debounced 200 ms.
//! An invalid edit keeps the last good config and reports file:line (see [`crate::layered::LayerCache`]).
//!
//! - [`watch`] is the low-level primitive: watch paths, call `on_change` once per burst of events.
//! - [`LiveConfig`] is what frontends use: it owns a [`Loaded`], re-runs the layered load on every change and
//!   exposes the current config, the latest errors and a generation counter to poll each frame.

use crate::layered::{load_layered_cached, LayerCache, LoadOptions, Loaded};
use crate::ConfigError;
use notify::{RecursiveMode, Watcher};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{mpsc, Arc, Mutex, Weak};
use std::time::{Duration, Instant};

/// Quiet period that ends a burst of file events.
pub const DEBOUNCE: Duration = Duration::from_millis(200);
/// A burst never delays a reload longer than this (editors that write in many steps).
pub const MAX_DELAY: Duration = Duration::from_millis(600);

/// Fastest allowed polling interval for [`WatchMode::from_poll_ms`].
pub const MIN_POLL: Duration = Duration::from_millis(100);

/// Watch backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WatchMode {
    /// FSEvents / inotify.
    Native,
    /// Polling at the given interval (network filesystems, tests).
    Poll(Duration),
}

impl WatchMode {
    /// From `general.watch_poll_ms` (0 = native). Polls faster than [`MIN_POLL`] are raised to it: polling
    /// compares file contents, and a 1 ms loop would blow the CPU budget (SPEC §14).
    pub fn from_poll_ms(ms: u64) -> WatchMode {
        if ms == 0 {
            WatchMode::Native
        } else {
            WatchMode::Poll(Duration::from_millis(ms).max(MIN_POLL))
        }
    }
}

type SharedWatcher = Arc<Mutex<Box<dyn Watcher + Send>>>;
/// A non-owning handle to the watcher (used from its own callback).
type WeakWatcher = Weak<Mutex<Box<dyn Watcher + Send>>>;

/// Keeps the watcher alive; dropping it stops watching.
pub struct ConfigWatcher {
    watcher: SharedWatcher,
    _thread: std::thread::JoinHandle<()>,
}

impl ConfigWatcher {
    /// Adds a path (recursive for directories when `recursive`).
    pub fn add(&self, path: &std::path::Path, recursive: bool) -> Result<(), ConfigError> {
        add_path(&self.watcher, path, recursive)
    }
}

fn add_path(w: &SharedWatcher, path: &std::path::Path, recursive: bool) -> Result<(), ConfigError> {
    let mode = if recursive && path.is_dir() {
        RecursiveMode::Recursive
    } else {
        RecursiveMode::NonRecursive
    };
    let mut guard = w.lock().map_err(|_| ConfigError {
        path: None,
        line: None,
        message: "watch: lock poisoned".into(),
    })?;
    guard.watch(path, mode).map_err(|e| ConfigError {
        path: Some(path.to_path_buf()),
        line: None,
        message: format!("watch: {e}"),
    })
}

impl std::fmt::Debug for ConfigWatcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ConfigWatcher")
    }
}

fn relevant(ev: &notify::Event) -> bool {
    if matches!(ev.kind, notify::EventKind::Access(_)) {
        return false;
    }
    // ignore our own atomic-write temp files and editor swap files
    ev.paths.is_empty()
        || ev.paths.iter().any(|p| {
            let name = p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
            !(name.starts_with('.') && name.contains(".tmp-")
                || name.ends_with('~')
                || name.ends_with(".swp")
                || name.ends_with(".swx")
                || name == "4913")
        })
}

/// Watches `paths` (directories recursively, files directly; missing ones are skipped) and calls `on_change`
/// once per burst.
pub fn watch(
    paths: Vec<PathBuf>,
    mode: WatchMode,
    on_change: impl Fn() + Send + 'static,
) -> Result<ConfigWatcher, ConfigError> {
    watch_entries(paths.into_iter().map(|p| (p, true)).collect(), mode, on_change)
}

/// [`watch`] with explicit recursion per path.
pub fn watch_entries(
    entries: Vec<(PathBuf, bool)>,
    mode: WatchMode,
    on_change: impl Fn() + Send + 'static,
) -> Result<ConfigWatcher, ConfigError> {
    let (tx, rx) = mpsc::channel::<()>();
    let handler = move |res: notify::Result<notify::Event>| {
        if let Ok(ev) = res {
            if relevant(&ev) {
                let _ = tx.send(());
            }
        }
    };
    let err = |e: notify::Error| ConfigError {
        path: None,
        line: None,
        message: format!("watch: {e}"),
    };
    let watcher: Box<dyn Watcher + Send> = match mode {
        WatchMode::Native => Box::new(notify::recommended_watcher(handler).map_err(err)?),
        WatchMode::Poll(iv) => Box::new(
            notify::PollWatcher::new(
                handler,
                notify::Config::default()
                    .with_poll_interval(iv)
                    .with_compare_contents(true),
            )
            .map_err(err)?,
        ),
    };
    let watcher: SharedWatcher = Arc::new(Mutex::new(watcher));
    for (p, recursive) in &entries {
        if p.exists() {
            add_path(&watcher, p, *recursive)?;
        }
    }
    let thread = std::thread::Builder::new()
        .name("oomtop-config-watch".into())
        .spawn(move || {
            while rx.recv().is_ok() {
                // debounce: wait for DEBOUNCE of quiet, but never longer than MAX_DELAY in total
                let start = Instant::now();
                loop {
                    let left = MAX_DELAY.saturating_sub(start.elapsed());
                    if left.is_zero() {
                        break;
                    }
                    match rx.recv_timeout(DEBOUNCE.min(left)) {
                        Ok(()) => continue,
                        Err(mpsc::RecvTimeoutError::Timeout) => break,
                        Err(mpsc::RecvTimeoutError::Disconnected) => return,
                    }
                }
                on_change();
            }
        })
        .map_err(|e| ConfigError {
            path: None,
            line: None,
            message: format!("watch thread: {e}"),
        })?;
    Ok(ConfigWatcher {
        watcher,
        _thread: thread,
    })
}

/// Directories holding the targets of symlinked files in the config dir and its sub-directories
/// (`config.d`, `themes`, `layouts`, `rules.d`), deduplicated.
fn symlink_target_dirs(dir: &Path) -> Vec<PathBuf> {
    let mut out: Vec<PathBuf> = Vec::new();
    let subdirs = ["", "config.d", "themes", "layouts", "rules.d"];
    for sub in subdirs {
        let Ok(rd) = std::fs::read_dir(dir.join(sub)) else {
            continue;
        };
        for e in rd.flatten() {
            let p = e.path();
            let is_link = std::fs::symlink_metadata(&p).is_ok_and(|m| m.file_type().is_symlink());
            if !is_link || p.is_dir() {
                continue;
            }
            let target = crate::write::resolve_symlinks(&p);
            if let Some(parent) = target.parent().filter(|d| d.is_dir()) {
                let parent = parent.to_path_buf();
                if !out.contains(&parent) {
                    out.push(parent);
                }
            }
        }
    }
    out
}

fn nearest_existing_ancestor(dir: &Path) -> Option<PathBuf> {
    dir.ancestors()
        .skip(1)
        // the parent of a one-component relative path is "", i.e. the current directory
        .map(|a| {
            if a.as_os_str().is_empty() {
                Path::new(".")
            } else {
                a
            }
        })
        .find(|a| a.is_dir())
        .map(Path::to_path_buf)
}

struct Shared {
    opts: LoadOptions,
    cache: LayerCache,
    loaded: Loaded,
}

/// A config that reloads itself when its files change.
pub struct LiveConfig {
    shared: Arc<Mutex<Shared>>,
    generation: Arc<AtomicU64>,
    _watcher: Option<ConfigWatcher>,
}

impl std::fmt::Debug for LiveConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LiveConfig")
            .field("generation", &self.generation())
            .finish()
    }
}

fn reload(shared: &Mutex<Shared>, generation: &AtomicU64) {
    if let Ok(mut s) = shared.lock() {
        let Shared { opts, cache, loaded } = &mut *s;
        let fresh = load_layered_cached(opts, cache);
        // runtime toggles survive reloads
        let runtime: Vec<(String, String)> = loaded
            .origins
            .iter()
            .filter(|(_, o)| **o == crate::layered::Origin::Runtime)
            .filter_map(|(k, _)| loaded.value(k).map(|v| (k.clone(), v)))
            .collect();
        let mut fresh = fresh;
        for (k, v) in runtime {
            let _ = fresh.set_runtime(&k, &v);
        }
        *loaded = fresh;
        generation.fetch_add(1, Ordering::SeqCst);
    }
}

/// What to watch for a set of load options, as (path, recursive) entries. This is the **only** safe way to
/// derive watch paths — never watch [`crate::paths::ConfigPaths::watch_paths`] recursively:
///
/// - the user config directory, recursively (it holds `config.d/`, `themes/`, `layouts/`, `rules.d/`);
/// - if it does not exist yet (the normal state: oomtop needs no config), its nearest existing ancestor
///   **non-recursively** — so creating the directory is noticed without a recursive watch of `~/.config` or
///   `$HOME` (every write by any other program would otherwise trigger a reload, and on Linux the whole tree
///   would be walked to add inotify watches);
/// - with an explicit `--config` file, whose directory can be anything (`--config ~/my.toml`): that
///   directory **non-recursively** (editors save by renaming over the file, which ends a watch on the file
///   itself) plus the `config.d/`, `themes/`, `layouts/` and `rules.d/` next to it that exist; a bare
///   relative `--config my.toml` means the current directory;
/// - the system layer (`/etc/oomtop`), recursively, when it exists;
/// - the directories that hold the targets of symlinked config files (dotfile managers), non-recursively.
pub fn watch_plan(opts: &LoadOptions) -> Vec<(PathBuf, bool)> {
    let dir = opts.user_dir();
    let mut entries: Vec<(PathBuf, bool)> = Vec::new();
    let add = |entries: &mut Vec<(PathBuf, bool)>, p: PathBuf, recursive: bool| {
        let covered = entries
            .iter()
            .any(|(e, rec)| *e == p || (*rec && p.starts_with(e)));
        if !covered && !p.as_os_str().is_empty() {
            entries.push((p, recursive));
        }
    };
    if opts.explicit_config().is_some() {
        // `dir` is the file's directory here
        if dir.is_dir() {
            add(&mut entries, dir.clone(), false);
            for sub in ["config.d", "themes", "layouts", "rules.d"] {
                let p = dir.join(sub);
                if p.is_dir() {
                    add(&mut entries, p, false);
                }
            }
        } else if let Some(anc) = nearest_existing_ancestor(&dir) {
            add(&mut entries, anc, false);
        }
    } else if dir.is_dir() {
        add(&mut entries, dir.clone(), true);
    } else if let Some(anc) = nearest_existing_ancestor(&dir) {
        add(&mut entries, anc, false);
    }
    if let Some(sys) = opts.system() {
        if sys.is_dir() {
            add(&mut entries, sys, true);
        }
    }
    for target_dir in symlink_target_dirs(&dir) {
        add(&mut entries, target_dir, false);
    }
    entries
}

/// Watches everything in [`watch_plan`] and calls `on_change` once per burst of events (debounced). When the
/// config directory does not exist yet, the watch moves closer as its ancestors appear and becomes a
/// recursive watch of the directory itself once it is created. Dropping the result stops watching.
///
/// Frontends that keep their own [`Loaded`] (the TUI) use this; [`LiveConfig`] is this plus the reload.
pub fn watch_config(
    opts: &LoadOptions,
    mode: WatchMode,
    on_change: impl Fn() + Send + 'static,
) -> Result<ConfigWatcher, ConfigError> {
    let entries = watch_plan(opts);
    // Weak: the callback runs on the watcher's own thread; a strong reference here would keep the watcher
    // (and that thread) alive forever after the handle is dropped.
    let slot: Arc<Mutex<Option<WeakWatcher>>> = Arc::new(Mutex::new(None));
    let slot2 = slot.clone();
    let opts = opts.clone();
    let watched: Mutex<Vec<(PathBuf, bool)>> = Mutex::new(entries.clone());
    let w = watch_entries(entries, mode, move || {
        // The plan changes as directories appear (the config dir itself, an intermediate ancestor such as
        // ~/.config, a `themes/` next to a --config file, a new symlink target): add what is new.
        let watcher = slot2.lock().ok().and_then(|g| g.as_ref().and_then(Weak::upgrade));
        if let (Some(w), Ok(mut seen)) = (watcher, watched.lock()) {
            for (p, recursive) in watch_plan(&opts) {
                if !seen.contains(&(p.clone(), recursive)) && add_path(&w, &p, recursive).is_ok() {
                    seen.push((p, recursive));
                }
            }
        }
        on_change()
    })?;
    if let Ok(mut g) = slot.lock() {
        *g = Some(Arc::downgrade(&w.watcher));
    }
    Ok(w)
}

impl LiveConfig {
    /// Loads once and starts watching (see [`watch_plan`]) when `live` is true.
    pub fn start(opts: LoadOptions, mode: WatchMode, live: bool) -> Result<LiveConfig, ConfigError> {
        let mut cache = LayerCache::new();
        let loaded = load_layered_cached(&opts, &mut cache);
        let watch_opts = opts.clone();
        let shared = Arc::new(Mutex::new(Shared { opts, cache, loaded }));
        let generation = Arc::new(AtomicU64::new(0));
        let watcher = if live {
            let (s, g) = (shared.clone(), generation.clone());
            Some(watch_config(&watch_opts, mode, move || reload(&s, &g))?)
        } else {
            None
        };
        Ok(LiveConfig {
            shared,
            generation,
            _watcher: watcher,
        })
    }

    /// Increments on every reload; compare with the last value seen to know when to re-read.
    pub fn generation(&self) -> u64 {
        self.generation.load(Ordering::SeqCst)
    }

    /// The current (last good) state.
    pub fn current(&self) -> Loaded {
        match self.shared.lock() {
            Ok(s) => s.loaded.clone(),
            Err(p) => p.into_inner().loaded.clone(),
        }
    }

    /// Errors of the latest load (shown inline with file:line).
    pub fn errors(&self) -> Vec<ConfigError> {
        self.current().errors
    }

    /// Reloads now (e.g. after the settings screen saved a file).
    pub fn reload_now(&self) {
        reload(&self.shared, &self.generation);
    }

    /// Applies a runtime toggle (kept across reloads, never persisted).
    pub fn set_runtime(&self, key: &str, value: &str) -> Result<(), ConfigError> {
        let mut s = self.shared.lock().map_err(|_| ConfigError {
            path: None,
            line: None,
            message: "config lock poisoned".into(),
        })?;
        s.loaded.set_runtime(key, value)?;
        self.generation.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::AtomicUsize;

    #[test]
    fn reload_fires_after_edit() {
        let d = tempfile::tempdir().unwrap();
        let f = d.path().join("config.toml");
        std::fs::write(&f, "[appearance]\ntheme = \"terminal\"\n").unwrap();
        let hits = Arc::new(AtomicUsize::new(0));
        let h = hits.clone();
        let _w = watch(
            vec![d.path().to_path_buf()],
            WatchMode::Poll(Duration::from_millis(50)),
            move || {
                h.fetch_add(1, Ordering::SeqCst);
            },
        )
        .unwrap();
        std::thread::sleep(Duration::from_millis(150));
        std::fs::write(&f, "[appearance]\ntheme = \"none\"\n").unwrap();
        let start = Instant::now();
        while hits.load(Ordering::SeqCst) == 0 && start.elapsed() < Duration::from_secs(5) {
            std::thread::sleep(Duration::from_millis(20));
        }
        assert!(
            hits.load(Ordering::SeqCst) >= 1,
            "reload within 1 s target (5 s test cap)"
        );
    }

    #[test]
    fn config_dir_created_later_is_picked_up() {
        let d = tempfile::tempdir().unwrap();
        let dir = d.path().join("cfg/oomtop");
        std::fs::create_dir_all(d.path().join("cfg")).unwrap();
        let live = LiveConfig::start(
            LoadOptions {
                config_dir: Some(dir.clone()),
                system_dir: Some(PathBuf::new()),
                hostname: Some("h".into()),
                env: Some(vec![]),
                ..Default::default()
            },
            WatchMode::Poll(Duration::from_millis(50)),
            true,
        )
        .unwrap();
        assert_eq!(live.current().config.appearance.theme, "terminal");
        std::thread::sleep(Duration::from_millis(150));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("config.toml"), "[appearance]\ntheme = \"sand\"\n").unwrap();
        let start = Instant::now();
        while live.current().config.appearance.theme != "sand" && start.elapsed() < Duration::from_secs(5) {
            std::thread::sleep(Duration::from_millis(20));
        }
        assert_eq!(live.current().config.appearance.theme, "sand");
        // edits inside the new dir are seen too
        std::thread::sleep(Duration::from_millis(150));
        std::fs::write(dir.join("config.toml"), "[appearance]\ntheme = \"mint\"\n").unwrap();
        let start = Instant::now();
        while live.current().config.appearance.theme != "mint" && start.elapsed() < Duration::from_secs(5) {
            std::thread::sleep(Duration::from_millis(20));
        }
        assert_eq!(live.current().config.appearance.theme, "mint");
    }

    #[test]
    fn dropping_live_config_stops_the_watcher() {
        // regression: the "add the dir once it appears" callback held a strong reference to the watcher, so
        // the watcher thread (and the shared config) lived forever after LiveConfig was dropped
        let d = tempfile::tempdir().unwrap();
        for dir_exists in [false, true] {
            let dir = d.path().join(format!("c{dir_exists}/oomtop"));
            std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
            if dir_exists {
                std::fs::create_dir_all(&dir).unwrap();
            }
            let live = LiveConfig::start(
                LoadOptions {
                    config_dir: Some(dir),
                    system_dir: Some(PathBuf::new()),
                    hostname: Some("h".into()),
                    env: Some(vec![]),
                    ..Default::default()
                },
                WatchMode::Poll(Duration::from_millis(30)),
                true,
            )
            .unwrap();
            let weak = Arc::downgrade(&live.shared);
            drop(live);
            let start = Instant::now();
            while weak.upgrade().is_some() && start.elapsed() < Duration::from_secs(5) {
                std::thread::sleep(Duration::from_millis(20));
            }
            assert!(
                weak.upgrade().is_none(),
                "watcher thread still alive (dir_exists={dir_exists})"
            );
        }
    }

    #[test]
    fn external_config_file_survives_rename_saves() {
        // `--config /elsewhere/my.toml`: editors save by renaming over the file; the parent is watched
        let d = tempfile::tempdir().unwrap();
        let other = d.path().join("elsewhere");
        std::fs::create_dir_all(&other).unwrap();
        let main = other.join("my.toml");
        std::fs::write(&main, "[appearance]\ntheme = \"mono\"\n").unwrap();
        let live = LiveConfig::start(
            LoadOptions {
                config_path: Some(main.clone()),
                config_dir: Some(d.path().join("cfg/oomtop")),
                system_dir: Some(PathBuf::new()),
                hostname: Some("h".into()),
                env: Some(vec![]),
                ..Default::default()
            },
            WatchMode::Poll(Duration::from_millis(40)),
            true,
        )
        .unwrap();
        assert_eq!(live.current().config.appearance.theme, "mono");
        for theme in ["sand", "mint"] {
            std::thread::sleep(Duration::from_millis(120));
            let tmp = other.join(".my.toml.swap");
            std::fs::write(&tmp, format!("[appearance]\ntheme = \"{theme}\"\n")).unwrap();
            std::fs::rename(&tmp, &main).unwrap();
            let start = Instant::now();
            while live.current().config.appearance.theme != theme && start.elapsed() < Duration::from_secs(5)
            {
                std::thread::sleep(Duration::from_millis(20));
            }
            assert_eq!(live.current().config.appearance.theme, theme);
        }
    }

    #[cfg(unix)]
    #[test]
    fn edits_at_a_symlink_target_reload() {
        let d = tempfile::tempdir().unwrap();
        let repo = d.path().join("dotfiles");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::write(repo.join("oomtop.toml"), "[appearance]\ntheme = \"mono\"\n").unwrap();
        let dir = d.path().join("cfg/oomtop");
        std::fs::create_dir_all(&dir).unwrap();
        std::os::unix::fs::symlink(repo.join("oomtop.toml"), dir.join("config.toml")).unwrap();
        assert_eq!(symlink_target_dirs(&dir), vec![repo.clone()]);
        let live = LiveConfig::start(
            LoadOptions {
                config_dir: Some(dir),
                system_dir: Some(PathBuf::new()),
                hostname: Some("h".into()),
                env: Some(vec![]),
                ..Default::default()
            },
            WatchMode::Poll(Duration::from_millis(40)),
            true,
        )
        .unwrap();
        assert_eq!(live.current().config.appearance.theme, "mono");
        std::thread::sleep(Duration::from_millis(120));
        // the dotfile repo's editor saves by rename, at the target
        std::fs::write(repo.join(".tmp"), "[appearance]\ntheme = \"coral\"\n").unwrap();
        std::fs::rename(repo.join(".tmp"), repo.join("oomtop.toml")).unwrap();
        let start = Instant::now();
        while live.current().config.appearance.theme != "coral" && start.elapsed() < Duration::from_secs(5) {
            std::thread::sleep(Duration::from_millis(20));
        }
        assert_eq!(live.current().config.appearance.theme, "coral");
    }

    #[test]
    fn plan_never_watches_an_ancestor_recursively() {
        // regression: with no config dir yet, the nearest ancestor (~/.config or $HOME) was watched
        // recursively, so any program writing there triggered a reload
        let d = tempfile::tempdir().unwrap();
        let home_cfg = d.path().join("dotconfig");
        std::fs::create_dir_all(&home_cfg).unwrap();
        let mut o = LoadOptions {
            config_dir: Some(home_cfg.join("oomtop")),
            system_dir: Some(PathBuf::new()),
            hostname: Some("h".into()),
            env: Some(vec![]),
            ..Default::default()
        };
        assert_eq!(watch_plan(&o), vec![(home_cfg.clone(), false)]);
        // once it exists: the directory itself, recursively, and nothing above it
        std::fs::create_dir_all(home_cfg.join("oomtop/themes")).unwrap();
        assert_eq!(watch_plan(&o), vec![(home_cfg.join("oomtop"), true)]);
        // an explicit --config can sit anywhere (even in $HOME): its directory is never watched recursively
        let other = d.path().join("elsewhere");
        std::fs::create_dir_all(other.join("themes")).unwrap();
        std::fs::create_dir_all(other.join("unrelated/deep")).unwrap();
        o.config_path = Some(other.join("my.toml"));
        assert_eq!(
            watch_plan(&o),
            vec![(other.clone(), false), (other.join("themes"), false)]
        );
        // a bare relative --config is the current directory, not "nothing"
        o.config_path = Some(PathBuf::from("my.toml"));
        o.config_dir = None;
        assert_eq!(o.user_dir(), PathBuf::from("."));
        let plan = watch_plan(&o);
        assert_eq!(plan[0], (PathBuf::from("."), false));
        assert!(plan.iter().all(|(_, recursive)| !recursive), "{plan:?}");
        // an empty OOMTOP_CONFIG is "unset"
        o.config_path = Some(PathBuf::new());
        o.config_dir = Some(home_cfg.join("oomtop"));
        assert_eq!(watch_plan(&o), vec![(home_cfg.join("oomtop"), true)]);
    }

    #[cfg(unix)]
    #[test]
    fn plan_includes_symlink_target_dirs() {
        let d = tempfile::tempdir().unwrap();
        let repo = d.path().join("dotfiles");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::write(repo.join("oomtop.toml"), "").unwrap();
        let dir = d.path().join("cfg/oomtop");
        std::fs::create_dir_all(&dir).unwrap();
        std::os::unix::fs::symlink(repo.join("oomtop.toml"), dir.join("config.toml")).unwrap();
        let o = LoadOptions {
            config_dir: Some(dir.clone()),
            system_dir: Some(PathBuf::new()),
            hostname: Some("h".into()),
            env: Some(vec![]),
            ..Default::default()
        };
        assert_eq!(watch_plan(&o), vec![(dir, true), (repo, false)]);
    }

    #[test]
    fn watch_config_calls_back_without_owning_a_loaded() {
        let d = tempfile::tempdir().unwrap();
        let dir = d.path().join("cfg/oomtop");
        std::fs::create_dir_all(d.path().join("cfg")).unwrap();
        let o = LoadOptions {
            config_dir: Some(dir.clone()),
            system_dir: Some(PathBuf::new()),
            hostname: Some("h".into()),
            env: Some(vec![]),
            ..Default::default()
        };
        let hits = Arc::new(AtomicUsize::new(0));
        let h = hits.clone();
        let _w = watch_config(&o, WatchMode::Poll(Duration::from_millis(40)), move || {
            h.fetch_add(1, Ordering::SeqCst);
        })
        .unwrap();
        std::thread::sleep(Duration::from_millis(120));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("config.toml"), "[appearance]\ntheme = \"sand\"\n").unwrap();
        let wait = |n: usize| {
            let start = Instant::now();
            while hits.load(Ordering::SeqCst) < n && start.elapsed() < Duration::from_secs(5) {
                std::thread::sleep(Duration::from_millis(20));
            }
            hits.load(Ordering::SeqCst)
        };
        let first = wait(1);
        assert!(first >= 1, "creating the config dir is noticed");
        // the directory itself is now watched: a later edit inside it calls back again
        std::thread::sleep(Duration::from_millis(700));
        let before = hits.load(Ordering::SeqCst);
        std::fs::write(dir.join("config.toml"), "[appearance]\ntheme = \"mint\"\n").unwrap();
        assert!(wait(before + 1) > before, "edits inside the new dir are seen");
    }

    #[test]
    fn temp_and_swap_files_are_ignored() {
        let ev = |name: &str| notify::Event {
            kind: notify::EventKind::Create(notify::event::CreateKind::File),
            paths: vec![PathBuf::from(format!("/c/{name}"))],
            attrs: Default::default(),
        };
        assert!(!relevant(&ev(".config.toml.tmp-123")));
        assert!(!relevant(&ev("config.toml.swp")));
        assert!(!relevant(&ev("config.toml~")));
        assert!(relevant(&ev("config.toml")));
        assert_eq!(WatchMode::from_poll_ms(0), WatchMode::Native);
        assert_eq!(WatchMode::from_poll_ms(1), WatchMode::Poll(MIN_POLL));
        assert_eq!(
            WatchMode::from_poll_ms(2000),
            WatchMode::Poll(Duration::from_secs(2))
        );
    }
}