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
//! Detected package managers and the grammar registry.
//!
//! Each [`PackageManager`] is a manager that's actually present on this
//! host (i.e. its binary was found on `PATH`). Construction goes through
//! [`detect_all`], which walks the closed [`GRAMMARS`] list, PATH-probes
//! each entry, and returns whatever exists.
//!
//! [`GRAMMARS`] is the single place that defines *how* zenops invokes a
//! manager — binary name, `sudo` requirement, install-command template,
//! and which distros ship it as their native manager. Adding a new
//! manager (zypper, apk, paru, …) is a single row here and a default
//! `install_hint.<name>` schema entry; detection and the rest of the
//! platform plumbing pick it up automatically.

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

use smol_str::SmolStr;

use super::identity::Identity;
use crate::utils::which::{self, SearchPath};

/// A package manager known to zenops *and* present on this host.
///
/// Created by detection at startup; never constructed by callers outside
/// of tests. Carries the invocation grammar copied off the registry at
/// detect time plus the resolved binary path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackageManager {
    name: SmolStr,
    binary: PathBuf,
    needs_sudo: bool,
    install_cmd_template: SmolStr,
}

impl PackageManager {
    /// Stable lowercase identifier used everywhere the manager is named:
    /// human output, `[pkg.<x>.install_hint.<name>]` keys, JSON event
    /// fields, the install-footer label.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Absolute path of the manager binary that was found on PATH.
    pub fn binary(&self) -> &Path {
        &self.binary
    }

    /// Whether the install command needs to be prefixed with `sudo`.
    pub fn needs_sudo(&self) -> bool {
        self.needs_sudo
    }

    /// Render the install command for the given package list, e.g.
    /// `"sudo dnf install ripgrep fd-find"`. The template carries the
    /// manager-specific shape (`pacman -S`, `apt install`, …); sudo is
    /// applied here based on [`needs_sudo`](Self::needs_sudo).
    pub fn install_command(&self, packages: &[String]) -> String {
        let pkgs = packages.join(" ");
        let rendered = self.install_cmd_template.replace("{pkgs}", &pkgs);
        if self.needs_sudo {
            format!("sudo {rendered}")
        } else {
            rendered
        }
    }
}

/// One row in the closed grammar registry — everything zenops needs to
/// know about a manager *without* knowing whether it's on this host yet.
#[derive(Debug, Clone, Copy)]
struct Grammar {
    name: &'static str,
    binary_name: &'static str,
    needs_sudo: bool,
    install_cmd_template: &'static str,
    role: Role,
    /// os-release `ID`s this manager is the native manager for. Matched
    /// against the host's `ID` *and* its `ID_LIKE` chain, so derivatives
    /// (Pop!_OS → ubuntu, EndeavourOS → arch, Bazzite → fedora) are
    /// covered without a row each. Empty for managers no distro ships as
    /// its own.
    native_ids: &'static [&'static str],
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Role {
    /// Wins the primary slot outright when present — installing it is an
    /// explicit user act that signals "use me". brew today.
    Preferred,
    /// A distro's own manager. Eligible for primary; the one matching the
    /// host's identity wins, with registry order as the tiebreak for a
    /// host whose identity names none of them.
    Native,
    /// Never primary — fills gaps the primary can't (cargo for Rust
    /// crates).
    Supplementary,
}

/// Every package manager zenops knows the invocation grammar for. Order
/// is the tiebreak when host identity doesn't settle the primary slot.
const GRAMMARS: &[Grammar] = &[
    Grammar {
        name: "brew",
        binary_name: "brew",
        needs_sudo: false,
        install_cmd_template: "brew install {pkgs}",
        role: Role::Preferred,
        native_ids: &[],
    },
    Grammar {
        name: "dnf",
        binary_name: "dnf",
        needs_sudo: true,
        install_cmd_template: "dnf install {pkgs}",
        role: Role::Native,
        native_ids: &["fedora", "rhel", "centos", "rocky", "almalinux"],
    },
    Grammar {
        name: "apt",
        binary_name: "apt",
        needs_sudo: true,
        install_cmd_template: "apt install {pkgs}",
        role: Role::Native,
        native_ids: &["debian", "ubuntu"],
    },
    Grammar {
        name: "pacman",
        binary_name: "pacman",
        needs_sudo: true,
        install_cmd_template: "pacman -S {pkgs}",
        role: Role::Native,
        native_ids: &["arch"],
    },
    Grammar {
        name: "cargo",
        binary_name: "cargo",
        needs_sudo: false,
        install_cmd_template: "cargo install {pkgs}",
        role: Role::Supplementary,
        native_ids: &[],
    },
];

/// Probe every known manager against `path` and partition the hits into
/// `(primary, supplementary)`. Everything that isn't primary rides along
/// as supplementary in registry order — brew never suppresses a native
/// manager's install hints, and vice versa.
///
/// Primary goes to brew when it's present, else to the manager native to
/// `identity`, else to the first [`Role::Native`] hit in registry order.
/// The identity step matters because a manager being installed doesn't
/// make it the host's: dnf is packaged for Debian, and picking it there
/// would have zenops suggest `sudo dnf install …` on an apt system.
pub fn detect_all(
    path: &SearchPath,
    identity: &Identity,
) -> Result<(Option<PackageManager>, Vec<PackageManager>), which::Error> {
    let mut found: Vec<(Role, PackageManager)> = Vec::new();
    for g in GRAMMARS {
        let Some(binary) = which::get_path(g.binary_name, path)? else {
            continue;
        };
        found.push((
            g.role,
            PackageManager {
                name: SmolStr::new_static(g.name),
                binary,
                needs_sudo: g.needs_sudo,
                install_cmd_template: SmolStr::new_static(g.install_cmd_template),
            },
        ));
    }
    let primary = pick_primary(&found, identity).map(|i| found.remove(i).1);
    let supplementary = found.into_iter().map(|(_, pm)| pm).collect();
    Ok((primary, supplementary))
}

/// Index of the manager that takes the primary slot, if any.
fn pick_primary(found: &[(Role, PackageManager)], identity: &Identity) -> Option<usize> {
    if let Some(i) = found.iter().position(|(r, _)| *r == Role::Preferred) {
        return Some(i);
    }
    if let Some(native) = native_for(identity)
        && let Some(i) = found.iter().position(|(_, pm)| pm.name() == native)
    {
        return Some(i);
    }
    found.iter().position(|(r, _)| *r == Role::Native)
}

/// The manager name this host's distro ships as its own, matching `ID`
/// first and then the `ID_LIKE` chain. `None` on a host with no
/// os-release (macOS) or one naming a distro no grammar row claims —
/// both cases where there's nothing to prefer.
fn native_for(identity: &Identity) -> Option<&'static str> {
    let claims = |id: &str| {
        GRAMMARS
            .iter()
            .find(|g| g.native_ids.contains(&id))
            .map(|g| g.name)
    };
    if let Some(id) = identity.distro_id.as_deref()
        && let Some(name) = claims(id)
    {
        return Some(name);
    }
    identity.distro_id_like.iter().find_map(|l| claims(l))
}

/// The install prefixes Homebrew itself supports: Apple silicon, Intel
/// macOS, and Linuxbrew. A brew found anywhere else is a custom build or
/// a shim.
const BREW_PREFIX_CANDIDATES: &[&str] =
    &["/opt/homebrew", "/usr/local", "/home/linuxbrew/.linuxbrew"];

/// Resolve the Homebrew install prefix that `${brew_prefix}` expands to.
/// `path_found` is the brew binary [`detect_all`] resolved on `PATH`, if
/// any.
///
/// The prefix is deliberately *not* tied to brew being on `PATH`. On a
/// fresh macOS install Homebrew sits at `/opt/homebrew` but isn't on the
/// login shell's `PATH` until a `brew shellenv` line lands in the profile
/// — which is exactly the file zenops is being asked to write. Gating
/// `${brew_prefix}` on `PATH` there would make `pkg.brew-macos` undetectable
/// and leave zenops unable to write the file that fixes it.
pub fn brew_prefix(path_found: Option<&Path>) -> Result<Option<PathBuf>, super::Error> {
    brew_prefix_among(path_found, BREW_PREFIX_CANDIDATES)
}

/// [`brew_prefix`] with the candidate roots as a parameter, so tests can
/// point it at a temp dir instead of the real `/opt/homebrew`.
fn brew_prefix_among(
    path_found: Option<&Path>,
    candidates: &[&str],
) -> Result<Option<PathBuf>, super::Error> {
    // Walk up two levels: `<prefix>/bin/brew` → `<prefix>`.
    let derived = path_found.and_then(|b| b.parent()?.parent().map(Path::to_path_buf));
    if let Some(p) = &derived
        && candidates.iter().any(|c| Path::new(c) == p)
    {
        return Ok(Some(p.clone()));
    }
    // Probe the standard roots. This finds an install that isn't on PATH
    // yet, and steps around a `brew` shim (mise, asdf, ~/.local/bin) whose
    // parent-of-parent is not a Homebrew prefix at all.
    for prefix in candidates.iter().map(Path::new) {
        let brew = prefix.join("bin/brew");
        if brew
            .try_exists()
            .map_err(|e| super::Error::BrewProbe(brew.clone(), e))?
        {
            return Ok(Some(prefix.to_path_buf()));
        }
    }
    // Nothing standard on disk — fall back to whatever PATH gave us. A
    // custom prefix is legal, just unverifiable.
    Ok(derived)
}

/// Test-only constructor — builds a [`PackageManager`] from a grammar
/// row by name without touching the filesystem. Panics if `name` isn't
/// in [`GRAMMARS`]. Callers use this to assemble synthetic
/// [`super::Platform`] values without standing up real binaries.
#[cfg(test)]
pub fn for_test(name: &str, binary: PathBuf) -> PackageManager {
    let g = GRAMMARS
        .iter()
        .find(|g| g.name == name)
        .unwrap_or_else(|| panic!("unknown manager name in for_test: {name}"));
    PackageManager {
        name: SmolStr::new_static(g.name),
        binary,
        needs_sudo: g.needs_sudo,
        install_cmd_template: SmolStr::new_static(g.install_cmd_template),
    }
}

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

    fn pm(name: &str) -> PackageManager {
        for_test(name, PathBuf::from(format!("/usr/bin/{name}")))
    }

    /// Absolute candidate prefixes under a temp `root`, so the probe runs
    /// against a temp dir instead of the real filesystem.
    fn candidates(root: &Path, names: &[&str]) -> Vec<String> {
        names
            .iter()
            .map(|n| root.join(n).to_string_lossy().into_owned())
            .collect()
    }

    /// Plant a real-looking `<prefix>/bin/brew` for the probe to find.
    fn install_brew(prefix: &Path) -> PathBuf {
        let bin = prefix.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let brew = bin.join("brew");
        std::fs::write(&brew, "#!/bin/sh\n").unwrap();
        brew
    }

    #[test]
    fn install_command_brew_no_sudo() {
        let pkgs = vec!["ripgrep".into(), "fd".into()];
        assert_eq!(pm("brew").install_command(&pkgs), "brew install ripgrep fd");
    }

    #[test]
    fn install_command_dnf_with_sudo() {
        let pkgs = vec!["ripgrep".into()];
        assert_eq!(pm("dnf").install_command(&pkgs), "sudo dnf install ripgrep");
    }

    #[test]
    fn install_command_pacman_uses_sync_flag() {
        let pkgs = vec!["skim".into()];
        assert_eq!(pm("pacman").install_command(&pkgs), "sudo pacman -S skim");
    }

    #[test]
    fn install_command_apt_with_sudo() {
        let pkgs = vec!["fd-find".into()];
        assert_eq!(pm("apt").install_command(&pkgs), "sudo apt install fd-find");
    }

    #[test]
    fn install_command_cargo_no_sudo() {
        let pkgs = vec!["skim".into(), "starship".into()];
        assert_eq!(
            pm("cargo").install_command(&pkgs),
            "cargo install skim starship"
        );
    }

    #[test]
    fn brew_prefix_derived_from_binary_on_a_standard_root() {
        let dir = tempfile::tempdir().unwrap();
        let cands = candidates(dir.path(), &["opt/homebrew", "usr/local"]);
        let refs: Vec<&str> = cands.iter().map(String::as_str).collect();
        let brew = install_brew(Path::new(&cands[0]));
        assert_eq!(
            brew_prefix_among(Some(&brew), &refs).unwrap(),
            Some(PathBuf::from(&cands[0]))
        );
    }

    #[test]
    fn brew_prefix_found_by_probe_when_brew_is_not_on_path() {
        // The fresh-macOS case: Homebrew is installed but nothing has put
        // it on PATH yet — that's the very thing zenops is about to write
        // into the login profile, so `${brew_prefix}` has to resolve
        // without PATH's help.
        let dir = tempfile::tempdir().unwrap();
        let cands = candidates(dir.path(), &["opt/homebrew", "usr/local"]);
        let refs: Vec<&str> = cands.iter().map(String::as_str).collect();
        install_brew(Path::new(&cands[0]));
        assert_eq!(
            brew_prefix_among(None, &refs).unwrap(),
            Some(PathBuf::from(&cands[0]))
        );
    }

    #[test]
    fn brew_prefix_prefers_a_standard_root_over_a_path_shim() {
        // A `brew` shim earlier on PATH (mise, asdf, ~/.local/bin) would
        // otherwise derive a prefix that isn't a Homebrew root at all.
        let dir = tempfile::tempdir().unwrap();
        let cands = candidates(dir.path(), &["opt/homebrew"]);
        let refs: Vec<&str> = cands.iter().map(String::as_str).collect();
        install_brew(Path::new(&cands[0]));
        let shim = install_brew(&dir.path().join("home/user/.local"));
        assert_eq!(
            brew_prefix_among(Some(&shim), &refs).unwrap(),
            Some(PathBuf::from(&cands[0]))
        );
    }

    #[test]
    fn brew_prefix_falls_back_to_a_custom_install_on_path() {
        // No standard root on disk: a non-standard prefix is legal, and
        // PATH is the only evidence we have of it.
        let dir = tempfile::tempdir().unwrap();
        let cands = candidates(dir.path(), &["opt/homebrew"]);
        let refs: Vec<&str> = cands.iter().map(String::as_str).collect();
        let custom = dir.path().join("srv/brew");
        let brew = install_brew(&custom);
        assert_eq!(brew_prefix_among(Some(&brew), &refs).unwrap(), Some(custom));
    }

    #[test]
    fn brew_prefix_none_without_brew_anywhere() {
        let dir = tempfile::tempdir().unwrap();
        let cands = candidates(dir.path(), &["opt/homebrew", "usr/local"]);
        let refs: Vec<&str> = cands.iter().map(String::as_str).collect();
        assert_eq!(brew_prefix_among(None, &refs).unwrap(), None);
    }

    #[test]
    fn detect_all_empty_search_path_yields_nothing() {
        let path = SearchPath::new(Vec::<PathBuf>::new());
        let (primary, supp) = detect_all(&path, &Identity::default()).unwrap();
        assert!(primary.is_none());
        assert!(supp.is_empty());
    }

    /// A search path holding an executable stub per named binary.
    #[cfg(unix)]
    fn path_with(dir: &Path, binaries: &[&str]) -> SearchPath {
        use std::os::unix::fs::PermissionsExt;
        for name in binaries {
            let bin = dir.join(name);
            std::fs::write(&bin, "#!/bin/sh\n").unwrap();
            std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        SearchPath::new(vec![dir.to_path_buf()])
    }

    fn identity(id: &str, id_like: &[&str]) -> Identity {
        Identity {
            distro_id: Some(SmolStr::new(id)),
            distro_id_like: id_like.iter().map(|s| SmolStr::new(*s)).collect(),
            distro_version_id: None,
        }
    }

    #[cfg(unix)]
    #[test]
    fn brew_and_native_both_surface_with_brew_primary() {
        // The Linux-with-brew case: when both brew and a native manager
        // are present, zenops surfaces BOTH. brew takes the single primary
        // slot and the native manager rides along as supplementary, so its
        // install hints still show. This locks in the "show both" decision
        // — brew does not suppress the native manager (which is the right
        // call on Linux, where brew is an additional layer, not a
        // replacement for apt/dnf/pacman).
        let dir = tempfile::tempdir().unwrap();
        let path = path_with(dir.path(), &["brew", "dnf"]);
        let (primary, supp) = detect_all(&path, &identity("fedora", &[])).unwrap();
        assert_eq!(primary.as_ref().map(PackageManager::name), Some("brew"));
        let supp: Vec<&str> = supp.iter().map(PackageManager::name).collect();
        assert!(
            supp.contains(&"dnf"),
            "native dnf should ride along as supplementary, got {supp:?}",
        );
    }

    #[cfg(unix)]
    #[test]
    fn primary_follows_host_identity_not_registry_order() {
        // dnf is packaged for Debian and Ubuntu. Registry order alone
        // would make it primary on an apt host and have zenops suggest
        // `sudo dnf install …` there.
        let dir = tempfile::tempdir().unwrap();
        let path = path_with(dir.path(), &["dnf", "apt"]);
        let (primary, supp) = detect_all(&path, &identity("ubuntu", &["debian"])).unwrap();
        assert_eq!(primary.as_ref().map(PackageManager::name), Some("apt"));
        let supp: Vec<&str> = supp.iter().map(PackageManager::name).collect();
        assert_eq!(supp, vec!["dnf"], "dnf still surfaces, just not primary");
    }

    #[cfg(unix)]
    #[test]
    fn primary_falls_back_to_registry_order_for_an_unclaimed_distro() {
        // A distro no grammar row claims: nothing to prefer, so the first
        // native manager found wins.
        let dir = tempfile::tempdir().unwrap();
        let path = path_with(dir.path(), &["dnf", "apt"]);
        let (primary, _) = detect_all(&path, &identity("haiku", &[])).unwrap();
        assert_eq!(primary.as_ref().map(PackageManager::name), Some("dnf"));
    }

    #[cfg(unix)]
    #[test]
    fn cargo_alone_is_never_primary() {
        let dir = tempfile::tempdir().unwrap();
        let path = path_with(dir.path(), &["cargo"]);
        let (primary, supp) = detect_all(&path, &identity("fedora", &[])).unwrap();
        assert!(primary.is_none());
        assert_eq!(
            supp.iter().map(PackageManager::name).collect::<Vec<_>>(),
            vec!["cargo"]
        );
    }

    #[test]
    fn native_for_matches_id_then_id_like() {
        assert_eq!(native_for(&identity("fedora", &[])), Some("dnf"));
        assert_eq!(native_for(&identity("debian", &[])), Some("apt"));
        assert_eq!(native_for(&identity("arch", &[])), Some("pacman"));
        // Derivatives are covered by the ID_LIKE chain, no row each.
        assert_eq!(
            native_for(&identity("pop", &["ubuntu", "debian"])),
            Some("apt")
        );
        assert_eq!(
            native_for(&identity("endeavouros", &["arch"])),
            Some("pacman")
        );
        assert_eq!(native_for(&identity("bazzite", &["fedora"])), Some("dnf"));
        // Unclaimed distro, and a host with no os-release at all.
        assert_eq!(native_for(&identity("haiku", &[])), None);
        assert_eq!(native_for(&Identity::default()), None);
    }

    #[test]
    fn registry_has_no_duplicate_names() {
        let mut names: Vec<&str> = GRAMMARS.iter().map(|g| g.name).collect();
        names.sort();
        let mut dedup = names.clone();
        dedup.dedup();
        assert_eq!(names, dedup, "duplicate manager names in GRAMMARS");
    }
}