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
// Shared across multiple integration-test binaries; each binary uses a
// different subset, so per-binary dead-code warnings are expected.
#![allow(dead_code)]

use std::{
    io::Write,
    path::{Path, PathBuf},
    sync::Arc,
};
use xshell::{Shell, cmd};
use zenops::{
    Args, Cmd, ColorChoice,
    config_files::ConfigFilePath,
    error::Error,
    output::{
        AppliedAction, BootstrapSummary, DoctorCheck, Event, ImportApplied, ImportPlan,
        InitSummary, OutputError, PkgEntry, ResolvedConfigFilePath, Status,
    },
    pkg_list,
    platform::Platform,
};
use zenops_safe_relative_path::{SafeRelativePath, srpath};

pub mod paths {
    use zenops_safe_relative_path::{SafeRelativePath, srpath};

    pub const HOME_DIR: &SafeRelativePath = srpath!("home/bob");
    pub const CONFIG_DIR: &SafeRelativePath = srpath!("home/bob/.config");
    pub const ZENOPS_DIR: &SafeRelativePath = srpath!("home/bob/.config/zenops");
    pub const ZENOPS_CONFIG: &SafeRelativePath = srpath!("home/bob/.config/zenops/config.toml");
}

pub struct TestEnv {
    #[allow(dead_code)] // Needed for automatic cleanup
    root: tempfile::TempDir,
    home: PathBuf,
    platform: Platform,
    bin_dir: PathBuf,
    default_args: Args,
    sh: Shell,
}

impl TestEnv {
    pub fn load() -> Self {
        let root = tempfile::tempdir().unwrap();
        let home = root.path().join("home/bob");
        let bin_dir = root.path().join("bin");
        std::fs::create_dir_all(&bin_dir).unwrap();
        let platform = Self::detect_platform(home.clone(), &bin_dir);
        let sh = Shell::new().unwrap();
        sh.change_dir(root.path());
        std::fs::create_dir_all(paths::ZENOPS_DIR.to_full_path(root.path())).unwrap();
        Self {
            root,
            home,
            platform,
            bin_dir,
            default_args: Args {
                color: ColorChoice::Never,
                stdin_is_terminal: false,
            },
            sh,
        }
    }

    fn detect_platform(home: PathBuf, bin_dir: &Path) -> Platform {
        let search_path = zenops::utils::which::SearchPath::new(vec![bin_dir.to_path_buf()]);
        // Detect a Platform pinned to the test home dir and the controlled
        // bin/ search path so pkg detection is deterministic across hosts.
        Platform::detect(home, search_path).expect("platform detection must not fail in tests")
    }

    /// Build a fresh [`Platform`] from the current `bin/` contents. Tests
    /// that call [`Self::add_binary`] after `load()` need a refreshed
    /// detection so the platform's package-manager list reflects the new
    /// binary. Returns a new `Platform` rather than mutating `self.platform`
    /// so test bindings can stay `let env = ...` instead of `let mut env`.
    fn fresh_platform(&self) -> Platform {
        Self::detect_platform(self.home.clone(), &self.bin_dir)
    }

    /// Place a 0-byte executable named `name` in the env's controlled
    /// `bin/` directory so `which`-driven detection finds it. Tests opt in
    /// to each binary they expect to be present, so detection outcomes are
    /// deterministic across hosts.
    pub fn add_binary(&self, name: &str) {
        let bin = self.bin_dir.join(name);
        std::fs::write(&bin, b"").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
    }

    pub fn resolve_path(&self, path: impl AsRef<SafeRelativePath>) -> PathBuf {
        path.as_ref().to_full_path(self.root.path())
    }

    pub fn cfpath(
        &self,
        path: impl AsRef<str>,
        map: impl FnOnce(Arc<SafeRelativePath>) -> ConfigFilePath,
    ) -> ResolvedConfigFilePath {
        let path = map(Arc::from(
            SafeRelativePath::from_relative_path(path.as_ref()).unwrap(),
        ));
        let full = path.resolved(&self.platform);

        ResolvedConfigFilePath {
            path,
            full: Arc::from(full),
        }
    }

    /// The `Status::GitRepoClean` entry emitted for this env's zenops repo
    /// when it has no uncommitted changes. Every test whose zenops repo is
    /// in a clean state has this prepended to its expected entries.
    pub fn git_repo_clean_entry(&self) -> Entry {
        Entry::Status(Status::GitRepoClean {
            repo: self.cfpath("", ConfigFilePath::Zenops),
        })
    }

    pub fn ensure_dir_exists_for_file(&self, file_path: impl AsRef<SafeRelativePath>) {
        if let Some(dir) = file_path.as_ref().safe_parent() {
            let path = dir.to_full_path(self.root.path());
            std::fs::create_dir_all(&path)
                .unwrap_or_else(|e| panic!("Failed to create directory {path:?}: {e}"));
        }
    }

    pub fn write_file(&self, path: impl AsRef<SafeRelativePath>, data: impl AsRef<[u8]>) {
        let path = path.as_ref();
        self.ensure_dir_exists_for_file(path);
        let full_path = path.to_full_path(self.root.path());
        std::fs::write(&full_path, data)
            .unwrap_or_else(|e| panic!("Failed to write to {path}: {e}\nFull path: {full_path:?}"));
    }

    pub fn delete_file(&self, path: impl AsRef<SafeRelativePath>) {
        let path = path.as_ref();
        self.ensure_dir_exists_for_file(path);
        let full_path = path.to_full_path(self.root.path());
        std::fs::remove_file(&full_path)
            .unwrap_or_else(|e| panic!("Failed to delete {path}: {e}\nFull path: {full_path:?}"));
    }

    pub fn delete_dir_all(&self, path: impl AsRef<SafeRelativePath>) {
        let path = path.as_ref();
        self.ensure_dir_exists_for_file(path);
        let full_path = path.to_full_path(self.root.path());
        std::fs::remove_dir_all(&full_path)
            .unwrap_or_else(|e| panic!("Failed to delete {path}: {e}\nFull path: {full_path:?}"));
    }

    pub fn create_dir(&self, path: impl AsRef<SafeRelativePath>) {
        let path = path.as_ref();
        let full_path = path.to_full_path(self.root.path());
        std::fs::create_dir_all(&full_path).unwrap_or_else(|e| {
            panic!("Failed to create directory {path}: {e}\nFull path: {full_path:?}")
        });
    }

    pub fn append_file(&self, path: impl AsRef<SafeRelativePath>, data: impl AsRef<[u8]>) {
        let path = path.as_ref().to_full_path(self.root.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::OpenOptions::new()
            .append(true)
            .create(true)
            .open(&path)
            .unwrap()
            .write_all(data.as_ref())
            .unwrap();
    }

    pub fn write_zenops_file(
        &self,
        path: impl AsRef<SafeRelativePath>,
        data: impl AsRef<[u8]>,
        commit: Option<&str>,
    ) {
        let path = path.as_ref();
        self.write_file(paths::ZENOPS_DIR.safe_join(path), data);
        if let Some(message) = commit {
            self.zenops_shell(|sh| {
                cmd!(sh, "git add {path}").ignore_stdout().run().unwrap();
                cmd!(sh, "git commit -m {message}")
                    .ignore_stdout()
                    .run()
                    .unwrap();
            });
        }
    }

    pub fn append_zenops_file(
        &self,
        path: impl AsRef<SafeRelativePath>,
        data: impl AsRef<[u8]>,
        commit: Option<&str>,
    ) {
        let path = path.as_ref();
        self.append_file(paths::ZENOPS_DIR.safe_join(path), data);
        if let Some(message) = commit {
            self.zenops_shell(|sh| {
                cmd!(sh, "git add {path}").ignore_stdout().run().unwrap();
                cmd!(sh, "git commit -m {message}")
                    .ignore_stdout()
                    .run()
                    .unwrap();
            });
        }
    }

    fn zenops_shell(&self, f: impl FnOnce(&Shell)) {
        let _dir = self.sh.push_dir(paths::ZENOPS_DIR.as_str());
        f(&self.sh)
    }

    pub fn init_config(&self, config: &str) {
        self.zenops_shell(|sh| {
            cmd!(sh, "git init --initial-branch=main")
                .ignore_stdout()
                .run()
                .unwrap();
            cmd!(sh, "git config commit.gpgsign false").run().unwrap();
            cmd!(sh, "git config user.email zen@example.com")
                .run()
                .unwrap();
            cmd!(sh, "git config user.name Zen").run().unwrap();
        });
        self.write_zenops_file(srpath!("config.toml"), config, Some("initial commit"));
    }

    /// Like [`Self::init_config`], but also creates a bare-repo remote named
    /// `origin` under `<tmp>/remote.git` and pushes the initial commit to its
    /// `main` branch. Returns the bare repo's path so tests can inspect it.
    pub fn init_config_with_remote(&self, config: &str) -> PathBuf {
        let bare = self.root.path().join("remote.git");
        cmd!(self.sh, "git init --initial-branch=main --bare")
            .arg(&bare)
            .ignore_stdout()
            .run()
            .unwrap();
        self.init_config(config);
        self.zenops_shell(|sh| {
            cmd!(sh, "git remote add origin").arg(&bare).run().unwrap();
            cmd!(sh, "git push -u origin main")
                .ignore_stdout()
                .ignore_stderr()
                .run()
                .unwrap();
        });
        bare
    }

    /// Create a bare repo at `<tmp>/origin.git` seeded with the given files
    /// on `main`, without touching the test env's zenops dir. Returns the
    /// bare repo's path; tests can pass it as a `file:///...` URL to
    /// `Cmd::Init`.
    pub fn seed_bare_repo(&self, files: &[(&str, &str)]) -> PathBuf {
        let bare = self.root.path().join("origin.git");
        let seed = self.root.path().join("seed");
        cmd!(self.sh, "git init --initial-branch=main --bare")
            .arg(&bare)
            .ignore_stdout()
            .run()
            .unwrap();
        std::fs::create_dir(&seed).unwrap();
        let _dir = self.sh.push_dir(&seed);
        cmd!(self.sh, "git init --initial-branch=main")
            .ignore_stdout()
            .ignore_stderr()
            .run()
            .unwrap();
        cmd!(self.sh, "git config commit.gpgsign false")
            .run()
            .unwrap();
        cmd!(self.sh, "git config user.email zen@example.com")
            .run()
            .unwrap();
        cmd!(self.sh, "git config user.name Zen").run().unwrap();
        for (name, content) in files {
            std::fs::write(seed.join(name), content).unwrap();
            cmd!(self.sh, "git add").arg(name).run().unwrap();
        }
        cmd!(self.sh, "git commit -m seed")
            .ignore_stdout()
            .run()
            .unwrap();
        cmd!(self.sh, "git remote add origin")
            .arg(&bare)
            .run()
            .unwrap();
        cmd!(self.sh, "git push -u origin main")
            .ignore_stdout()
            .ignore_stderr()
            .run()
            .unwrap();
        bare
    }

    /// Clone the given bare repo into `<tmp>/sidecar`, add a file, commit,
    /// and push. Used to seed a new upstream commit that the zenops repo can
    /// then pull.
    pub fn seed_remote_commit(
        &self,
        bare: &Path,
        filename: &str,
        content: &str,
        message: &str,
    ) -> PathBuf {
        let sidecar = self.root.path().join("sidecar");
        cmd!(self.sh, "git clone")
            .arg(bare)
            .arg(&sidecar)
            .ignore_stdout()
            .ignore_stderr()
            .run()
            .unwrap();
        let _dir = self.sh.push_dir(&sidecar);
        cmd!(self.sh, "git config commit.gpgsign false")
            .run()
            .unwrap();
        cmd!(self.sh, "git config user.email zen@example.com")
            .run()
            .unwrap();
        cmd!(self.sh, "git config user.name Zen").run().unwrap();
        std::fs::write(sidecar.join(filename), content).unwrap();
        cmd!(self.sh, "git add").arg(filename).run().unwrap();
        cmd!(self.sh, "git commit -m {message}")
            .ignore_stdout()
            .run()
            .unwrap();
        cmd!(self.sh, "git push")
            .ignore_stdout()
            .ignore_stderr()
            .run()
            .unwrap();
        sidecar
    }

    /// Run `git <args>` in `dir` and return its stdout.
    pub fn git_out(&self, dir: &Path, args: &[&str]) -> String {
        let _dir = self.sh.push_dir(dir);
        cmd!(self.sh, "git").args(args).read().unwrap()
    }

    pub fn run(&self, cmd: &Cmd) -> Result<Output, Error> {
        // Always re-detect — `add_binary` between load() and run() may
        // have changed which managers are findable on PATH.
        let platform = self.fresh_platform();
        let mut output = Output::default();
        let host = zenops::HostInputs {
            platform: &platform,
            args: &self.default_args,
        };
        zenops::real_main(cmd, &host, &mut output)?;
        Ok(output)
    }

    /// Drive `zenops import` through the scripted-picker path. Bypasses
    /// the binary's TTY/--yes routing so a test can flatten the plan and
    /// pick rows deterministically without a real terminal.
    pub fn run_import_picked(
        &self,
        path: &Path,
        pkg: Option<&str>,
        source: Option<&str>,
        brew: &[String],
        script: Vec<zenops::picker::ScriptedStep>,
    ) -> Result<Output, Error> {
        let platform = self.fresh_platform();
        let mut output = Output::default();
        let mut picker = zenops::picker::ScriptedPicker::new(script);
        zenops::import::run_with_io(
            path,
            pkg,
            source,
            brew,
            false,
            false,
            &platform,
            &mut output,
            None,
            Some(&mut picker),
        )?;
        Ok(output)
    }

    /// Run `zenops pkg` and return only the `PkgEntry` events that came back.
    /// Convenience for the pkg listing tests, which don't care about
    /// status/git events. Takes `pkg_list::Options` so new flags don't keep
    /// growing this signature.
    pub fn run_pkg_list(&self, opts: pkg_list::Options) -> Result<Vec<PkgEntry>, Error> {
        let pkg_list::Options {
            pattern,
            all,
            all_hints,
            verbose,
        } = opts;
        let out = self.run(&Cmd::Pkg {
            pattern,
            all,
            all_hints,
            verbose,
        })?;
        Ok(out
            .entries
            .into_iter()
            .filter_map(|e| match e {
                Entry::Pkg(p) => Some(p),
                _ => None,
            })
            .collect())
    }

    pub fn create_symlink(
        &self,
        real_path: impl AsRef<SafeRelativePath>,
        symlink_path: impl AsRef<SafeRelativePath>,
    ) {
        self.ensure_dir_exists_for_file(symlink_path.as_ref());
        let real_path = self.resolve_path(real_path);
        let symlink_path = self.resolve_path(symlink_path);
        std::os::unix::fs::symlink(&real_path, &symlink_path).unwrap_or_else(|e| {
            panic!("Failed to create symlink from {real_path:?} to {symlink_path:?}: {e}")
        });
    }

    pub fn create_dangling_symlink(
        &self,
        real_path: impl AsRef<Path>,
        symlink_path: impl AsRef<SafeRelativePath>,
    ) {
        self.ensure_dir_exists_for_file(symlink_path.as_ref());
        let symlink_path = self.resolve_path(symlink_path);
        std::os::unix::fs::symlink(real_path.as_ref(), &symlink_path).unwrap_or_else(|e| {
            panic!(
                "Failed to create symlink from {:?} to {symlink_path:?}: {e}",
                real_path.as_ref()
            )
        });
    }

    /// Set the mode bits on `rel`. Returns a guard that restores the
    /// original mode on drop so `tempfile` cleanup can recurse into the
    /// directory at the end of the test.
    pub fn chmod(&self, rel: impl AsRef<SafeRelativePath>, mode: u32) -> PermGuard {
        use std::os::unix::fs::PermissionsExt;
        let path = self.resolve_path(rel);
        let original = std::fs::metadata(&path)
            .unwrap_or_else(|e| panic!("Failed to read metadata for {path:?}: {e}"))
            .permissions()
            .mode();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
            .unwrap_or_else(|e| panic!("Failed to chmod {path:?} to {mode:o}: {e}"));
        PermGuard { path, original }
    }
}

/// RAII guard that restores a path's original Unix mode on drop. Tests
/// that chmod managed paths use this so `tempfile`'s recursive cleanup
/// can still descend into them after the test body completes.
pub struct PermGuard {
    path: PathBuf,
    original: u32,
}

impl Drop for PermGuard {
    fn drop(&mut self) {
        use std::os::unix::fs::PermissionsExt;
        let _ =
            std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(self.original));
    }
}

#[derive(Debug, PartialEq)]
pub enum Entry {
    Status(Status),
    AppliedAction(AppliedAction),
    Pkg(PkgEntry),
    Doctor(DoctorCheck),
    Init(InitSummary),
    Bootstrap(BootstrapSummary),
    ImportPlan(ImportPlan),
    ImportApplied(ImportApplied),
}

#[derive(Default, Debug, PartialEq)]
pub struct Output {
    pub entries: Vec<Entry>,
}

impl zenops::output::Output for Output {
    fn push(&mut self, event: Event) -> Result<(), OutputError> {
        self.entries.push(match event {
            Event::Status(status) => Entry::Status(status),
            Event::AppliedAction(action) => Entry::AppliedAction(action),
            Event::PkgEntry(entry) => Entry::Pkg(entry),
            Event::DoctorCheck(check) => Entry::Doctor(check),
            Event::InitSummary(summary) => Entry::Init(summary),
            Event::BootstrapSummary(summary) => Entry::Bootstrap(summary),
            Event::ImportPlan(plan) => Entry::ImportPlan(plan),
            Event::ImportApplied(applied) => Entry::ImportApplied(applied),
        });
        Ok(())
    }
}