zenops 0.18.0

Declarative system configuration management for shell config and dotfiles.
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
//! Host operating-system facts and condition patterns.
//!
//! [`Os`] is the concrete fact about the host, returned by [`Os::current`].
//! Detection is strict: a platform/distro/version that isn't in the
//! supported matrix produces [`Error::UnsupportedPlatform`] or
//! [`Error::UnsupportedHost`] instead of a partially populated value.
//! Adding support means adding a variant **and** the integration-test row
//! that covers it — never a silent fallback.
//!
//! [`OsPattern`] is the matcher used by `Condition::Os { os = "..." }` in
//! TOML. It mirrors [`Os`] but adds explicit wildcard variants — e.g.
//! [`OsPattern::Linux`] matches any supported Linux distro/version. Match
//! direction is one-way: a pattern is asked [`OsPattern::matches`] against
//! a concrete [`Os`].
//!
//! TOML surface for patterns is a single string keyed off the variant:
//!
//! ```toml
//! os = "linux"
//! os = "macos"
//! os = "fedora"
//! os = "fedora-42"
//! ```

use std::path::Path;

use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use smol_str::SmolStr;

// ---------- Concrete host fact ----------

/// The host operating system as a fully concrete fact.
///
/// Construct via [`Os::current`]; never assemble by hand outside detection
/// — every variant corresponds to a row in the supported-host matrix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
    /// A supported Linux host. The inner [`Linux`] pins the distro and
    /// version exactly.
    Linux(Linux),
    /// A supported macOS host. Version is intentionally not modeled yet —
    /// add a payload when a real use case arrives.
    Macos,
}

/// Linux host facts. Currently just the distro; widen when other axes
/// (kernel, libc) become load-bearing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Linux {
    /// The detected Linux distribution.
    pub distro: Distro,
}

/// Supported Linux distributions. Commented variants are anchor points
/// for the next distro added — uncomment along with detection + tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Distro {
    /// Fedora — see [`Fedora`] for the version payload.
    Fedora(Fedora),
    /// Ubuntu — see [`Ubuntu`] for the version payload.
    Ubuntu(Ubuntu),
    /// Arch Linux — rolling release, no version payload.
    Arch,
    // Debian(Debian),   // not yet in the supported matrix
}

/// Fedora host facts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Fedora {
    /// The detected Fedora release.
    pub version: FedoraVersion,
}

/// Supported Fedora releases. New releases are added as new variants —
/// the exhaustive match in [`DistroPattern::matches`] then forces every
/// caller to be reviewed against the new row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FedoraVersion {
    /// Fedora 42 — includes dnf5 and the new command syntax.
    F42,
    // F43, ...
}

/// Ubuntu host facts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ubuntu {
    /// The detected Ubuntu release.
    pub version: UbuntuVersion,
}

/// Supported Ubuntu releases. Each is a deliberate code change paired
/// with an integration-test row — adding `U2410` etc. requires updating
/// every exhaustive match plus the matrix harness.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UbuntuVersion {
    /// Ubuntu 24.04 LTS (Noble Numbat) — apt + rustup in default repos.
    U2404,
    // U2410, U2604, ...
}

impl Os {
    /// Detect the current host. Errors with [`Error::UnsupportedPlatform`]
    /// for a platform we don't model (Windows, BSDs, …) or
    /// [`Error::UnsupportedHost`] for a Linux distro/version we haven't
    /// added to the matrix. No silent fallback — adding support is a
    /// deliberate code change.
    pub fn current() -> Result<Self, Error> {
        match std::env::consts::OS {
            "macos" => Ok(Os::Macos),
            "linux" => detect_linux(),
            other => Err(Error::UnsupportedPlatform(other)),
        }
    }
}

impl std::fmt::Display for Os {
    /// Human-readable label suitable for `zenops doctor` and the `${os}`
    /// template input. Macos renders as `"macos"`; Linux distros render
    /// as `"<distro> <version>"` (e.g. `"fedora 42"`, `"ubuntu 24.04"`)
    /// or just `"<distro>"` for rolling releases (e.g. `"arch"`),
    /// dropping the implicit `linux` prefix that adds no information.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Os::Macos => f.write_str("macos"),
            Os::Linux(linux) => match linux.distro {
                Distro::Fedora(Fedora {
                    version: FedoraVersion::F42,
                }) => f.write_str("fedora 42"),
                Distro::Ubuntu(Ubuntu {
                    version: UbuntuVersion::U2404,
                }) => f.write_str("ubuntu 24.04"),
                Distro::Arch => f.write_str("arch"),
            },
        }
    }
}

const OS_RELEASE_PATH: &str = "/etc/os-release";

fn detect_linux() -> Result<Os, Error> {
    let body = std::fs::read_to_string(Path::new(OS_RELEASE_PATH)).map_err(Error::OsReleaseRead)?;
    let (id, version_id) = parse_os_release(&body)?;
    let distro = match (id.as_str(), version_id.as_deref()) {
        ("fedora", Some("42")) => Distro::Fedora(Fedora {
            version: FedoraVersion::F42,
        }),
        ("ubuntu", Some("24.04")) => Distro::Ubuntu(Ubuntu {
            version: UbuntuVersion::U2404,
        }),
        // Arch is rolling — no VERSION_ID in /etc/os-release. Match on
        // ID alone and ignore any VERSION_ID a non-stock host might set.
        ("arch", _) => Distro::Arch,
        _ => {
            return Err(Error::UnsupportedHost {
                id,
                version_id: version_id.unwrap_or_default(),
            });
        }
    };
    Ok(Os::Linux(Linux { distro }))
}

/// Parse `/etc/os-release` for `ID` and `VERSION_ID`. Values may be
/// double-quoted per the spec; surrounding quotes are stripped. Other
/// fields are ignored. `ID` is required; `VERSION_ID` is optional
/// (rolling distros like Arch don't set it).
fn parse_os_release(body: &str) -> Result<(String, Option<String>), Error> {
    let mut id: Option<String> = None;
    let mut version_id: Option<String> = None;
    for line in body.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let value = value.trim().trim_matches('"').to_string();
        match key.trim() {
            "ID" => id = Some(value),
            "VERSION_ID" => version_id = Some(value),
            _ => {}
        }
    }
    let id = id
        .filter(|s| !s.is_empty())
        .ok_or(Error::OsReleaseMissingField("ID"))?;
    // VERSION_ID present-but-empty is treated as absent; rolling distros
    // (Arch) omit the field entirely, which is also absent.
    let version_id = version_id.filter(|s| !s.is_empty());
    Ok((id, version_id))
}

// ---------- Pattern type for conditions ----------

/// A condition-side pattern matched against a host [`Os`]. Mirrors `Os`
/// but adds explicit wildcard variants — e.g. [`OsPattern::Linux`] matches
/// any supported Linux distro/version.
///
/// Deserialized from a TOML string; see the module docs for accepted
/// spellings. The deserializer rejects anything outside the closed set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OsPattern {
    /// Matches any supported Linux host.
    Linux,
    /// Narrows to a specific distro (with optional version).
    LinuxDistro(DistroPattern),
    /// Matches any supported macOS host.
    Macos,
}

/// Pattern counterpart of [`Distro`]. Each distro gets a "match any
/// version" variant and a "match this version" variant; rolling distros
/// (none yet) would have only the bare variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DistroPattern {
    /// Any supported Fedora release.
    Fedora,
    /// A specific Fedora release.
    FedoraVersion(FedoraVersion),
    /// Any supported Ubuntu release.
    Ubuntu,
    /// A specific Ubuntu release.
    UbuntuVersion(UbuntuVersion),
    /// Arch Linux — rolling, no version variant.
    Arch,
}

impl OsPattern {
    /// Does this pattern accept the given host?
    pub fn matches(&self, host: &Os) -> bool {
        match (self, host) {
            (OsPattern::Linux, Os::Linux(_)) => true,
            (OsPattern::Macos, Os::Macos) => true,
            (OsPattern::LinuxDistro(dp), Os::Linux(l)) => dp.matches(&l.distro),
            (OsPattern::Linux, Os::Macos)
            | (OsPattern::Macos, Os::Linux(_))
            | (OsPattern::LinuxDistro(_), Os::Macos) => false,
        }
    }
}

impl DistroPattern {
    /// Does this pattern accept the given distro?
    pub fn matches(&self, host: &Distro) -> bool {
        match (self, host) {
            (DistroPattern::Fedora, Distro::Fedora(_)) => true,
            (DistroPattern::FedoraVersion(want), Distro::Fedora(f)) => *want == f.version,
            (DistroPattern::Ubuntu, Distro::Ubuntu(_)) => true,
            (DistroPattern::UbuntuVersion(want), Distro::Ubuntu(u)) => *want == u.version,
            (DistroPattern::Arch, Distro::Arch) => true,
            (DistroPattern::Fedora, Distro::Ubuntu(_) | Distro::Arch)
            | (DistroPattern::FedoraVersion(_), Distro::Ubuntu(_) | Distro::Arch)
            | (DistroPattern::Ubuntu, Distro::Fedora(_) | Distro::Arch)
            | (DistroPattern::UbuntuVersion(_), Distro::Fedora(_) | Distro::Arch)
            | (DistroPattern::Arch, Distro::Fedora(_) | Distro::Ubuntu(_)) => false,
        }
    }
}

// ---------- TOML / JSON serde for OsPattern ----------

const SUPPORTED_TOKENS: &[&str] = &[
    "linux",
    "macos",
    "fedora",
    "fedora-42",
    "ubuntu",
    "ubuntu-24.04",
    "arch",
];

impl OsPattern {
    fn from_token(s: &str) -> Result<Self, String> {
        match s {
            "linux" => Ok(OsPattern::Linux),
            "macos" => Ok(OsPattern::Macos),
            "fedora" => Ok(OsPattern::LinuxDistro(DistroPattern::Fedora)),
            "fedora-42" => Ok(OsPattern::LinuxDistro(DistroPattern::FedoraVersion(
                FedoraVersion::F42,
            ))),
            "ubuntu" => Ok(OsPattern::LinuxDistro(DistroPattern::Ubuntu)),
            "ubuntu-24.04" => Ok(OsPattern::LinuxDistro(DistroPattern::UbuntuVersion(
                UbuntuVersion::U2404,
            ))),
            "arch" => Ok(OsPattern::LinuxDistro(DistroPattern::Arch)),
            other => Err(format!(
                "unknown os value '{other}'; supported: {}",
                SUPPORTED_TOKENS
                    .iter()
                    .map(|t| format!("\"{t}\""))
                    .collect::<Vec<_>>()
                    .join(", ")
            )),
        }
    }

    fn to_token(self) -> &'static str {
        match self {
            OsPattern::Linux => "linux",
            OsPattern::Macos => "macos",
            OsPattern::LinuxDistro(DistroPattern::Fedora) => "fedora",
            OsPattern::LinuxDistro(DistroPattern::FedoraVersion(FedoraVersion::F42)) => "fedora-42",
            OsPattern::LinuxDistro(DistroPattern::Ubuntu) => "ubuntu",
            OsPattern::LinuxDistro(DistroPattern::UbuntuVersion(UbuntuVersion::U2404)) => {
                "ubuntu-24.04"
            }
            OsPattern::LinuxDistro(DistroPattern::Arch) => "arch",
        }
    }
}

impl<'de> Deserialize<'de> for OsPattern {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s: SmolStr = SmolStr::deserialize(d)?;
        OsPattern::from_token(s.as_str()).map_err(de::Error::custom)
    }
}

impl Serialize for OsPattern {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.to_token())
    }
}

impl schemars::JsonSchema for OsPattern {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "OsPattern".into()
    }

    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "enum": SUPPORTED_TOKENS,
            "description": "Host pattern. 'linux' / 'macos' match any supported version; 'fedora' matches any supported Fedora release; '<distro>-<version>' (e.g. 'fedora-42') pins an exact release.",
        })
    }
}

// ---------- Errors ----------

/// Failures from host detection. Every variant means "we won't proceed" —
/// no caller is expected to recover and run with partial information.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// `std::env::consts::OS` was something other than `linux` / `macos`.
    #[error("Unsupported platform: {0}")]
    UnsupportedPlatform(&'static str),
    /// `/etc/os-release` parsed cleanly, but the `(ID, VERSION_ID)` pair
    /// isn't in the supported matrix.
    #[error("Unsupported host: ID={id} VERSION_ID={version_id}")]
    UnsupportedHost {
        /// The `ID=` field from `/etc/os-release`.
        id: String,
        /// The `VERSION_ID=` field from `/etc/os-release`.
        version_id: String,
    },
    /// Reading `/etc/os-release` itself failed.
    #[error("Failed to read /etc/os-release: {0}")]
    OsReleaseRead(std::io::Error),
    /// `/etc/os-release` lacked a required field. `ID` is always
    /// required; `VERSION_ID` is required by detect_linux only for
    /// versioned distros (Fedora, Ubuntu), and is reported as a
    /// non-match via [`Self::UnsupportedHost`] rather than this variant.
    #[error("/etc/os-release is missing required field: {0}")]
    OsReleaseMissingField(&'static str),
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::UnsupportedPlatform(a), Self::UnsupportedPlatform(b)) => a == b,
            (
                Self::UnsupportedHost {
                    id: a,
                    version_id: b,
                },
                Self::UnsupportedHost {
                    id: c,
                    version_id: d,
                },
            ) => a == c && b == d,
            (Self::OsReleaseRead(a), Self::OsReleaseRead(b)) => a.kind() == b.kind(),
            (Self::OsReleaseMissingField(a), Self::OsReleaseMissingField(b)) => a == b,
            _ => false,
        }
    }
}

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

    fn fedora42() -> Os {
        Os::Linux(Linux {
            distro: Distro::Fedora(Fedora {
                version: FedoraVersion::F42,
            }),
        })
    }

    fn arch_host() -> Os {
        Os::Linux(Linux {
            distro: Distro::Arch,
        })
    }

    #[test]
    fn parse_os_release_real_fedora_sample() {
        let body = r#"NAME="Fedora Linux"
VERSION="42 (Cloud Edition)"
RELEASE_TYPE=stable
ID=fedora
VERSION_ID=42
VERSION_CODENAME=""
PLATFORM_ID="platform:f42"
PRETTY_NAME="Fedora Linux 42 (Cloud Edition)"
"#;
        let (id, version_id) = parse_os_release(body).unwrap();
        assert_eq!(id, "fedora");
        assert_eq!(version_id.as_deref(), Some("42"));
    }

    #[test]
    fn parse_os_release_strips_double_quotes() {
        let body = "ID=\"fedora\"\nVERSION_ID=\"42\"\n";
        let (id, version_id) = parse_os_release(body).unwrap();
        assert_eq!(id, "fedora");
        assert_eq!(version_id.as_deref(), Some("42"));
    }

    #[test]
    fn parse_os_release_missing_id_errors() {
        assert_eq!(
            parse_os_release("VERSION_ID=42\n").unwrap_err(),
            Error::OsReleaseMissingField("ID"),
        );
    }

    #[test]
    fn parse_os_release_missing_version_id_returns_none() {
        // Rolling distros (Arch) don't set VERSION_ID. The parser
        // returns None for it; detect_linux decides whether that's a
        // recognized rolling distro or an unsupported host.
        let (id, version_id) = parse_os_release("ID=arch\nBUILD_ID=rolling\n").unwrap();
        assert_eq!(id, "arch");
        assert_eq!(version_id, None);
    }

    #[test]
    fn parse_os_release_empty_version_id_treated_as_none() {
        let (id, version_id) = parse_os_release("ID=foo\nVERSION_ID=\"\"\n").unwrap();
        assert_eq!(id, "foo");
        assert_eq!(version_id, None);
    }

    #[test]
    fn parse_os_release_empty_id_treated_as_missing() {
        // Some hosts emit `ID=""`; treat that as missing rather than a
        // valid empty distro name.
        assert_eq!(
            parse_os_release("ID=\"\"\nVERSION_ID=42\n").unwrap_err(),
            Error::OsReleaseMissingField("ID"),
        );
    }

    #[test]
    fn parse_os_release_arch_sample() {
        let body = r#"NAME="Arch Linux"
PRETTY_NAME="Arch Linux"
ID=arch
BUILD_ID=rolling
ANSI_COLOR="38;2;23;147;209"
HOME_URL="https://archlinux.org/"
"#;
        let (id, version_id) = parse_os_release(body).unwrap();
        assert_eq!(id, "arch");
        assert_eq!(version_id, None);
    }

    #[test]
    fn pattern_linux_matches_any_linux_host() {
        assert!(OsPattern::Linux.matches(&fedora42()));
        assert!(!OsPattern::Linux.matches(&Os::Macos));
    }

    #[test]
    fn pattern_macos_does_not_match_linux() {
        assert!(OsPattern::Macos.matches(&Os::Macos));
        assert!(!OsPattern::Macos.matches(&fedora42()));
    }

    #[test]
    fn pattern_fedora_matches_any_fedora_version() {
        let p = OsPattern::LinuxDistro(DistroPattern::Fedora);
        assert!(p.matches(&fedora42()));
        assert!(!p.matches(&Os::Macos));
    }

    #[test]
    fn pattern_arch_matches_arch_host_only() {
        let p = OsPattern::LinuxDistro(DistroPattern::Arch);
        assert!(p.matches(&arch_host()));
        assert!(!p.matches(&fedora42()));
        assert!(!p.matches(&Os::Macos));
    }

    #[test]
    fn pattern_linux_matches_arch_host_too() {
        // Sanity: the `linux` wildcard pattern accepts rolling distros
        // (Arch) the same way it accepts versioned ones.
        assert!(OsPattern::Linux.matches(&arch_host()));
    }

    #[test]
    fn display_renders_arch_without_version() {
        assert_eq!(arch_host().to_string(), "arch");
    }

    #[test]
    fn pattern_fedora_42_matches_exact_release() {
        let p = OsPattern::LinuxDistro(DistroPattern::FedoraVersion(FedoraVersion::F42));
        assert!(p.matches(&fedora42()));
        assert!(!p.matches(&Os::Macos));
    }

    #[test]
    fn pattern_round_trips_through_toml_string() {
        for token in SUPPORTED_TOKENS {
            #[derive(serde::Deserialize, serde::Serialize)]
            struct Holder {
                v: OsPattern,
            }
            let h: Holder = toml::from_str(&format!(r#"v = "{token}""#)).unwrap();
            let back = toml::to_string(&h).unwrap();
            assert!(
                back.contains(&format!("v = \"{token}\"")),
                "expected `v = \"{token}\"` in {back}"
            );
        }
    }

    #[test]
    fn display_renders_macos_and_fedora_42() {
        assert_eq!(Os::Macos.to_string(), "macos");
        assert_eq!(fedora42().to_string(), "fedora 42");
    }

    #[test]
    fn pattern_rejects_unknown_token() {
        #[derive(Debug, serde::Deserialize)]
        struct Holder {
            #[allow(dead_code)]
            v: OsPattern,
        }
        let err = toml::from_str::<Holder>(r#"v = "windows""#)
            .unwrap_err()
            .to_string();
        assert!(err.contains("unknown os value 'windows'"), "got: {err}");
        assert!(err.contains("\"linux\""), "got: {err}");
        assert!(err.contains("\"fedora-42\""), "got: {err}");
    }
}