zenops 0.20.0

Declarative system configuration management for shell config and dotfiles.
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
//! Host platform facts as one struct.
//!
//! [`Platform`] is the single source of truth for everything zenops
//! needs to know about the machine it's running on. It bundles:
//!
//! - **Filesystem** — `$HOME` and derived `~/.config` / `~/.config/zenops`
//!   roots.
//! - **Identity** (informational, never gates zenops itself) — `os_family`,
//!   `distro_id`, `distro_id_like`, `distro_version_id`, `arch`, `hostname`.
//!   The distro fields are raw strings copied straight out of
//!   `/etc/os-release`; we never interpret them.
//! - **Capabilities** — the primary and supplementary package managers
//!   actually present on this host (PATH-probed), the declared and
//!   detected shells, the binary search path.
//!
//! Construction goes through [`Platform::detect`]. Every host *fact* it
//! can't determine becomes `None` / empty, so running on an unrecognised
//! distro is a degraded host rather than a crash. File management and
//! shell init still work, package-install hints surface for whatever
//! managers are present, and user `when` clauses still match through
//! `ID_LIKE` (`when = "ubuntu"` accepts Pop!_OS). It returns a `Result`
//! only because the probing machinery itself can fail — a `PATH` entry
//! that won't canonicalise, a candidate Homebrew prefix that won't stat.
//! Those errors are bubbled, not swallowed.
//!
//! User-authored `when` patterns use [`OsPattern`], which matches against
//! the identity fields. Detection of which package managers are installed
//! goes through a closed grammar registry inside the `manager` submodule —
//! probing each known manager binary on `PATH`.

use std::path::{Path, PathBuf};

use indexmap::IndexMap;
use smol_str::SmolStr;

use crate::utils::which::{self, SearchPath};

mod identity;
mod manager;
mod pattern;

pub use manager::PackageManager;
pub use pattern::OsPattern;

#[cfg(test)]
pub use identity::Identity;

#[cfg(test)]
pub use manager::for_test as manager_for_test;

/// Failure modes for [`Platform::detect`]. Host *facts* that can't be
/// determined degrade to `None`; these two are machinery failures, and
/// are bubbled rather than swallowed.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// A `PATH` lookup failed for a reason other than "binary not found"
    /// — e.g. a `PATH` entry that won't canonicalise.
    #[error(transparent)]
    Which(#[from] which::Error),
    /// Failed to stat a candidate Homebrew install prefix.
    #[error("Failed to probe for brew at {0:?}: {1}")]
    BrewProbe(PathBuf, #[source] std::io::Error),
}

/// Active shell. Same lowercase TOML token in both `[shell].type` and
/// `$SHELL` basename detection.
#[derive(serde::Deserialize, schemars::JsonSchema, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Shell {
    /// The Bourne Again shell.
    Bash,
    /// The Z shell.
    Zsh,
}

impl Shell {
    /// Map a `$SHELL` basename (`"bash"`, `"zsh"`, …) to the matching
    /// [`Shell`]. Returns `None` for anything else — zenops only manages
    /// bash and zsh today.
    pub fn from_basename(name: &str) -> Option<Self> {
        match name {
            "bash" => Some(Shell::Bash),
            "zsh" => Some(Shell::Zsh),
            _ => None,
        }
    }

    /// Stable lowercase identifier matching the `[shell].type` TOML token
    /// and the `$SHELL` basename. Used for human display and rendering
    /// config files.
    pub fn as_str(self) -> &'static str {
        match self {
            Shell::Bash => "bash",
            Shell::Zsh => "zsh",
        }
    }
}

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

/// OS family, with an `Other` escape hatch so detection cannot fail.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OsFamily {
    /// Any Linux kernel (`std::env::consts::OS == "linux"`).
    Linux,
    /// macOS (`std::env::consts::OS == "macos"`).
    Macos,
    /// Anything else `std::env::consts::OS` returns (FreeBSD, Haiku, …).
    /// Carries the raw token so doctor / template inputs can render it.
    Other(SmolStr),
}

impl OsFamily {
    fn detect() -> Self {
        match std::env::consts::OS {
            "linux" => OsFamily::Linux,
            "macos" => OsFamily::Macos,
            other => OsFamily::Other(SmolStr::new_static(other)),
        }
    }

    /// Lowercase token used in `${os}` template inputs and human display.
    pub fn as_token(&self) -> &str {
        match self {
            OsFamily::Linux => "linux",
            OsFamily::Macos => "macos",
            OsFamily::Other(s) => s.as_str(),
        }
    }
}

/// The host as zenops sees it. Constructed once at startup via
/// [`Platform::detect`]; threaded by reference through every subcommand
/// that makes a platform-dependent decision.
#[derive(Debug, Clone)]
pub struct Platform {
    home: PathBuf,
    config_dir: PathBuf,
    zenops_dir: PathBuf,
    path: SearchPath,
    arch: SmolStr,

    os_family: OsFamily,
    distro_id: Option<SmolStr>,
    distro_id_like: Vec<SmolStr>,
    distro_version_id: Option<SmolStr>,

    hostname: SmolStr,

    primary_pkg_manager: Option<PackageManager>,
    supplementary_pkg_managers: Vec<PackageManager>,
    brew_prefix: Option<PathBuf>,

    detected_shell: Option<Shell>,
}

impl Platform {
    /// Detect the current host. Every host fact zenops can't determine
    /// becomes `None` / empty, so detection never fails on an unknown host.
    /// It still returns a `Result` because the probing machinery itself can
    /// fail — a `PATH` entry that won't canonicalise, a candidate Homebrew
    /// prefix that won't stat — and that is bubbled, not swallowed.
    ///
    /// `home` is taken as a parameter (callers resolve it once via
    /// `home::home_dir()` at the top of `main`) so this function doesn't
    /// reach back to that global.
    pub fn detect(home: PathBuf, path: SearchPath) -> Result<Self, Error> {
        let config_dir = home.join(".config");
        let zenops_dir = home.join(".config/zenops");
        let os_family = OsFamily::detect();
        let identity = if matches!(os_family, OsFamily::Linux) {
            identity::Identity::detect()
        } else {
            identity::Identity::default()
        };
        let arch = SmolStr::new_static(std::env::consts::ARCH);
        let hostname = SmolStr::new(gethostname::gethostname().to_string_lossy());
        let detected_shell = detect_shell_from_env();
        let (primary_pkg_manager, supplementary_pkg_managers) =
            manager::detect_all(&path, &identity)?;
        let brew_on_path = primary_pkg_manager
            .iter()
            .chain(supplementary_pkg_managers.iter())
            .find(|m| m.name() == "brew");
        let brew_prefix = manager::brew_prefix(brew_on_path.map(PackageManager::binary))?;

        Ok(Self {
            home,
            config_dir,
            zenops_dir,
            path,
            arch,
            os_family,
            distro_id: identity.distro_id,
            distro_id_like: identity.distro_id_like,
            distro_version_id: identity.distro_version_id,
            hostname,
            primary_pkg_manager,
            supplementary_pkg_managers,
            brew_prefix,
            detected_shell,
        })
    }

    // --- filesystem ---

    /// Absolute path of `$HOME`.
    pub fn home(&self) -> &Path {
        &self.home
    }

    /// Expand a leading `~` or `~/...` against this host's `$HOME`. A `~`
    /// anywhere other than the start is left untouched: zenops does no
    /// `~user` expansion, so a tilde produced mid-path by `${...}`
    /// expansion is not mistaken for the home directory.
    pub fn resolve_home_tilde(&self, path: &str) -> String {
        if path == "~" {
            self.home.to_string_lossy().into_owned()
        } else if let Some(rest) = path.strip_prefix("~/") {
            // Textual splice, not `Path::join`: join drops the base when
            // the tail is absolute, so `~//etc` would resolve to `/etc`
            // rather than somewhere under `$HOME`.
            format!("{}/{rest}", self.home.display())
        } else {
            path.to_string()
        }
    }

    /// Absolute path of `$HOME/.config`. Will become `$XDG_CONFIG_HOME`-
    /// aware later; today it's a literal join.
    pub fn config_dir(&self) -> &Path {
        &self.config_dir
    }

    /// Absolute path of the cloned zenops config repo
    /// (`$HOME/.config/zenops`).
    pub fn zenops_dir(&self) -> &Path {
        &self.zenops_dir
    }

    /// Binary search path. Used by `pkg.*.detect = { which = "..." }`
    /// strategies and ad-hoc lookups via [`which`](Self::which) /
    /// [`has_binary`](Self::has_binary).
    pub fn search_path(&self) -> &SearchPath {
        &self.path
    }

    // --- identity ---

    /// OS family (`Linux` / `Macos` / `Other(token)`).
    pub fn os_family(&self) -> &OsFamily {
        &self.os_family
    }

    /// Raw `os-release.ID`, if any. `None` on macOS (no os-release) and
    /// on Linux hosts without a readable `/etc/os-release`.
    pub fn distro_id(&self) -> Option<&str> {
        self.distro_id.as_deref()
    }

    /// Raw `os-release.ID_LIKE` chain, space-split. Empty when absent.
    pub fn distro_id_like(&self) -> &[SmolStr] {
        &self.distro_id_like
    }

    /// Raw `os-release.VERSION_ID`, if any.
    pub fn distro_version_id(&self) -> Option<&str> {
        self.distro_version_id.as_deref()
    }

    /// CPU architecture — `std::env::consts::ARCH`. Not branched on
    /// today; surfaced for templates and future binary-download paths.
    pub fn arch(&self) -> &str {
        &self.arch
    }

    /// Machine hostname.
    pub fn hostname(&self) -> &str {
        &self.hostname
    }

    // --- capabilities ---

    /// The manager zenops would use to install missing packages. Brew
    /// (if PATH-found) wins; otherwise the manager this host's distro
    /// ships as its own. `None` on a host with no recognised managers
    /// at all (graceful degradation — file management still works).
    pub fn primary_pkg_manager(&self) -> Option<&PackageManager> {
        self.primary_pkg_manager.as_ref()
    }

    /// Every detected manager that didn't take the primary slot, in
    /// registry order. That's cargo, plus any other primary-eligible
    /// manager also present — on a Fedora host with brew, brew is primary
    /// and dnf lands here, so its install hints still surface.
    pub fn supplementary_pkg_managers(&self) -> &[PackageManager] {
        &self.supplementary_pkg_managers
    }

    /// All detected managers — primary (if any) followed by the
    /// supplementaries in registry order.
    pub fn all_pkg_managers(&self) -> impl Iterator<Item = &PackageManager> + '_ {
        self.primary_pkg_manager
            .iter()
            .chain(self.supplementary_pkg_managers.iter())
    }

    /// Look up a detected manager by name (e.g. `"brew"`, `"cargo"`).
    pub fn pkg_manager_by_name(&self, name: &str) -> Option<&PackageManager> {
        self.all_pkg_managers().find(|m| m.name() == name)
    }

    /// Homebrew's install prefix, behind `${brew_prefix}`. Independent of
    /// [`primary_pkg_manager`](Self::primary_pkg_manager): a Homebrew
    /// that's installed but not yet on `PATH` still has a prefix, and
    /// that's the case zenops has to write shell config for.
    pub fn brew_prefix(&self) -> Option<&Path> {
        self.brew_prefix.as_deref()
    }

    // --- shell ---

    /// Shell detected from `$SHELL`'s basename. Drives the `zenops init`
    /// bootstrap prompt and doctor display; not consulted by `when`
    /// clauses today.
    pub fn detected_shell(&self) -> Option<Shell> {
        self.detected_shell
    }

    // --- PATH probing (thin shims over `utils::which`) ---

    /// Resolve `binary` against the host's search path. `Ok(None)` when
    /// not found; only errors on lookup-machinery failure.
    pub fn which(&self, binary: &str) -> Result<Option<PathBuf>, which::Error> {
        which::get_path(binary, &self.path)
    }

    /// Whether `binary` resolves on the host's search path.
    pub fn has_binary(&self, binary: &str) -> Result<bool, which::Error> {
        which::exists(binary, &self.path)
    }

    // --- template inputs ---

    /// The platform-provided `${...}` template inputs (`${os}`,
    /// `${arch}`, `${brew_prefix}` when brew is detected). Callers may
    /// layer user-config inputs (`${user.name}`, `${user.email}`) on
    /// top in their own bag.
    pub fn template_inputs(&self) -> IndexMap<SmolStr, SmolStr> {
        let mut m = IndexMap::new();
        m.insert(
            SmolStr::new_static("os"),
            // Linux/Macos give `&'static str`, but Other carries a runtime
            // SmolStr — pay the (tiny) clone cost rather than special-case.
            SmolStr::new(self.os_family.as_token()),
        );
        m.insert(SmolStr::new_static("arch"), self.arch.clone());
        if let Some(prefix) = self.brew_prefix() {
            m.insert(
                SmolStr::new_static("brew_prefix"),
                SmolStr::new(prefix.to_string_lossy()),
            );
        }
        m
    }
}

/// `$SHELL` basename → [`Shell`]. `None` for unset / empty / non-bash-zsh.
fn detect_shell_from_env() -> Option<Shell> {
    let raw = std::env::var("SHELL").ok()?;
    let name = Path::new(&raw).file_name()?.to_str()?;
    Shell::from_basename(name)
}

// --- test helpers ---

#[cfg(test)]
impl Platform {
    /// Minimal synthetic [`Platform`] for tests that only care about the
    /// filesystem roots: identity is blank, no managers, no shells.
    pub(crate) fn for_test_home(home: PathBuf) -> Self {
        Self::for_test_with_identity(
            home,
            SearchPath::new(Vec::<PathBuf>::new()),
            SmolStr::new_static("x86_64"),
            OsFamily::Linux,
            identity::Identity::default(),
            SmolStr::new_static("test-host"),
            None,
            None,
            Vec::new(),
        )
    }

    /// Build a synthetic [`Platform`] for tests with full control over
    /// every field. Used by sibling-module tests and integration tests
    /// that need a `Platform` without standing up a real host.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn for_test_with_identity(
        home: PathBuf,
        path: SearchPath,
        arch: SmolStr,
        os_family: OsFamily,
        identity: identity::Identity,
        hostname: SmolStr,
        detected_shell: Option<Shell>,
        primary_pkg_manager: Option<PackageManager>,
        supplementary_pkg_managers: Vec<PackageManager>,
    ) -> Self {
        let config_dir = home.join(".config");
        let zenops_dir = home.join(".config/zenops");
        Self {
            home,
            config_dir,
            zenops_dir,
            path,
            arch,
            os_family,
            distro_id: identity.distro_id,
            distro_id_like: identity.distro_id_like,
            distro_version_id: identity.distro_version_id,
            hostname,
            primary_pkg_manager,
            supplementary_pkg_managers,
            brew_prefix: None,
            detected_shell,
        }
    }

    /// Attach a Homebrew prefix to a synthetic platform. Separate from
    /// the constructors because brew detection is independent of the
    /// package-manager fields.
    pub(crate) fn with_brew_prefix(mut self, prefix: PathBuf) -> Self {
        self.brew_prefix = Some(prefix);
        self
    }
}

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

    fn fedora_platform() -> Platform {
        Platform::for_test_with_identity(
            PathBuf::from("/home/test"),
            SearchPath::new(Vec::<PathBuf>::new()),
            SmolStr::new_static("x86_64"),
            OsFamily::Linux,
            Identity {
                distro_id: Some(SmolStr::new("fedora")),
                distro_id_like: Vec::new(),
                distro_version_id: Some(SmolStr::new("42")),
            },
            SmolStr::new_static("host"),
            Some(Shell::Zsh),
            None,
            Vec::new(),
        )
    }

    #[test]
    fn detect_runs_on_current_host_without_error() {
        // Smoke test only — we can't make strong assertions about the
        // build host, but detect must never error.
        let home = std::env::temp_dir();
        let path = SearchPath::from_env();
        let p = Platform::detect(home, path).expect("detect must not error");
        // Hostname is non-empty on every reasonable build host.
        assert!(!p.hostname().is_empty());
        // Arch always populated from consts::ARCH.
        assert!(!p.arch().is_empty());
    }

    #[test]
    fn config_and_zenops_dirs_are_derived_from_home() {
        let p = fedora_platform();
        assert_eq!(p.home(), Path::new("/home/test"));
        assert_eq!(p.config_dir(), Path::new("/home/test/.config"));
        assert_eq!(p.zenops_dir(), Path::new("/home/test/.config/zenops"));
    }

    #[test]
    fn template_inputs_include_os_and_arch() {
        let p = fedora_platform();
        let inputs = p.template_inputs();
        assert_eq!(inputs.get("os").map(SmolStr::as_str), Some("linux"));
        assert_eq!(inputs.get("arch").map(SmolStr::as_str), Some("x86_64"));
        // No brew detected on this synthetic platform.
        assert!(inputs.get("brew_prefix").is_none());
    }

    #[test]
    fn template_inputs_include_brew_prefix_when_present() {
        // Note the empty manager fields: `${brew_prefix}` comes off the
        // prefix, not off brew being on PATH. This is the fresh-macOS
        // host whose login profile doesn't source `brew shellenv` yet.
        let p = Platform::for_test_with_identity(
            PathBuf::from("/Users/test"),
            SearchPath::new(Vec::<PathBuf>::new()),
            SmolStr::new_static("aarch64"),
            OsFamily::Macos,
            Identity::default(),
            SmolStr::new_static("mac"),
            None,
            None,
            Vec::new(),
        )
        .with_brew_prefix(PathBuf::from("/opt/homebrew"));
        assert!(p.pkg_manager_by_name("brew").is_none());
        let inputs = p.template_inputs();
        assert_eq!(
            inputs.get("brew_prefix").map(SmolStr::as_str),
            Some("/opt/homebrew"),
        );
    }

    #[test]
    fn os_family_other_renders_as_raw_token() {
        let fam = OsFamily::Other(SmolStr::new_static("freebsd"));
        assert_eq!(fam.as_token(), "freebsd");
    }

    #[test]
    fn shell_from_basename() {
        assert_eq!(Shell::from_basename("bash"), Some(Shell::Bash));
        assert_eq!(Shell::from_basename("zsh"), Some(Shell::Zsh));
        assert_eq!(Shell::from_basename("fish"), None);
        assert_eq!(Shell::from_basename(""), None);
    }

    #[test]
    fn all_pkg_managers_concatenates_primary_and_supplementary() {
        let p = Platform::for_test_with_identity(
            PathBuf::from("/h"),
            SearchPath::new(Vec::<PathBuf>::new()),
            SmolStr::new_static("x86_64"),
            OsFamily::Linux,
            Identity::default(),
            SmolStr::new_static("h"),
            None,
            Some(manager::for_test("dnf", PathBuf::from("/usr/bin/dnf"))),
            vec![manager::for_test(
                "cargo",
                PathBuf::from("/home/h/.cargo/bin/cargo"),
            )],
        );
        let names: Vec<&str> = p.all_pkg_managers().map(PackageManager::name).collect();
        assert_eq!(names, vec!["dnf", "cargo"]);
        assert_eq!(
            p.pkg_manager_by_name("dnf").map(PackageManager::name),
            Some("dnf")
        );
        assert_eq!(
            p.pkg_manager_by_name("cargo").map(PackageManager::name),
            Some("cargo")
        );
        assert!(p.pkg_manager_by_name("brew").is_none());
    }

    #[test]
    fn recognised_identity_with_no_managers_has_no_primary() {
        // Capability is probed, never derived from identity. A host that
        // identifies as Fedora but whose package manager isn't on the
        // search path zenops captured (a stripped PATH in a cron job, a
        // minimal container) is still recognised as fedora, but reports no
        // primary manager rather than pretending dnf is reachable. This
        // decoupling is deliberate: install hints degrade to "no path
        // here" instead of emitting a command that would fail.
        let p = Platform::for_test_with_identity(
            PathBuf::from("/home/test"),
            SearchPath::new(Vec::<PathBuf>::new()),
            SmolStr::new_static("x86_64"),
            OsFamily::Linux,
            Identity {
                distro_id: Some(SmolStr::new("fedora")),
                distro_id_like: Vec::new(),
                distro_version_id: Some(SmolStr::new("42")),
            },
            SmolStr::new_static("host"),
            None,
            None,
            Vec::new(),
        );
        assert_eq!(p.distro_id(), Some("fedora"));
        assert!(p.primary_pkg_manager().is_none());
        assert!(p.all_pkg_managers().next().is_none());
    }

    #[test]
    fn resolve_home_tilde_only_expands_leading_tilde() {
        let p = Platform::for_test_home(PathBuf::from("/home/test"));
        assert_eq!(p.resolve_home_tilde("~"), "/home/test");
        assert_eq!(p.resolve_home_tilde("~/foo/bar"), "/home/test/foo/bar");
        // The tail stays under $HOME even when it looks absolute — a
        // `${...}` that expands to `/etc/passwd` must not escape.
        assert_eq!(
            p.resolve_home_tilde("~//etc/passwd"),
            "/home/test//etc/passwd"
        );
        // A non-leading tilde is left alone: no `~user` expansion, and a
        // mid-path `~` from `${...}` expansion must not be mangled.
        assert_eq!(p.resolve_home_tilde("/etc/~lock"), "/etc/~lock");
        assert_eq!(p.resolve_home_tilde("~user/x"), "~user/x");
        assert_eq!(p.resolve_home_tilde("plain/path"), "plain/path");
    }
}