Skip to main content

rigtop_core/
config.rs

1//! User configuration (`config.toml`).
2//!
3//! The file lives at `<config dir>/rigtop/config.toml`
4//! (`~/.config/rigtop/config.toml` on Linux, `%APPDATA%\rigtop\config.toml`
5//! on Windows). A missing file means "all defaults".
6//!
7//! ```toml
8//! [sensors]
9//! # Names for sensor channels, keyed by the stable channel key shown in the UI.
10//! labels = { "nct6686:nct6683.2592/fan1" = "CPU fan", "nct6686:nct6683.2592/temp1" = "VRM" }
11//! # Channels to hide (e.g. unconnected thermistors reading -40 °C).
12//! hidden = ["nct6686:nct6683.2592/temp4"]
13//!
14//! [smart]
15//! # Directory with smartctl JSON files written by the root timer.
16//! dir = "/var/lib/rigtop/smart"
17//!
18//! [btrfs]
19//! # Directory with btrfs scrub status files copied by the root timer.
20//! scrub_dir = "/var/lib/rigtop/btrfs"
21//!
22//! [alerts]
23//! # When readings become alerts (0 turns one off).
24//! filesystem_warning_percent = 90
25//! filesystem_critical_percent = 97
26//! filesystem_full_warning_hours = 24  # full this soon at the last half hour's rate
27//! cpu_warning_celsius = 96    # hottest CPU reading
28//! gpu_warning_celsius = 85
29//! drive_warning_celsius = 70  # SMART or NVMe sensor
30//! memory_warning_percent = 90 # memory in use (without cache)
31//! gpu_memory_warning_percent = 0  # VRAM; off: frameworks reserve most of it
32//! memory_pressure_warning_percent = 10  # time tasks waited for memory (Linux)
33//! io_pressure_warning_percent = 30      # time all tasks waited for I/O (Linux)
34//! ignored_units = []          # failed systemd units not to warn about
35//!
36//! [notifications]
37//! # rigtop-gui: desktop notifications for new alerts ("critical", "warning" or "off").
38//! level = "critical"
39//!
40//! [updates]
41//! # Look for new releases on github.com (at startup and every interval:
42//! # "30m", "6h", "1d", "1h30m", ...; at least a minute).
43//! check = true
44//! interval = "1h"
45//! notify = true   # rigtop-gui: desktop notification for a new release
46//!
47//! [watch]
48//! # `rigtop --watch`: run a command when an alert appears or clears on any
49//! # host, with RIGTOP_HOST, RIGTOP_SEVERITY, RIGTOP_CHANGE, RIGTOP_ALERT and
50//! # RIGTOP_MESSAGE in its environment.
51//! command = 'curl -s -d "$RIGTOP_MESSAGE" https://ntfy.sh/my-topic'
52//! level = "critical"     # or "warning" ("off" runs nothing)
53//! cleared = true         # also when an alert goes away
54//! interval = "10s"       # time between samples
55//! offline_after = "3m"   # a host unreachable this long is a critical alert
56//! processes = ["train.py"]  # also tell when these exit, on any host
57//!
58//! [lhm]
59//! # Windows: LibreHardwareMonitor's web server ("" to disable).
60//! url = "http://127.0.0.1:8085/data.json"
61//!
62//! [tui]
63//! # Boxes of the host view not to draw (also toggled with `v`).
64//! hidden_panels = ["gpu"]
65//! show_widgets = true   # the widget column (`w`)
66//!
67//! [overview]
68//! # Sections of each host card, most important first.
69//! sections = ["cpu", "gpu", "memory", "processes", "network", "storage"]
70//! include_local = true
71//! processes = 10
72//! alerts_first = false  # true: hosts that need attention first
73//!
74//! [[hosts]]
75//! name = "zefat"
76//!
77//! [[hosts]]
78//! name = "nas"
79//! ssh = "admin@nas.local"
80//! command = "/usr/local/bin/rigtop --agent"
81//! sections = ["storage", "cpu", "network"]
82//! [hosts.alerts]       # this host's thresholds, over those of [alerts]
83//! filesystem_warning_percent = 95
84//!
85//! [[widgets]]
86//! name = "Clock"
87//! builtin = "clock"
88//!
89//! [[widgets]]
90//! name = "Rates"
91//! command = "~/bin/rates.sh"   # prints text or JSON rows, see `widget`
92//! interval_secs = 60
93//!
94//! ```
95//!
96//! Labels are applied by front-ends rather than by data sources, so that a
97//! client monitoring remote hosts uses its own local configuration.
98
99use std::collections::BTreeMap;
100use std::fs;
101use std::io;
102use std::path::{Path, PathBuf};
103use std::time::{Duration, Instant, SystemTime};
104
105use serde::{Deserialize, Serialize};
106
107use crate::snapshot::{Fan, Temperature};
108
109/// What a new configuration file starts with: every setting, commented out
110/// at its default, with short explanations.
111pub const CONFIG_TEMPLATE: &str = include_str!("config_template.toml");
112
113/// Default location of the SMART result files.
114pub const DEFAULT_SMART_DIR: &str = "/var/lib/rigtop/smart";
115/// Default location of the copied btrfs scrub status files.
116pub const DEFAULT_SCRUB_DIR: &str = "/var/lib/rigtop/btrfs";
117/// Default address of LibreHardwareMonitor's web server (Windows sensors).
118pub const DEFAULT_LHM_URL: &str = "http://127.0.0.1:8085/data.json";
119
120/// Errors while loading or saving the configuration.
121#[derive(Debug, thiserror::Error)]
122pub enum ConfigError {
123    /// The file could not be read or written.
124    #[error("cannot access {path}: {source}")]
125    Io {
126        /// File that failed.
127        path: PathBuf,
128        /// Underlying error.
129        source: io::Error,
130    },
131    /// The file is not valid TOML or has unexpected fields.
132    #[error("invalid config {path}: {source}")]
133    Parse {
134        /// File that failed.
135        path: PathBuf,
136        /// Underlying error.
137        source: toml::de::Error,
138    },
139    /// The configuration could not be serialized.
140    #[error("cannot serialize config: {0}")]
141    Serialize(#[from] toml::ser::Error),
142    /// A host's `alerts` table has a key `[alerts]` does not, or a value of
143    /// the wrong type.
144    #[error("invalid alerts of host {host} in {path}: {source}")]
145    HostAlerts {
146        /// File that failed.
147        path: PathBuf,
148        /// Name of the host.
149        host: String,
150        /// Underlying error (boxed: it would make every result large).
151        source: Box<toml::de::Error>,
152    },
153    /// The file is not valid TOML, so it cannot be edited in place.
154    #[error("cannot edit {path}: {source}")]
155    Edit {
156        /// File that failed.
157        path: PathBuf,
158        /// Underlying error.
159        source: toml_edit::TomlError,
160    },
161}
162
163/// Top-level configuration.
164#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
165#[serde(default, deny_unknown_fields)]
166pub struct Config {
167    /// Sensor naming and visibility.
168    pub sensors: SensorConfig,
169    /// SMART result files.
170    pub smart: SmartConfig,
171    /// btrfs scrub status files.
172    pub btrfs: BtrfsConfig,
173    /// LibreHardwareMonitor's web server, the source of temperatures, fans
174    /// and CPU power on Windows.
175    pub lhm: LhmConfig,
176    /// The multi-host overview.
177    pub overview: OverviewConfig,
178    /// The terminal UI.
179    pub tui: TuiConfig,
180    /// When a reading becomes an alert.
181    pub alerts: AlertsConfig,
182    /// Desktop notifications for new alerts (GUI).
183    pub notifications: NotificationsConfig,
184    /// Looking for new rigtop releases.
185    pub updates: UpdatesConfig,
186    /// Alerts sent by `rigtop --watch`.
187    pub watch: WatchConfig,
188    /// Remote hosts monitored over SSH (`[[hosts]]` tables).
189    pub hosts: Vec<HostConfig>,
190    /// Extra panels beside the monitor (`[[widgets]]` tables).
191    pub widgets: Vec<WidgetConfig>,
192}
193
194/// Widgets drawn by rigtop itself.
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(rename_all = "lowercase")]
197pub enum BuiltinWidget {
198    /// The date and a large clock.
199    Clock,
200}
201
202/// One widget: a built-in one, or a command whose output is shown (see
203/// [`crate::widget`] for the output format).
204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
205#[serde(default, deny_unknown_fields)]
206pub struct WidgetConfig {
207    /// Title of the widget.
208    pub name: String,
209    /// Shell command printing the content.
210    pub command: Option<String>,
211    /// Or a built-in widget.
212    pub builtin: Option<BuiltinWidget>,
213    /// Seconds between runs of the command.
214    pub interval_secs: u64,
215    /// Seconds after which a run is killed.
216    pub timeout_secs: u64,
217}
218
219impl Default for WidgetConfig {
220    fn default() -> Self {
221        Self {
222            name: String::new(),
223            command: None,
224            builtin: None,
225            interval_secs: 5,
226            timeout_secs: 10,
227        }
228    }
229}
230
231/// A block of information on a host card in the overview.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
233#[serde(rename_all = "lowercase")]
234pub enum OverviewSection {
235    Cpu,
236    Gpu,
237    Memory,
238    Processes,
239    Network,
240    Storage,
241}
242
243impl OverviewSection {
244    /// All sections in the default priority order.
245    pub const ALL: [OverviewSection; 6] = [
246        OverviewSection::Cpu,
247        OverviewSection::Gpu,
248        OverviewSection::Memory,
249        OverviewSection::Processes,
250        OverviewSection::Network,
251        OverviewSection::Storage,
252    ];
253
254    /// Name shown in menus.
255    pub fn label(self) -> &'static str {
256        match self {
257            OverviewSection::Cpu => "CPU",
258            OverviewSection::Gpu => "GPU",
259            OverviewSection::Memory => "Memory",
260            OverviewSection::Processes => "Processes",
261            OverviewSection::Network => "Network",
262            OverviewSection::Storage => "Storage",
263        }
264    }
265}
266
267/// Settings of the terminal UI.
268#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
269#[serde(default, deny_unknown_fields)]
270pub struct TuiConfig {
271    /// Boxes of the host view not to draw (`v` toggles them and saves the
272    /// choice here). The CPU box is always drawn.
273    pub hidden_panels: Vec<OverviewSection>,
274    /// Whether the widget column is shown (`w`, or `v` then `w`).
275    pub show_widgets: bool,
276}
277
278impl Default for TuiConfig {
279    fn default() -> Self {
280        Self {
281            hidden_panels: Vec::new(),
282            show_widgets: true,
283        }
284    }
285}
286
287/// Settings of the multi-host overview.
288#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
289#[serde(default, deny_unknown_fields)]
290pub struct OverviewConfig {
291    /// Sections shown on each host card, most important first. Sections are
292    /// dropped from the end when a card is too small; leaving one out of
293    /// the list hides it.
294    pub sections: Vec<OverviewSection>,
295    /// Whether this machine also gets a card (it always has its own tab).
296    pub include_local: bool,
297    /// Processes listed per card. Hosts not shown in detail only send this
298    /// many, to keep SSH traffic small.
299    pub processes: usize,
300    /// Put hosts that need attention first (unreachable or with critical
301    /// alerts, then warnings); the others keep their order. Off by default,
302    /// so that cards stay where they are.
303    pub alerts_first: bool,
304}
305
306impl Default for OverviewConfig {
307    fn default() -> Self {
308        Self {
309            sections: OverviewSection::ALL.to_vec(),
310            include_local: true,
311            processes: 10,
312            alerts_first: false,
313        }
314    }
315}
316
317/// A remote host to monitor.
318#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
319#[serde(deny_unknown_fields)]
320pub struct HostConfig {
321    /// Name shown in tabs and on the overview card.
322    pub name: String,
323    /// SSH destination (a `~/.ssh/config` host, `user@host`, ...);
324    /// defaults to `name`.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub ssh: Option<String>,
327    /// Command that starts the agent; defaults to `rigtop --agent`.
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub command: Option<String>,
330    /// Overview sections for this host, overriding `[overview] sections`
331    /// (e.g. storage first for a file server).
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub sections: Option<Vec<OverviewSection>>,
334    /// Alert thresholds of this host: the keys given replace those of
335    /// `[alerts]` (e.g. a higher CPU temperature for a laptop). Checked when
336    /// the file is loaded; see [`Config::alerts_for`].
337    #[serde(default, skip_serializing_if = "Option::is_none")]
338    pub alerts: Option<toml::Table>,
339}
340
341impl HostConfig {
342    /// A host given only by its SSH destination (e.g. on the command line).
343    pub fn from_destination(destination: &str) -> Self {
344        Self {
345            name: destination.to_owned(),
346            ssh: None,
347            command: None,
348            sections: None,
349            alerts: None,
350        }
351    }
352
353    /// The SSH destination.
354    pub fn destination(&self) -> &str {
355        self.ssh.as_deref().unwrap_or(&self.name)
356    }
357}
358
359/// Sensor naming and visibility.
360#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
361#[serde(default, deny_unknown_fields)]
362pub struct SensorConfig {
363    /// User-defined names keyed by channel key (`"<chip key>/fan1"`, `"<chip key>/temp3"`).
364    /// A `BTreeMap` keeps the saved file in a stable order.
365    pub labels: BTreeMap<String, String>,
366    /// Channel keys to hide.
367    pub hidden: Vec<String>,
368}
369
370/// Where to find SMART results.
371#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
372#[serde(default, deny_unknown_fields)]
373pub struct SmartConfig {
374    /// Directory containing one smartctl JSON file per device.
375    pub dir: PathBuf,
376}
377
378impl Default for SmartConfig {
379    fn default() -> Self {
380        Self {
381            dir: PathBuf::from(DEFAULT_SMART_DIR),
382        }
383    }
384}
385
386/// Which new alerts the GUI announces with a desktop notification.
387#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
388#[serde(rename_all = "lowercase")]
389pub enum NotifyLevel {
390    /// No notifications.
391    Off,
392    /// Warnings and critical alerts.
393    Warning,
394    /// Critical alerts only (data at risk).
395    #[default]
396    Critical,
397}
398
399/// Thresholds that turn readings into alerts (overview cards, status dots
400/// and notifications). 0 turns an alert off. Applied by the front-end, so
401/// remote hosts are judged by the viewer's settings.
402#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
403#[serde(default, deny_unknown_fields)]
404pub struct AlertsConfig {
405    /// Filesystem usage (%) for a warning.
406    pub filesystem_warning_percent: f64,
407    /// Filesystem usage (%) for a critical alert.
408    pub filesystem_critical_percent: f64,
409    /// A filesystem that will be full within this many hours, at the growth
410    /// of the last half hour, is a warning.
411    pub filesystem_full_warning_hours: f64,
412    /// Hottest CPU reading (°C) for a warning. Desktop Ryzen CPUs run up to
413    /// 95 °C under full load by design.
414    pub cpu_warning_celsius: f32,
415    /// GPU temperature (°C) for a warning.
416    pub gpu_warning_celsius: f32,
417    /// Drive temperature (°C, from SMART or the NVMe sensor) for a warning.
418    pub drive_warning_celsius: f32,
419    /// Memory in use (%, page cache not counted) for a warning.
420    pub memory_warning_percent: f64,
421    /// GPU memory in use (%) for a warning. Off by default: PyTorch, JAX
422    /// and TensorFlow reserve most of the VRAM up front, so a busy GPU
423    /// always looks full.
424    pub gpu_memory_warning_percent: f64,
425    /// Share of the last minute (%) in which some task waited for memory
426    /// (Linux pressure stall information) for a warning: reclaim or swap
427    /// is slowing work down.
428    pub memory_pressure_warning_percent: f64,
429    /// Share of the last minute (%) in which every runnable task waited for
430    /// I/O for a warning. Not "some" task: that is near 100% during any
431    /// large copy.
432    pub io_pressure_warning_percent: f64,
433    /// systemd units whose failure is not worth a warning (e.g. a
434    /// `systemd-networkd-wait-online.service` that fails on every boot).
435    pub ignored_units: Vec<String>,
436}
437
438impl Default for AlertsConfig {
439    fn default() -> Self {
440        Self {
441            filesystem_warning_percent: 90.0,
442            filesystem_critical_percent: 97.0,
443            filesystem_full_warning_hours: 24.0,
444            cpu_warning_celsius: 96.0,
445            gpu_warning_celsius: 85.0,
446            drive_warning_celsius: 70.0,
447            memory_warning_percent: 90.0,
448            gpu_memory_warning_percent: 0.0,
449            memory_pressure_warning_percent: 10.0,
450            io_pressure_warning_percent: 30.0,
451            ignored_units: Vec::new(),
452        }
453    }
454}
455
456/// Desktop notification settings.
457#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
458#[serde(default, deny_unknown_fields)]
459pub struct NotificationsConfig {
460    pub level: NotifyLevel,
461}
462
463/// Looking for new rigtop releases on GitHub.
464#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
465#[serde(default, deny_unknown_fields)]
466pub struct UpdatesConfig {
467    /// Look for new releases (contacts github.com); `false` never does.
468    pub check: bool,
469    /// Time between checks (also checked at startup), written like "1h",
470    /// "30m", "1d" or "1h30m".
471    #[serde(with = "duration_text")]
472    pub interval: Duration,
473    /// Announce a new release with a desktop notification (GUI), besides
474    /// the note in the title.
475    pub notify: bool,
476}
477
478impl Default for UpdatesConfig {
479    fn default() -> Self {
480        Self {
481            check: true,
482            interval: Duration::from_secs(3600),
483            notify: true,
484        }
485    }
486}
487
488impl UpdatesConfig {
489    /// Time between checks; at least a minute, whatever the file says.
490    pub fn check_interval(&self) -> Duration {
491        self.interval.max(Duration::from_secs(60))
492    }
493}
494
495/// `rigtop --watch`: watching every host without a screen and running a
496/// command when alerts appear or clear.
497#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
498#[serde(default, deny_unknown_fields)]
499pub struct WatchConfig {
500    /// Shell command run for each change ("" runs nothing; changes are
501    /// still printed and kept in the alert history).
502    pub command: String,
503    /// The least severe alerts the command runs for.
504    pub level: NotifyLevel,
505    /// Also run the command when an alert clears.
506    pub cleared: bool,
507    /// Time between samples of each host.
508    #[serde(with = "duration_text")]
509    pub interval: Duration,
510    /// A host that sends nothing this long becomes a critical alert.
511    #[serde(with = "duration_text")]
512    pub offline_after: Duration,
513    /// Time a run of the command may take before it is killed.
514    #[serde(with = "duration_text")]
515    pub timeout: Duration,
516    /// Processes to announce the exit of, on every host, by name or by a
517    /// file in their command line (`"train.py"`, `"rsync"`); see
518    /// [`crate::view::process_matches`].
519    pub processes: Vec<String>,
520}
521
522impl Default for WatchConfig {
523    fn default() -> Self {
524        Self {
525            command: String::new(),
526            level: NotifyLevel::Critical,
527            cleared: true,
528            interval: Duration::from_secs(10),
529            offline_after: Duration::from_secs(180),
530            timeout: Duration::from_secs(30),
531            processes: Vec::new(),
532        }
533    }
534}
535
536/// Durations written as text: a number and a unit (`s`, `m`, `h` or `d`),
537/// possibly several, as in "1h30m".
538mod duration_text {
539    use std::time::Duration;
540
541    use serde::de::Error;
542    use serde::{Deserialize, Deserializer, Serializer};
543
544    const UNITS: [(char, u64); 4] = [('d', 86_400), ('h', 3600), ('m', 60), ('s', 1)];
545
546    pub fn serialize<S: Serializer>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
547        serializer.serialize_str(&format(*duration))
548    }
549
550    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
551        let text = String::deserialize(deserializer)?;
552        parse(&text).ok_or_else(|| {
553            D::Error::custom(format!(
554                "invalid duration {text:?}: write a number and s, m, h or d, \
555                 e.g. \"30m\", \"6h\" or \"1h30m\""
556            ))
557        })
558    }
559
560    /// "1h30m" -> 90 minutes; `None` for anything else.
561    pub fn parse(text: &str) -> Option<Duration> {
562        let text: String = text.chars().filter(|c| !c.is_whitespace()).collect();
563        if text.is_empty() {
564            return None;
565        }
566        let mut total = 0u64;
567        let mut number = String::new();
568        for c in text.chars() {
569            if c.is_ascii_digit() {
570                number.push(c);
571                continue;
572            }
573            let (_, secs) = UNITS
574                .iter()
575                .find(|(unit, _)| *unit == c.to_ascii_lowercase())?;
576            let value: u64 = number.parse().ok()?;
577            total = total.checked_add(value.checked_mul(*secs)?)?;
578            number.clear();
579        }
580        // A number without a unit at the end is ambiguous.
581        number.is_empty().then(|| Duration::from_secs(total))
582    }
583
584    /// 90 minutes -> "1h30m"; whole seconds only.
585    pub fn format(duration: Duration) -> String {
586        let mut secs = duration.as_secs();
587        if secs == 0 {
588            return "0s".to_owned();
589        }
590        let mut text = String::new();
591        for (unit, size) in UNITS {
592            if secs >= size {
593                text.push_str(&format!("{}{unit}", secs / size));
594                secs %= size;
595            }
596        }
597        text
598    }
599}
600
601/// Where to read Windows sensors from.
602#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
603#[serde(default, deny_unknown_fields)]
604pub struct LhmConfig {
605    /// `data.json` of LibreHardwareMonitor's "Remote Web Server" (plain
606    /// HTTP without authentication); empty to disable.
607    pub url: String,
608}
609
610impl Default for LhmConfig {
611    fn default() -> Self {
612        Self {
613            url: DEFAULT_LHM_URL.to_owned(),
614        }
615    }
616}
617
618/// Where to find btrfs scrub results.
619#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
620#[serde(default, deny_unknown_fields)]
621pub struct BtrfsConfig {
622    /// Directory with world-readable copies of `scrub.status.<fsid>`.
623    pub scrub_dir: PathBuf,
624}
625
626impl Default for BtrfsConfig {
627    fn default() -> Self {
628        Self {
629            scrub_dir: PathBuf::from(DEFAULT_SCRUB_DIR),
630        }
631    }
632}
633
634/// Creates the configuration file at `path` from [`CONFIG_TEMPLATE`] if
635/// there is none yet (with its directory). Returns true when it did.
636pub fn create_if_missing(path: &Path) -> io::Result<bool> {
637    if path.exists() {
638        return Ok(false);
639    }
640    if let Some(dir) = path.parent() {
641        fs::create_dir_all(dir)?;
642    }
643    fs::write(path, CONFIG_TEMPLATE)?;
644    Ok(true)
645}
646
647impl Config {
648    /// Default path of the configuration file, if the platform has a config directory.
649    pub fn default_path() -> Option<PathBuf> {
650        dirs::config_dir().map(|dir| dir.join("rigtop").join("config.toml"))
651    }
652
653    /// Loads the configuration from `path`. A missing file yields the defaults.
654    pub fn load(path: &Path) -> Result<Self, ConfigError> {
655        let text = match fs::read_to_string(path) {
656            Ok(text) => text,
657            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
658            Err(source) => {
659                return Err(ConfigError::Io {
660                    path: path.to_owned(),
661                    source,
662                });
663            }
664        };
665        let config: Self = toml::from_str(&text).map_err(|source| ConfigError::Parse {
666            path: path.to_owned(),
667            source,
668        })?;
669        // A typo in a host's thresholds fails now, like one in [alerts].
670        for host in &config.hosts {
671            config
672                .alerts_for(host)
673                .map_err(|source| ConfigError::HostAlerts {
674                    path: path.to_owned(),
675                    host: host.name.clone(),
676                    source: Box::new(source),
677                })?;
678        }
679        Ok(config)
680    }
681
682    /// The alert thresholds of `host`: `[alerts]` with the keys of the
683    /// host's own `alerts` table in place of its own.
684    pub fn alerts_for(&self, host: &HostConfig) -> Result<AlertsConfig, toml::de::Error> {
685        let Some(overrides) = &host.alerts else {
686            return Ok(self.alerts.clone());
687        };
688        // Serializing plain numbers and strings cannot fail.
689        let mut merged = toml::Table::try_from(&self.alerts).unwrap_or_default();
690        merged.extend(overrides.clone());
691        merged.try_into()
692    }
693
694    /// Loads from [`Config::default_path`], or returns the defaults when the
695    /// platform has no config directory.
696    pub fn load_default() -> Result<Self, ConfigError> {
697        match Self::default_path() {
698            Some(path) => Self::load(&path),
699            None => Ok(Self::default()),
700        }
701    }
702
703    /// Writes the configuration to `path`, creating parent directories.
704    ///
705    /// The file is written to a temporary sibling and renamed into place, so
706    /// a crash never leaves a truncated config behind.
707    pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
708        let text = toml::to_string_pretty(self)?;
709        let io_err = |source| ConfigError::Io {
710            path: path.to_owned(),
711            source,
712        };
713        if let Some(parent) = path.parent() {
714            fs::create_dir_all(parent).map_err(io_err)?;
715        }
716        let tmp = path.with_extension("toml.tmp");
717        fs::write(&tmp, text).map_err(io_err)?;
718        fs::rename(&tmp, path).map_err(io_err)
719    }
720
721    /// Replaces the `[[hosts]]` of the configuration file at `path` with
722    /// `hosts`, keeping everything else in the file (other settings,
723    /// comments, formatting) untouched. Creates the file if needed.
724    ///
725    /// Used by the GUI's host editor. The edited file is checked to load as
726    /// a valid configuration before it replaces the old one.
727    pub fn save_hosts(path: &Path, hosts: &[HostConfig]) -> Result<(), ConfigError> {
728        edit_file(path, |document| {
729            if hosts.is_empty() {
730                document.remove("hosts");
731                return Ok(());
732            }
733            let mut tables = toml_edit::ArrayOfTables::new();
734            for host in hosts {
735                let mut table = toml_edit::Table::new();
736                table["name"] = toml_edit::value(host.name.as_str());
737                if let Some(ssh) = &host.ssh {
738                    table["ssh"] = toml_edit::value(ssh.as_str());
739                }
740                if let Some(command) = &host.command {
741                    table["command"] = toml_edit::value(command.as_str());
742                }
743                if let Some(sections) = &host.sections {
744                    let mut array = toml_edit::Array::new();
745                    for section in sections {
746                        // Serialized names match the serde representation.
747                        let name = toml::Value::try_from(section)?;
748                        if let Some(name) = name.as_str() {
749                            array.push(name);
750                        }
751                    }
752                    table["sections"] = toml_edit::value(array);
753                }
754                if let Some(alerts) = &host.alerts {
755                    // Written as [hosts.alerts] under the host's keys.
756                    let mut sub = toml_edit::Table::new();
757                    for (key, value) in alerts {
758                        if let Ok(value) = value.to_string().parse::<toml_edit::Value>() {
759                            sub[key.as_str()] = toml_edit::value(value);
760                        }
761                    }
762                    table["alerts"] = toml_edit::Item::Table(sub);
763                }
764                tables.push(table);
765            }
766            document["hosts"] = toml_edit::Item::ArrayOfTables(tables);
767            Ok(())
768        })
769    }
770
771    /// Replaces the sensor names and hidden sensors (`[sensors]`) of the
772    /// configuration file at `path`, keeping the rest of the file as it is,
773    /// like [`Config::save_hosts`]. Names stay an inline table if they were
774    /// one.
775    ///
776    /// Used by the GUI's sensor editor.
777    /// Writes `[tui]` (keys left at their defaults are removed), leaving
778    /// the rest of the file as it is.
779    pub fn save_tui(path: &Path, tui: &TuiConfig) -> Result<(), ConfigError> {
780        edit_file(path, |document| {
781            if !document.contains_key("tui") {
782                if *tui == TuiConfig::default() {
783                    return Ok(());
784                }
785                document["tui"] = toml_edit::table();
786            }
787            let Some(table) = document["tui"].as_table_like_mut() else {
788                // Not a table: loading would have failed already.
789                return Ok(());
790            };
791            if tui.hidden_panels.is_empty() {
792                table.remove("hidden_panels");
793            } else {
794                let names: toml_edit::Array = tui
795                    .hidden_panels
796                    .iter()
797                    .filter_map(|section| {
798                        serde_json::to_value(section)
799                            .ok()
800                            .and_then(|v| v.as_str().map(str::to_owned))
801                    })
802                    .collect();
803                table.insert("hidden_panels", toml_edit::value(names));
804            }
805            if tui.show_widgets {
806                table.remove("show_widgets");
807            } else {
808                table.insert("show_widgets", toml_edit::value(false));
809            }
810            Ok(())
811        })
812    }
813
814    pub fn save_sensors(path: &Path, sensors: &SensorConfig) -> Result<(), ConfigError> {
815        edit_file(path, |document| {
816            if !document.contains_key("sensors") {
817                if sensors.labels.is_empty() && sensors.hidden.is_empty() {
818                    return Ok(());
819                }
820                document["sensors"] = toml_edit::table();
821            }
822            let Some(table) = document["sensors"].as_table_like_mut() else {
823                // Not a table: loading would have failed already.
824                return Ok(());
825            };
826            if sensors.hidden.is_empty() {
827                table.remove("hidden");
828            } else {
829                let hidden: toml_edit::Array = sensors.hidden.iter().map(String::as_str).collect();
830                table.insert("hidden", toml_edit::value(hidden));
831            }
832            let inline = table.get("labels").is_some_and(|l| l.is_inline_table());
833            if sensors.labels.is_empty() {
834                table.remove("labels");
835            } else if inline {
836                let labels: toml_edit::InlineTable = sensors
837                    .labels
838                    .iter()
839                    .map(|(k, v)| (k.as_str(), toml_edit::Value::from(v.as_str())))
840                    .collect();
841                table.insert("labels", toml_edit::value(labels));
842            } else {
843                let mut labels = toml_edit::Table::new();
844                for (key, name) in &sensors.labels {
845                    labels[key.as_str()] = toml_edit::value(name.as_str());
846                }
847                table.insert("labels", toml_edit::Item::Table(labels));
848            }
849            if table.is_empty() {
850                document.remove("sensors");
851            }
852            Ok(())
853        })
854    }
855
856    /// Display name of a fan: the user-defined label, or the driver/generic label.
857    pub fn fan_label<'a>(&'a self, fan: &'a Fan) -> &'a str {
858        self.label_for(&fan.key).unwrap_or(&fan.label)
859    }
860
861    /// Display name of a temperature channel.
862    pub fn temperature_label<'a>(&'a self, temperature: &'a Temperature) -> &'a str {
863        self.label_for(&temperature.key)
864            .unwrap_or(&temperature.label)
865    }
866
867    /// User-defined label for a channel key, if any.
868    pub fn label_for(&self, key: &str) -> Option<&str> {
869        self.sensors.labels.get(key).map(String::as_str)
870    }
871
872    /// Sets (or, with an empty name, removes) the label of a channel.
873    pub fn set_label(&mut self, key: &str, name: &str) {
874        let name = name.trim();
875        if name.is_empty() {
876            self.sensors.labels.remove(key);
877        } else {
878            self.sensors.labels.insert(key.to_owned(), name.to_owned());
879        }
880    }
881
882    /// Whether the user chose to hide a channel.
883    pub fn is_hidden(&self, key: &str) -> bool {
884        self.sensors.hidden.iter().any(|k| k == key)
885    }
886}
887
888/// Reads the configuration file at `path` (or an empty one), lets `edit`
889/// change it with comments and formatting kept, and writes it back if it
890/// still loads as a configuration (through a temporary file, so a crash
891/// never leaves a truncated file behind).
892fn edit_file(
893    path: &Path,
894    edit: impl FnOnce(&mut toml_edit::DocumentMut) -> Result<(), ConfigError>,
895) -> Result<(), ConfigError> {
896    let io_err = |source| ConfigError::Io {
897        path: path.to_owned(),
898        source,
899    };
900    let text = match fs::read_to_string(path) {
901        Ok(text) => text,
902        Err(err) if err.kind() == io::ErrorKind::NotFound => String::new(),
903        Err(err) => return Err(io_err(err)),
904    };
905    let mut document: toml_edit::DocumentMut =
906        text.parse().map_err(|source| ConfigError::Edit {
907            path: path.to_owned(),
908            source,
909        })?;
910    edit(&mut document)?;
911    let edited = document.to_string();
912    // Never write a file that rigtop itself could not load afterwards.
913    toml::from_str::<Config>(&edited).map_err(|source| ConfigError::Parse {
914        path: path.to_owned(),
915        source,
916    })?;
917    if let Some(parent) = path.parent() {
918        fs::create_dir_all(parent).map_err(io_err)?;
919    }
920    let tmp = path.with_extension("toml.tmp");
921    fs::write(&tmp, edited).map_err(io_err)?;
922    fs::rename(&tmp, path).map_err(io_err)
923}
924
925/// How often [`ConfigWatcher::poll`] looks at the file.
926const WATCH_INTERVAL: Duration = Duration::from_secs(1);
927
928/// Notices when the configuration file changes, so a running rigtop can
929/// apply the edits without a restart.
930pub struct ConfigWatcher {
931    path: PathBuf,
932    /// Modification time and size when last seen (`None`: no file).
933    stamp: Option<(Option<SystemTime>, u64)>,
934    last_check: Instant,
935    interval: Duration,
936}
937
938impl ConfigWatcher {
939    /// Watches `path`, taking its current state as already loaded.
940    pub fn new(path: PathBuf) -> Self {
941        Self {
942            stamp: file_stamp(&path),
943            path,
944            last_check: Instant::now(),
945            interval: WATCH_INTERVAL,
946        }
947    }
948
949    /// The file being watched.
950    pub fn path(&self) -> &Path {
951        &self.path
952    }
953
954    /// Takes the file as it is now as already loaded, e.g. after rigtop
955    /// itself wrote to it.
956    pub fn mark_seen(&mut self) {
957        self.stamp = file_stamp(&self.path);
958    }
959
960    /// When the file changed since the previous call, its new contents (or
961    /// why they cannot be used, e.g. a file saved half-way). `None` when
962    /// unchanged, checked less than a second ago, or removed: a missing
963    /// file keeps the configuration in use rather than resetting it.
964    pub fn poll(&mut self) -> Option<Result<Config, ConfigError>> {
965        if self.last_check.elapsed() < self.interval {
966            return None;
967        }
968        self.last_check = Instant::now();
969        let stamp = file_stamp(&self.path);
970        if stamp == self.stamp {
971            return None;
972        }
973        self.stamp = stamp;
974        stamp?;
975        Some(Config::load(&self.path))
976    }
977}
978
979/// Modification time and size of `path`, if it exists.
980fn file_stamp(path: &Path) -> Option<(Option<SystemTime>, u64)> {
981    let metadata = fs::metadata(path).ok()?;
982    Some((metadata.modified().ok(), metadata.len()))
983}
984
985#[cfg(test)]
986mod tests {
987    use super::*;
988
989    #[test]
990    fn template_parses_with_every_setting_uncommented() {
991        // Settings are commented as "#key", explanations as "# text".
992        let settings: String = CONFIG_TEMPLATE
993            .lines()
994            .filter_map(|line| line.strip_prefix('#'))
995            .filter(|line| !line.starts_with(' ') && !line.is_empty())
996            .map(|line| format!("{line}\n"))
997            .collect();
998        let config: Config = toml::from_str(&settings).unwrap();
999        assert_eq!(config.hosts[0].name, "nas");
1000        // The defaults it shows are the real ones.
1001        assert_eq!(config.alerts, AlertsConfig::default());
1002        assert_eq!(config.watch, WatchConfig::default());
1003        assert_eq!(config.overview, OverviewConfig::default());
1004        // As written, everything is commented out.
1005        let empty: Config = toml::from_str(CONFIG_TEMPLATE).unwrap();
1006        assert_eq!(empty, Config::default());
1007
1008        let tmp = tempfile::tempdir().unwrap();
1009        let path = tmp.path().join("rigtop/config.toml");
1010        assert!(create_if_missing(&path).unwrap());
1011        assert!(!create_if_missing(&path).unwrap(), "left as it is");
1012        assert_eq!(Config::load(&path).unwrap(), Config::default());
1013    }
1014
1015    #[test]
1016    fn hidden_panels_are_saved_and_loaded() {
1017        let tmp = tempfile::tempdir().unwrap();
1018        let path = tmp.path().join("config.toml");
1019        fs::write(&path, "# mine\n[alerts]\ncpu_warning_celsius = 90\n").unwrap();
1020        let tui = TuiConfig {
1021            hidden_panels: vec![OverviewSection::Gpu, OverviewSection::Network],
1022            show_widgets: false,
1023        };
1024        Config::save_tui(&path, &tui).unwrap();
1025        let text = fs::read_to_string(&path).unwrap();
1026        assert!(text.starts_with("# mine"), "{text}");
1027        let config = Config::load(&path).unwrap();
1028        assert_eq!(
1029            config.tui.hidden_panels,
1030            vec![OverviewSection::Gpu, OverviewSection::Network]
1031        );
1032        assert!(!config.tui.show_widgets);
1033        assert_eq!(config.alerts.cpu_warning_celsius, 90.0);
1034        Config::save_tui(&path, &TuiConfig::default()).unwrap();
1035        let config = Config::load(&path).unwrap();
1036        assert_eq!(config.tui, TuiConfig::default());
1037        assert!(!fs::read_to_string(&path).unwrap().contains("show_widgets"));
1038    }
1039
1040    #[test]
1041    fn watch_settings() {
1042        let config: Config = toml::from_str(
1043            "[watch]\ncommand = \"notify-send x\"\nlevel = \"warning\"\ninterval = \"30s\"\n",
1044        )
1045        .unwrap();
1046        assert_eq!(config.watch.command, "notify-send x");
1047        assert_eq!(config.watch.level, NotifyLevel::Warning);
1048        assert!(config.watch.cleared);
1049        assert_eq!(config.watch.interval, Duration::from_secs(30));
1050        assert_eq!(config.watch.offline_after, Duration::from_secs(180));
1051        assert!(toml::from_str::<Config>("[watch]\ncomand = \"x\"\n").is_err());
1052    }
1053
1054    #[test]
1055    fn update_checks_can_be_tuned_or_turned_off() {
1056        let config: Config =
1057            toml::from_str("[updates]\ninterval = \"6h\"\nnotify = false\n").unwrap();
1058        assert!(config.updates.check);
1059        assert_eq!(
1060            config.updates.check_interval(),
1061            Duration::from_secs(6 * 3600)
1062        );
1063        assert!(!config.updates.notify);
1064        let config: Config =
1065            toml::from_str("[updates]\ncheck = false\ninterval = \"10s\"\n").unwrap();
1066        assert!(!config.updates.check);
1067        assert_eq!(
1068            config.updates.check_interval(),
1069            Duration::from_secs(60),
1070            "at least a minute"
1071        );
1072        let error = toml::from_str::<Config>("[updates]\ninterval = \"6 hours\"\n").unwrap_err();
1073        assert!(error.to_string().contains("invalid duration"), "{error}");
1074    }
1075
1076    #[test]
1077    fn durations_read_and_write_as_text() {
1078        let minutes = |m: u64| Some(Duration::from_secs(m * 60));
1079        assert_eq!(duration_text::parse("30m"), minutes(30));
1080        assert_eq!(duration_text::parse("1h30m"), minutes(90));
1081        assert_eq!(duration_text::parse("1h 30m"), minutes(90));
1082        assert_eq!(duration_text::parse("1d"), minutes(24 * 60));
1083        assert_eq!(duration_text::parse("2H"), minutes(120));
1084        for bad in ["", "6", "h", "1.5h", "1w", "-1h", "6 hours"] {
1085            assert_eq!(duration_text::parse(bad), None, "{bad:?}");
1086        }
1087        assert_eq!(duration_text::format(Duration::from_secs(5400)), "1h30m");
1088        assert_eq!(duration_text::format(Duration::from_secs(86_400)), "1d");
1089        // The defaults survive saving and loading.
1090        let text = toml::to_string(&Config::default()).unwrap();
1091        assert!(text.contains("interval = \"1h\""), "{text}");
1092        assert_eq!(toml::from_str::<Config>(&text).unwrap(), Config::default());
1093    }
1094
1095    #[test]
1096    fn watcher_reports_edits_once() {
1097        let tmp = tempfile::tempdir().unwrap();
1098        let path = tmp.path().join("config.toml");
1099        fs::write(&path, "[alerts]\ncpu_warning_celsius = 90\n").unwrap();
1100        let mut watcher = ConfigWatcher::new(path.clone());
1101        watcher.interval = Duration::ZERO;
1102        assert!(
1103            watcher.poll().is_none(),
1104            "the initial file counts as loaded"
1105        );
1106
1107        // A different size, so the change shows even where file times are coarse.
1108        fs::write(&path, "[alerts]\ncpu_warning_celsius = 100\n").unwrap();
1109        let config = watcher.poll().unwrap().unwrap();
1110        assert_eq!(config.alerts.cpu_warning_celsius, 100.0);
1111        assert!(watcher.poll().is_none(), "reported once");
1112
1113        fs::write(&path, "[alerts\n").unwrap();
1114        assert!(
1115            watcher.poll().unwrap().is_err(),
1116            "a broken file is an error"
1117        );
1118        fs::remove_file(&path).unwrap();
1119        assert!(
1120            watcher.poll().is_none(),
1121            "removing the file changes nothing"
1122        );
1123    }
1124
1125    #[test]
1126    fn missing_file_gives_defaults() {
1127        let tmp = tempfile::tempdir().unwrap();
1128        let config = Config::load(&tmp.path().join("none.toml")).unwrap();
1129        assert_eq!(config, Config::default());
1130        assert_eq!(config.smart.dir, PathBuf::from(DEFAULT_SMART_DIR));
1131    }
1132
1133    #[test]
1134    fn parses_labels_hidden_and_smart_dir() {
1135        let tmp = tempfile::tempdir().unwrap();
1136        let path = tmp.path().join("config.toml");
1137        fs::write(
1138            &path,
1139            r#"
1140[sensors]
1141labels = { "nct6686:nct6683.2592/fan1" = "CPU fan" }
1142hidden = ["nct6686:nct6683.2592/temp4"]
1143
1144[smart]
1145dir = "/tmp/smart"
1146
1147[lhm]
1148url = ""
1149
1150[notifications]
1151level = "warning"
1152
1153[alerts]
1154drive_warning_celsius = 65
1155cpu_warning_celsius = 0
1156gpu_memory_warning_percent = 98
1157"#,
1158        )
1159        .unwrap();
1160        let config = Config::load(&path).unwrap();
1161        let fan = Fan {
1162            key: "nct6686:nct6683.2592/fan1".to_owned(),
1163            label: "fan1".to_owned(),
1164            rpm: 900,
1165        };
1166        let other = Fan {
1167            key: "nct6686:nct6683.2592/fan2".to_owned(),
1168            label: "fan2".to_owned(),
1169            rpm: 0,
1170        };
1171        assert_eq!(config.fan_label(&fan), "CPU fan");
1172        // Unnamed channels fall back to the generic label.
1173        assert_eq!(config.fan_label(&other), "fan2");
1174        assert!(config.is_hidden("nct6686:nct6683.2592/temp4"));
1175        assert_eq!(config.smart.dir, PathBuf::from("/tmp/smart"));
1176        assert_eq!(config.lhm.url, "");
1177        assert_eq!(config.notifications.level, NotifyLevel::Warning);
1178        assert_eq!(Config::default().notifications.level, NotifyLevel::Critical);
1179        assert_eq!(Config::default().lhm.url, DEFAULT_LHM_URL);
1180        assert_eq!(config.alerts.drive_warning_celsius, 65.0);
1181        assert_eq!(config.alerts.cpu_warning_celsius, 0.0);
1182        // Unset thresholds keep their defaults.
1183        assert_eq!(config.alerts.gpu_warning_celsius, 85.0);
1184        assert_eq!(config.alerts.memory_warning_percent, 90.0);
1185        assert_eq!(config.alerts.gpu_memory_warning_percent, 98.0);
1186    }
1187
1188    #[test]
1189    fn parses_hosts_and_overview() {
1190        let config: Config = toml::from_str(
1191            r#"
1192[overview]
1193sections = ["storage", "cpu"]
1194include_local = false
1195
1196[[hosts]]
1197name = "zefat"
1198
1199[[hosts]]
1200name = "nas"
1201ssh = "admin@nas.local"
1202sections = ["storage"]
1203
1204[[widgets]]
1205name = "Clock"
1206builtin = "clock"
1207
1208[[widgets]]
1209name = "Rates"
1210command = "rates.sh"
1211interval_secs = 60
1212"#,
1213        )
1214        .unwrap();
1215        assert_eq!(
1216            config.overview.sections,
1217            vec![OverviewSection::Storage, OverviewSection::Cpu]
1218        );
1219        assert!(!config.overview.include_local);
1220        assert_eq!(config.overview.processes, 10, "default kept");
1221        assert_eq!(config.hosts.len(), 2);
1222        assert_eq!(config.hosts[0].destination(), "zefat");
1223        assert_eq!(config.widgets[0].builtin, Some(BuiltinWidget::Clock));
1224        assert_eq!(config.widgets[1].command.as_deref(), Some("rates.sh"));
1225        assert_eq!(config.widgets[1].interval_secs, 60);
1226        assert_eq!(config.widgets[1].timeout_secs, 10, "default kept");
1227        assert_eq!(config.hosts[1].destination(), "admin@nas.local");
1228        assert_eq!(
1229            config.hosts[1].sections,
1230            Some(vec![OverviewSection::Storage])
1231        );
1232        // Defaults: every section in priority order, local included.
1233        let defaults = Config::default();
1234        assert_eq!(defaults.overview.sections, OverviewSection::ALL.to_vec());
1235        assert!(defaults.overview.include_local);
1236    }
1237
1238    #[test]
1239    fn save_hosts_replaces_only_the_hosts() {
1240        let tmp = tempfile::tempdir().unwrap();
1241        let path = tmp.path().join("config.toml");
1242        fs::write(
1243            &path,
1244            "# my settings\n[sensors]\nlabels = { \"a/fan1\" = \"CPU fan\" } # keep me\n\n[[hosts]]\nname = \"old\"\n",
1245        )
1246        .unwrap();
1247        let hosts = vec![
1248            HostConfig::from_destination("zefat"),
1249            HostConfig {
1250                name: "nas".to_owned(),
1251                ssh: Some("admin@nas.local".to_owned()),
1252                command: Some("/opt/rigtop --agent".to_owned()),
1253                sections: Some(vec![OverviewSection::Storage, OverviewSection::Cpu]),
1254                alerts: Some(
1255                    toml::from_str("cpu_warning_celsius = 90.0\nignored_units = [\"a.service\"]")
1256                        .unwrap(),
1257                ),
1258            },
1259        ];
1260        Config::save_hosts(&path, &hosts).unwrap();
1261
1262        let text = fs::read_to_string(&path).unwrap();
1263        assert!(
1264            text.contains("# my settings") && text.contains("# keep me"),
1265            "{text}"
1266        );
1267        assert!(!text.contains("\"old\""), "{text}");
1268        let config = Config::load(&path).unwrap();
1269        assert_eq!(config.hosts, hosts);
1270        assert_eq!(config.label_for("a/fan1"), Some("CPU fan"));
1271
1272        // Removing every host drops the [[hosts]] tables.
1273        Config::save_hosts(&path, &[]).unwrap();
1274        assert!(Config::load(&path).unwrap().hosts.is_empty());
1275        assert!(fs::read_to_string(&path).unwrap().contains("# keep me"));
1276    }
1277
1278    #[test]
1279    fn host_alerts_replace_the_keys_they_give() {
1280        let tmp = tempfile::tempdir().unwrap();
1281        let path = tmp.path().join("config.toml");
1282        fs::write(
1283            &path,
1284            "[alerts]\nmemory_warning_percent = 80\n\n\
1285             [[hosts]]\nname = \"laptop\"\n[hosts.alerts]\ncpu_warning_celsius = 100\n\n\
1286             [[hosts]]\nname = \"nas\"\n",
1287        )
1288        .unwrap();
1289        let config = Config::load(&path).unwrap();
1290        let laptop = config.alerts_for(&config.hosts[0]).unwrap();
1291        assert_eq!(laptop.cpu_warning_celsius, 100.0);
1292        // The others come from [alerts], set or default.
1293        assert_eq!(laptop.memory_warning_percent, 80.0);
1294        assert_eq!(laptop.gpu_warning_celsius, 85.0);
1295        assert_eq!(config.alerts_for(&config.hosts[1]).unwrap(), config.alerts);
1296
1297        // A typo fails the load, naming the host.
1298        fs::write(
1299            &path,
1300            "[[hosts]]\nname = \"laptop\"\n[hosts.alerts]\ncpu_warning_celsus = 100\n",
1301        )
1302        .unwrap();
1303        let err = Config::load(&path).unwrap_err().to_string();
1304        assert!(
1305            err.contains("laptop") && err.contains("cpu_warning_celsus"),
1306            "{err}"
1307        );
1308    }
1309
1310    #[test]
1311    fn save_sensors_replaces_only_names_and_hidden_sensors() {
1312        let tmp = tempfile::tempdir().unwrap();
1313        let path = tmp.path().join("config.toml");
1314        fs::write(
1315            &path,
1316            "# my settings\n[sensors]\nlabels = { \"a/fan1\" = \"CPU fan\" } # inline\n\n[[hosts]]\nname = \"zefat\"\n",
1317        )
1318        .unwrap();
1319        let mut sensors = SensorConfig::default();
1320        sensors
1321            .labels
1322            .insert("a/fan1".to_owned(), "CPU fan".to_owned());
1323        sensors
1324            .labels
1325            .insert("b:c.1/temp2".to_owned(), "VRM".to_owned());
1326        sensors.hidden.push("b:c.1/temp4".to_owned());
1327        Config::save_sensors(&path, &sensors).unwrap();
1328
1329        let text = fs::read_to_string(&path).unwrap();
1330        assert!(text.contains("# my settings"), "{text}");
1331        // Inline names stay inline.
1332        assert!(text.contains("labels = {"), "{text}");
1333        let config = Config::load(&path).unwrap();
1334        assert_eq!(config.sensors, sensors);
1335        assert_eq!(config.hosts[0].name, "zefat");
1336
1337        // Nothing left: the [sensors] table goes away.
1338        Config::save_sensors(&path, &SensorConfig::default()).unwrap();
1339        let text = fs::read_to_string(&path).unwrap();
1340        assert!(!text.contains("[sensors]"), "{text}");
1341        assert_eq!(Config::load(&path).unwrap().hosts.len(), 1);
1342
1343        // A new file gets a [sensors.labels] table.
1344        let fresh = tmp.path().join("new.toml");
1345        Config::save_sensors(&fresh, &sensors).unwrap();
1346        let text = fs::read_to_string(&fresh).unwrap();
1347        assert!(text.contains("[sensors.labels]"), "{text}");
1348        assert_eq!(Config::load(&fresh).unwrap().sensors, sensors);
1349    }
1350
1351    #[test]
1352    fn save_hosts_creates_a_missing_file() {
1353        let tmp = tempfile::tempdir().unwrap();
1354        let path = tmp.path().join("new/rigtop/config.toml");
1355        Config::save_hosts(&path, &[HostConfig::from_destination("zefat")]).unwrap();
1356        assert_eq!(Config::load(&path).unwrap().hosts[0].name, "zefat");
1357    }
1358
1359    #[test]
1360    fn save_hosts_refuses_to_touch_a_broken_file() {
1361        let tmp = tempfile::tempdir().unwrap();
1362        let path = tmp.path().join("config.toml");
1363        fs::write(&path, "[sensors\n").unwrap();
1364        let err = Config::save_hosts(&path, &[]).unwrap_err();
1365        assert!(matches!(err, ConfigError::Edit { .. }), "{err}");
1366        assert_eq!(fs::read_to_string(&path).unwrap(), "[sensors\n");
1367    }
1368
1369    #[test]
1370    fn unknown_fields_are_rejected() {
1371        let tmp = tempfile::tempdir().unwrap();
1372        let path = tmp.path().join("config.toml");
1373        // A typo such as "label" instead of "labels" must not be silently ignored.
1374        fs::write(&path, "[sensors]\nlabel = {}\n").unwrap();
1375        assert!(matches!(
1376            Config::load(&path),
1377            Err(ConfigError::Parse { .. })
1378        ));
1379    }
1380
1381    #[test]
1382    fn save_and_reload_round_trip() {
1383        let tmp = tempfile::tempdir().unwrap();
1384        let path = tmp.path().join("nested/rigtop/config.toml");
1385        let mut config = Config::default();
1386        config.set_label("k10temp:0000:00:18.3/temp3", " CCD1 ");
1387        config.set_label("nct6686:nct6683.2592/fan1", "Rear fan");
1388        config.set_label("nct6686:nct6683.2592/fan1", "");
1389        config.save(&path).unwrap();
1390
1391        let back = Config::load(&path).unwrap();
1392        assert_eq!(back.label_for("k10temp:0000:00:18.3/temp3"), Some("CCD1"));
1393        // An empty name removes the label.
1394        assert_eq!(back.label_for("nct6686:nct6683.2592/fan1"), None);
1395        assert!(!path.with_extension("toml.tmp").exists());
1396    }
1397}