zenops 0.12.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
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! Crate-wide error type.
//!
//! [`Error`] is the unified failure mode for every fallible operation in the
//! `zenops` binary — config load, file writes, git invocations, prompt I/O,
//! init pre-flight, schema emission. Variants use `thiserror` and either own
//! their source (typed `#[source]`) or transparently re-export a foreign
//! error ([`OutputError`], [`zenops_safe_relative_path::error::Error`]).
//!
//! The [`PartialEq`] impl is for tests only: `std::io::Error` and
//! `xshell::Error` aren't naturally comparable, so the impl falls back to
//! comparing [`std::io::ErrorKind`] or [`Display`](std::fmt::Display) output
//! variant by variant.

use std::path::PathBuf;

use smol_str::SmolStr;

use crate::output::{OutputError, ResolvedConfigFilePath};

/// Crate-wide error. Each variant's user-facing string lives on its
/// `#[error(...)]` attribute (the `Display` impl); the doc comment here
/// adds the trigger context the message can't carry.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// I/O error opening `config.toml` (e.g. missing file, permission denied).
    #[error("Failed to open the database file {0:?}: {1}")]
    OpenDb(PathBuf, #[source] std::io::Error),
    /// `config.toml` parsed but failed TOML deserialization or schema validation.
    #[error("Failed to parse the database from file {0:?}: {1}")]
    ParseDb(PathBuf, #[source] toml::de::Error),
    /// A subprocess invoked through `xshell` failed (non-zero exit, signal,
    /// I/O error). The wrapped error carries the command and stderr.
    #[error("Failed to execute command")]
    Shell(#[from] xshell::Error),
    /// Writing a generated config file to disk failed.
    #[error("Failed to write config file {0}: {1}")]
    FailedToWriteConfig(ResolvedConfigFilePath, std::io::Error),
    /// Reading an existing managed file from disk failed (e.g. permission
    /// denied, or a directory occupies the path where a generated file should
    /// land).
    #[error("Failed to read existing config file {0}: {1}")]
    FailedToReadConfig(ResolvedConfigFilePath, #[source] std::io::Error),
    /// Stat-ing a managed path failed for a reason other than "not found"
    /// (e.g. permission denied on a parent). The wrapped path is whichever
    /// path the probe was attempted on.
    #[error("Failed to probe filesystem state at {0:?}: {1}")]
    SymlinkProbeFailed(PathBuf, #[source] std::io::Error),
    /// `symlink(2)` failed in [`crate::config_files`]'s `create_symlink`
    /// helper. Bundles both ends so the user sees the symlink they were
    /// attempting and the underlying I/O reason.
    #[error("Failed to create symlink {symlink} -> {real}: {source}")]
    CreateSymlinkFailed {
        /// The intended symlink target (the file in the zenops repo).
        real: ResolvedConfigFilePath,
        /// Where the symlink was being created.
        symlink: ResolvedConfigFilePath,
        /// Underlying `symlink(2)` failure.
        #[source]
        source: std::io::Error,
    },
    /// Apply pass: a managed symlink already points at the intended target,
    /// but that target doesn't exist in the zenops repo. The user must add
    /// the file before zenops can manage it.
    #[error("Symlink {symlink} -> {real}: {real} does not exist in the zenops repo")]
    SymlinkRealPathMissing {
        /// The intended symlink target (the file in the zenops repo).
        real: ResolvedConfigFilePath,
        /// Where the symlink lives.
        symlink: ResolvedConfigFilePath,
    },
    /// Apply pass refused to clobber a path that is neither a regular file,
    /// directory, nor symlink (FIFO, socket, device node, etc.) with a
    /// managed symlink. The user must remove the existing entry first.
    #[error(
        "Not creating symlink at {0}: a non-file, non-directory entry (FIFO, socket, etc.) already exists"
    )]
    RefusingToOverwriteOtherWithSymlink(ResolvedConfigFilePath),
    /// A `..`-traversal or other path-safety violation surfaced from
    /// [`zenops_safe_relative_path`].
    #[error(transparent)]
    SafeRelativePath(#[from] zenops_safe_relative_path::error::Error),
    /// Apply pass refused to clobber an existing regular file with a
    /// symlink. The user must remove the existing file first.
    #[error("Not creating symlink {symlink} -> {real}: a file already exists")]
    RefusingToOverwriteFileWithSymlink {
        /// The intended symlink target (the file in the zenops repo).
        real: ResolvedConfigFilePath,
        /// The path that already exists as a regular file.
        symlink: ResolvedConfigFilePath,
    },
    /// Apply pass refused to clobber an existing directory with a symlink.
    #[error("Not creating symlink {symlink} -> {real}: a directory already exists")]
    RefusingToOverwriteDirectoryWithSymlink {
        /// The intended symlink target.
        real: ResolvedConfigFilePath,
        /// The path that already exists as a directory.
        symlink: ResolvedConfigFilePath,
    },
    /// `mkdir -p` of a parent directory for a managed file failed.
    #[error("Failed to create directory {0:?}: {1}")]
    CreateDirectoryError(ResolvedConfigFilePath, std::io::Error),
    /// A pkg's template referenced an input that's not declared anywhere
    /// (no system input, no `[pkg.<name>.inputs]` entry).
    #[error(
        "Package {pkg} references undefined input {input}; mark the action optional or set [pkg.{pkg}.inputs].{input}"
    )]
    UnresolvedInput {
        /// The pkg whose template failed to resolve.
        pkg: SmolStr,
        /// The input name that wasn't found.
        input: SmolStr,
    },
    /// A pkg template contains a `${` with no matching `}`.
    #[error("Package {pkg} has an unterminated `${{` in a template")]
    TemplateUnterminated {
        /// The pkg whose template failed to parse.
        pkg: SmolStr,
    },
    /// `apply` was invoked without a TTY and without `--yes`/`--dry-run`,
    /// so there's no way to confirm prompts.
    #[error(
        "apply requires a terminal for prompts; pass --yes to apply all changes non-interactively, or --dry-run to preview"
    )]
    ApplyNeedsYesOrTty,
    /// `apply --yes` was invoked on a dirty zenops repo without
    /// `--allow-dirty`. The check exists so cron/CI surfaces divergence
    /// instead of silently applying uncommitted state.
    #[error(
        "zenops config repo at {0:?} has uncommitted changes. Commit them first, or re-run with --allow-dirty to apply anyway."
    )]
    DirtyRepoRequiresAllowDirty(PathBuf),
    /// I/O error reading a yes/no answer from stdin.
    #[error("Failed to read confirmation from stdin: {0}")]
    PromptRead(#[source] std::io::Error),
    /// User pressed Ctrl-C at an interactive prompt. Distinct from a
    /// closed stdin or Ctrl-D so callers can abort the whole run.
    #[error("Interrupted")]
    PromptInterrupted,
    /// An [`Output`](crate::output::Output) implementation failed to write
    /// (rendering or JSON serialization error).
    #[error(transparent)]
    Output(#[from] OutputError),
    /// `zenops init` target directory exists and is non-empty. The user
    /// must clear it (or use `zenops repo pull` if it's already a clone).
    #[error(
        "Cannot init: {0:?} already exists and is not empty. Remove it first, or use `zenops repo pull` if it's already a zenops repo."
    )]
    InitDirNotEmpty(PathBuf),
    /// `zenops init` (bootstrap form, no URL) found the target directory
    /// already exists. Bootstrap refuses to touch any existing path so it
    /// can never clobber a previous setup.
    #[error(
        "Cannot init: {0:?} already exists. Bootstrap refuses to touch an existing path; remove it first, or pass a URL to clone into it."
    )]
    InitDirExists(PathBuf),
    /// `zenops init` bootstrap target already contains a `.git` directory.
    /// Reported instead of [`Self::InitDirExists`] when the existing
    /// directory looks like a git repo.
    #[error(
        "Cannot init: {0:?} already contains a .git directory. Looks like a zenops repo already exists; remove it first or skip init."
    )]
    InitGitDirExists(PathBuf),
    /// `git init` itself failed during `zenops init` bootstrap.
    #[error("Failed to initialize git repo: {source}")]
    InitGitInitFailed {
        /// Underlying xshell failure.
        #[source]
        source: xshell::Error,
    },
    /// `zenops init` (bootstrap form, no URL) was invoked without a TTY.
    /// Prompts can't run reliably without one, so we refuse rather than
    /// silently accept defaults from a closed stdin.
    #[error(
        "init bootstrap requires a terminal for prompts; clone with a URL instead, or run from a TTY"
    )]
    InitNeedsTty,
    /// `zenops init` cloned successfully but the repo lacks a `config.toml`
    /// at its root, so it isn't a zenops config repo. The clone is left in
    /// place for inspection.
    #[error(
        "Cloned repo at {0:?} has no config.toml at its root. Is this a zenops config repo? The clone was left in place so you can inspect it."
    )]
    InitNoConfigToml(PathBuf),
    /// `git clone` itself failed during `zenops init` (auth, network,
    /// invalid URL).
    #[error("Failed to clone {url}: {source}")]
    InitCloneFailed {
        /// The URL passed to `git clone`.
        url: String,
        /// The underlying xshell failure.
        #[source]
        source: xshell::Error,
    },
    /// I/O error during `zenops init` pre-flight (e.g. probing the target
    /// directory, removing it before clone).
    #[error("Init I/O error at {0:?}: {1}")]
    InitIo(PathBuf, #[source] std::io::Error),
    /// `curl` isn't on `PATH` and is needed to fetch a user's GitHub keys.
    #[error(
        "curl is required to fetch GitHub SSH keys; install curl or switch the entry to type = \"manual\""
    )]
    CurlNotFound,
    /// `curl https://api.github.com/users/<u>/ssh_signing_keys` failed.
    #[error("Failed to fetch SSH keys for GitHub user {username}: {source}")]
    GithubKeyFetchFailed {
        /// GitHub username queried.
        username: SmolStr,
        /// Underlying xshell/curl failure.
        #[source]
        source: xshell::Error,
    },
    /// GitHub returned a body that didn't match the expected SSH-signing-key JSON shape.
    #[error("Failed to parse SSH signing keys response for GitHub user {username}: {source}")]
    GithubKeyParseFailed {
        /// GitHub username queried.
        username: SmolStr,
        /// Underlying serde_json failure.
        #[source]
        source: serde_json::Error,
    },
    /// `serde_json` failed to serialise the bundled JSON Schema.
    #[error("Failed to emit schema: {0}")]
    SchemaEmit(#[source] serde_json::Error),
    /// I/O error writing the serialised schema to stdout.
    #[error("Failed to write schema to stdout: {0}")]
    SchemaWrite(#[source] std::io::Error),
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::OpenDb(l0, l1), Self::OpenDb(r0, r1)) => l0 == r0 && l1.kind() == r1.kind(),
            (Self::ParseDb(l0, l1), Self::ParseDb(r0, r1)) => l0 == r0 && l1 == r1,
            (Self::Shell(l0), Self::Shell(r0)) => l0.to_string() == r0.to_string(),
            (Self::FailedToWriteConfig(l0, l1), Self::FailedToWriteConfig(r0, r1)) => {
                l0 == r0 && l1.kind() == r1.kind()
            }
            (Self::FailedToReadConfig(l0, l1), Self::FailedToReadConfig(r0, r1)) => {
                l0 == r0 && l1.kind() == r1.kind()
            }
            (Self::SymlinkProbeFailed(l0, l1), Self::SymlinkProbeFailed(r0, r1)) => {
                l0 == r0 && l1.kind() == r1.kind()
            }
            (
                Self::CreateSymlinkFailed {
                    real: l_real,
                    symlink: l_symlink,
                    source: l_src,
                },
                Self::CreateSymlinkFailed {
                    real: r_real,
                    symlink: r_symlink,
                    source: r_src,
                },
            ) => l_real == r_real && l_symlink == r_symlink && l_src.kind() == r_src.kind(),
            (
                Self::SymlinkRealPathMissing {
                    real: l_real,
                    symlink: l_symlink,
                },
                Self::SymlinkRealPathMissing {
                    real: r_real,
                    symlink: r_symlink,
                },
            ) => l_real == r_real && l_symlink == r_symlink,
            (
                Self::RefusingToOverwriteOtherWithSymlink(l0),
                Self::RefusingToOverwriteOtherWithSymlink(r0),
            ) => l0 == r0,
            (Self::SafeRelativePath(l0), Self::SafeRelativePath(r0)) => l0 == r0,
            (
                Self::RefusingToOverwriteFileWithSymlink {
                    real: l_real,
                    symlink: l_symlink,
                },
                Self::RefusingToOverwriteFileWithSymlink {
                    real: r_real,
                    symlink: r_symlink,
                },
            ) => l_real == r_real && l_symlink == r_symlink,
            (
                Self::RefusingToOverwriteDirectoryWithSymlink {
                    real: l_real,
                    symlink: l_symlink,
                },
                Self::RefusingToOverwriteDirectoryWithSymlink {
                    real: r_real,
                    symlink: r_symlink,
                },
            ) => l_real == r_real && l_symlink == r_symlink,
            (Self::CreateDirectoryError(l0, l1), Self::CreateDirectoryError(r0, r1)) => {
                l0 == r0 && l1.kind() == r1.kind()
            }
            (
                Self::UnresolvedInput {
                    pkg: l_pkg,
                    input: l_input,
                },
                Self::UnresolvedInput {
                    pkg: r_pkg,
                    input: r_input,
                },
            ) => l_pkg == r_pkg && l_input == r_input,
            (Self::TemplateUnterminated { pkg: l }, Self::TemplateUnterminated { pkg: r }) => {
                l == r
            }
            (Self::ApplyNeedsYesOrTty, Self::ApplyNeedsYesOrTty) => true,
            (Self::DirtyRepoRequiresAllowDirty(l0), Self::DirtyRepoRequiresAllowDirty(r0)) => {
                l0 == r0
            }
            (Self::PromptRead(l0), Self::PromptRead(r0)) => l0.kind() == r0.kind(),
            (Self::PromptInterrupted, Self::PromptInterrupted) => true,
            (Self::Output(l0), Self::Output(r0)) => l0.to_string() == r0.to_string(),
            (Self::InitDirNotEmpty(l0), Self::InitDirNotEmpty(r0)) => l0 == r0,
            (Self::InitDirExists(l0), Self::InitDirExists(r0)) => l0 == r0,
            (Self::InitGitDirExists(l0), Self::InitGitDirExists(r0)) => l0 == r0,
            (
                Self::InitGitInitFailed { source: l_src },
                Self::InitGitInitFailed { source: r_src },
            ) => l_src.to_string() == r_src.to_string(),
            (Self::InitNeedsTty, Self::InitNeedsTty) => true,
            (Self::InitNoConfigToml(l0), Self::InitNoConfigToml(r0)) => l0 == r0,
            (
                Self::InitCloneFailed {
                    url: l_url,
                    source: l_src,
                },
                Self::InitCloneFailed {
                    url: r_url,
                    source: r_src,
                },
            ) => l_url == r_url && l_src.to_string() == r_src.to_string(),
            (Self::InitIo(l0, l1), Self::InitIo(r0, r1)) => l0 == r0 && l1.kind() == r1.kind(),
            (Self::CurlNotFound, Self::CurlNotFound) => true,
            (
                Self::GithubKeyFetchFailed {
                    username: l_user,
                    source: l_src,
                },
                Self::GithubKeyFetchFailed {
                    username: r_user,
                    source: r_src,
                },
            ) => l_user == r_user && l_src.to_string() == r_src.to_string(),
            (
                Self::GithubKeyParseFailed {
                    username: l_user,
                    source: l_src,
                },
                Self::GithubKeyParseFailed {
                    username: r_user,
                    source: r_src,
                },
            ) => l_user == r_user && l_src.to_string() == r_src.to_string(),
            (Self::SchemaEmit(l), Self::SchemaEmit(r)) => l.to_string() == r.to_string(),
            (Self::SchemaWrite(l), Self::SchemaWrite(r)) => l.kind() == r.kind(),
            _ => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io;
    use std::path::{Path, PathBuf};
    use std::sync::Arc;

    use similar_asserts::assert_eq;
    use xshell::{Shell, cmd};
    use zenops_safe_relative_path::srpath;

    use crate::config_files::ConfigFilePath;
    use crate::output::ResolvedConfigFilePath;

    use super::*;

    fn rcfp(rel: &'static str) -> ResolvedConfigFilePath {
        let path = ConfigFilePath::Home(Arc::from(
            zenops_safe_relative_path::SafeRelativePath::from_relative_path(rel).unwrap(),
        ));
        let full = Arc::from(Path::new("/tmp").join(rel).as_path());
        ResolvedConfigFilePath { path, full }
    }

    fn io(kind: io::ErrorKind) -> io::Error {
        io::Error::from(kind)
    }

    fn xshell_err() -> xshell::Error {
        // Re-running the same failing command produces equal `to_string()`,
        // which is what `PartialEq` compares for `Self::Shell(_)`.
        let sh = Shell::new().unwrap();
        cmd!(sh, "false").quiet().run().unwrap_err()
    }

    fn json_err() -> serde_json::Error {
        serde_json::from_str::<serde_json::Value>("{").unwrap_err()
    }

    #[test]
    fn open_db_eq_compares_path_and_io_kind() {
        let a = Error::OpenDb(PathBuf::from("/x"), io(io::ErrorKind::NotFound));
        let b = Error::OpenDb(PathBuf::from("/x"), io(io::ErrorKind::NotFound));
        let c = Error::OpenDb(PathBuf::from("/y"), io(io::ErrorKind::NotFound));
        let d = Error::OpenDb(PathBuf::from("/x"), io(io::ErrorKind::PermissionDenied));
        assert_eq!(a, b);
        assert_ne!(a, c);
        assert_ne!(a, d);
    }

    #[test]
    fn parse_db_eq_compares_path_and_inner_error() {
        let toml_err = toml::from_str::<toml::Value>("not = valid = toml").unwrap_err();
        let toml_err2 = toml::from_str::<toml::Value>("not = valid = toml").unwrap_err();
        let a = Error::ParseDb(PathBuf::from("/x"), toml_err);
        let b = Error::ParseDb(PathBuf::from("/x"), toml_err2);
        assert_eq!(a, b);
    }

    #[test]
    fn shell_eq_compares_display_string() {
        let a = Error::Shell(xshell_err());
        let b = Error::Shell(xshell_err());
        assert_eq!(a, b);
    }

    #[test]
    fn failed_to_write_config_eq_and_ne() {
        let a = Error::FailedToWriteConfig(rcfp("a"), io(io::ErrorKind::PermissionDenied));
        let b = Error::FailedToWriteConfig(rcfp("a"), io(io::ErrorKind::PermissionDenied));
        let c = Error::FailedToWriteConfig(rcfp("b"), io(io::ErrorKind::PermissionDenied));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn failed_to_read_config_eq_and_ne() {
        let a = Error::FailedToReadConfig(rcfp("a"), io(io::ErrorKind::PermissionDenied));
        let b = Error::FailedToReadConfig(rcfp("a"), io(io::ErrorKind::PermissionDenied));
        let c = Error::FailedToReadConfig(rcfp("a"), io(io::ErrorKind::NotFound));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn symlink_probe_failed_eq_and_ne() {
        let a = Error::SymlinkProbeFailed(PathBuf::from("/x"), io(io::ErrorKind::Other));
        let b = Error::SymlinkProbeFailed(PathBuf::from("/x"), io(io::ErrorKind::Other));
        let c = Error::SymlinkProbeFailed(PathBuf::from("/y"), io(io::ErrorKind::Other));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn create_symlink_failed_eq_and_ne() {
        let mk = |real, symlink, kind| Error::CreateSymlinkFailed {
            real: rcfp(real),
            symlink: rcfp(symlink),
            source: io(kind),
        };
        assert_eq!(
            mk("r", "s", io::ErrorKind::AlreadyExists),
            mk("r", "s", io::ErrorKind::AlreadyExists)
        );
        assert_ne!(
            mk("r", "s", io::ErrorKind::AlreadyExists),
            mk("other", "s", io::ErrorKind::AlreadyExists)
        );
        assert_ne!(
            mk("r", "s", io::ErrorKind::AlreadyExists),
            mk("r", "s", io::ErrorKind::NotFound)
        );
    }

    #[test]
    fn symlink_real_path_missing_eq_and_ne() {
        let a = Error::SymlinkRealPathMissing {
            real: rcfp("r"),
            symlink: rcfp("s"),
        };
        let b = Error::SymlinkRealPathMissing {
            real: rcfp("r"),
            symlink: rcfp("s"),
        };
        let c = Error::SymlinkRealPathMissing {
            real: rcfp("r"),
            symlink: rcfp("other"),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn refusing_to_overwrite_other_eq_and_ne() {
        let a = Error::RefusingToOverwriteOtherWithSymlink(rcfp("a"));
        let b = Error::RefusingToOverwriteOtherWithSymlink(rcfp("a"));
        let c = Error::RefusingToOverwriteOtherWithSymlink(rcfp("b"));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn safe_relative_path_eq_delegates_to_inner() {
        let traversal_err =
            zenops_safe_relative_path::SafeRelativePath::from_relative_path("..").unwrap_err();
        let traversal_err2 =
            zenops_safe_relative_path::SafeRelativePath::from_relative_path("..").unwrap_err();
        let a = Error::SafeRelativePath(traversal_err);
        let b = Error::SafeRelativePath(traversal_err2);
        let c = Error::SafeRelativePath(
            zenops_safe_relative_path::error::Error::NotASinglePathComponent("a/b".to_string()),
        );
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn refusing_to_overwrite_file_eq_and_ne() {
        let a = Error::RefusingToOverwriteFileWithSymlink {
            real: rcfp("r"),
            symlink: rcfp("s"),
        };
        let b = Error::RefusingToOverwriteFileWithSymlink {
            real: rcfp("r"),
            symlink: rcfp("s"),
        };
        let c = Error::RefusingToOverwriteFileWithSymlink {
            real: rcfp("r"),
            symlink: rcfp("t"),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn refusing_to_overwrite_directory_eq_and_ne() {
        let a = Error::RefusingToOverwriteDirectoryWithSymlink {
            real: rcfp("r"),
            symlink: rcfp("s"),
        };
        let b = Error::RefusingToOverwriteDirectoryWithSymlink {
            real: rcfp("r"),
            symlink: rcfp("s"),
        };
        let c = Error::RefusingToOverwriteDirectoryWithSymlink {
            real: rcfp("other"),
            symlink: rcfp("s"),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn create_directory_error_eq_and_ne() {
        let a = Error::CreateDirectoryError(rcfp("a"), io(io::ErrorKind::PermissionDenied));
        let b = Error::CreateDirectoryError(rcfp("a"), io(io::ErrorKind::PermissionDenied));
        let c = Error::CreateDirectoryError(rcfp("a"), io(io::ErrorKind::NotFound));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn unresolved_input_eq_and_ne() {
        let a = Error::UnresolvedInput {
            pkg: SmolStr::new_static("p"),
            input: SmolStr::new_static("i"),
        };
        let b = Error::UnresolvedInput {
            pkg: SmolStr::new_static("p"),
            input: SmolStr::new_static("i"),
        };
        let c = Error::UnresolvedInput {
            pkg: SmolStr::new_static("p"),
            input: SmolStr::new_static("other"),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn template_unterminated_eq_and_ne() {
        let a = Error::TemplateUnterminated {
            pkg: SmolStr::new_static("p"),
        };
        let b = Error::TemplateUnterminated {
            pkg: SmolStr::new_static("p"),
        };
        let c = Error::TemplateUnterminated {
            pkg: SmolStr::new_static("q"),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn unit_variants_compare_equal_to_themselves() {
        assert_eq!(Error::ApplyNeedsYesOrTty, Error::ApplyNeedsYesOrTty);
        assert_eq!(Error::PromptInterrupted, Error::PromptInterrupted);
        assert_eq!(Error::InitNeedsTty, Error::InitNeedsTty);
        assert_eq!(Error::CurlNotFound, Error::CurlNotFound);
    }

    #[test]
    fn dirty_repo_requires_allow_dirty_eq_and_ne() {
        let a = Error::DirtyRepoRequiresAllowDirty(PathBuf::from("/x"));
        let b = Error::DirtyRepoRequiresAllowDirty(PathBuf::from("/x"));
        let c = Error::DirtyRepoRequiresAllowDirty(PathBuf::from("/y"));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn prompt_read_eq_compares_io_kind() {
        let a = Error::PromptRead(io(io::ErrorKind::UnexpectedEof));
        let b = Error::PromptRead(io(io::ErrorKind::UnexpectedEof));
        let c = Error::PromptRead(io(io::ErrorKind::Other));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn output_eq_compares_display_string() {
        let a = Error::Output(OutputError::Io(io(io::ErrorKind::BrokenPipe)));
        let b = Error::Output(OutputError::Io(io(io::ErrorKind::BrokenPipe)));
        assert_eq!(a, b);
    }

    #[test]
    fn init_dir_variants_eq_and_ne() {
        assert_eq!(
            Error::InitDirNotEmpty(PathBuf::from("/a")),
            Error::InitDirNotEmpty(PathBuf::from("/a"))
        );
        assert_ne!(
            Error::InitDirNotEmpty(PathBuf::from("/a")),
            Error::InitDirNotEmpty(PathBuf::from("/b"))
        );
        assert_eq!(
            Error::InitDirExists(PathBuf::from("/a")),
            Error::InitDirExists(PathBuf::from("/a"))
        );
        assert_ne!(
            Error::InitDirExists(PathBuf::from("/a")),
            Error::InitDirExists(PathBuf::from("/b"))
        );
        assert_eq!(
            Error::InitGitDirExists(PathBuf::from("/a")),
            Error::InitGitDirExists(PathBuf::from("/a"))
        );
        assert_eq!(
            Error::InitNoConfigToml(PathBuf::from("/a")),
            Error::InitNoConfigToml(PathBuf::from("/a"))
        );
    }

    #[test]
    fn init_git_init_failed_eq_compares_display_string() {
        let a = Error::InitGitInitFailed {
            source: xshell_err(),
        };
        let b = Error::InitGitInitFailed {
            source: xshell_err(),
        };
        assert_eq!(a, b);
    }

    #[test]
    fn init_clone_failed_eq_compares_url_and_display() {
        let a = Error::InitCloneFailed {
            url: "https://example/x".to_string(),
            source: xshell_err(),
        };
        let b = Error::InitCloneFailed {
            url: "https://example/x".to_string(),
            source: xshell_err(),
        };
        let c = Error::InitCloneFailed {
            url: "https://example/y".to_string(),
            source: xshell_err(),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn init_io_eq_and_ne() {
        let a = Error::InitIo(PathBuf::from("/x"), io(io::ErrorKind::Other));
        let b = Error::InitIo(PathBuf::from("/x"), io(io::ErrorKind::Other));
        let c = Error::InitIo(PathBuf::from("/x"), io(io::ErrorKind::NotFound));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn github_key_fetch_failed_eq_and_ne() {
        let a = Error::GithubKeyFetchFailed {
            username: SmolStr::new_static("u"),
            source: xshell_err(),
        };
        let b = Error::GithubKeyFetchFailed {
            username: SmolStr::new_static("u"),
            source: xshell_err(),
        };
        let c = Error::GithubKeyFetchFailed {
            username: SmolStr::new_static("v"),
            source: xshell_err(),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn github_key_parse_failed_eq_and_ne() {
        let a = Error::GithubKeyParseFailed {
            username: SmolStr::new_static("u"),
            source: json_err(),
        };
        let b = Error::GithubKeyParseFailed {
            username: SmolStr::new_static("u"),
            source: json_err(),
        };
        let c = Error::GithubKeyParseFailed {
            username: SmolStr::new_static("v"),
            source: json_err(),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn schema_emit_eq_compares_display_string() {
        let a = Error::SchemaEmit(json_err());
        let b = Error::SchemaEmit(json_err());
        assert_eq!(a, b);
    }

    #[test]
    fn schema_write_eq_compares_io_kind() {
        let a = Error::SchemaWrite(io(io::ErrorKind::BrokenPipe));
        let b = Error::SchemaWrite(io(io::ErrorKind::BrokenPipe));
        let c = Error::SchemaWrite(io(io::ErrorKind::Other));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn cross_variant_compare_returns_false() {
        assert_ne!(Error::ApplyNeedsYesOrTty, Error::PromptInterrupted);
        assert_ne!(
            Error::CurlNotFound,
            Error::OpenDb(PathBuf::from("/x"), io(io::ErrorKind::NotFound))
        );
        let _ = srpath!("dummy"); // keep srpath import in use
    }

    #[test]
    fn from_xshell_error_wraps_in_shell_variant() {
        let e: Error = xshell_err().into();
        assert!(matches!(e, Error::Shell(_)));
    }

    #[test]
    fn from_safe_relative_path_error_wraps() {
        let inner = zenops_safe_relative_path::error::Error::NotASinglePathComponent("a/b".into());
        let e: Error = inner.into();
        assert!(matches!(e, Error::SafeRelativePath(_)));
    }
}