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
//! Library root for the `zenops` binary.
//!
//! This page is the Rust API surface. For user-facing docs — config file
//! reference, CLI reference, and guide — see <https://zenops.cc> (also
//! served offline by `zenops docs --open`).
//!
//! Exposes the clap [`Cmd`] subcommand enum, the global [`Args`], the
//! [`ColorChoice`] resolver, and the [`real_main`] dispatcher that routes a
//! parsed command into the right module.
//!
//! `Init`, `Doctor`, and `Schema` are dispatched *before* `Config::load`
//! because they must work without — or independently of — a usable
//! `~/.config/zenops/config.toml`. Every other command goes through
//! `Config::load` first.
//!
//! See [`crate::output`] for the structured-event channel that all commands
//! emit through; the `zenops` binary entrypoint wires up `Cli` and picks a
//! renderer.

#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links, rustdoc::private_intra_doc_links)]

mod ansi;
mod config;
pub mod config_files;
pub mod docs;
mod doctor;
pub mod error;
pub mod git;
pub mod import;
pub mod init;
pub mod line_prompter;
pub mod output;
pub mod picker;
pub mod pkg_list;
pub mod platform;
pub mod prompt;
pub mod schema;
pub mod utils;

use std::io::IsTerminal;

use clap::Subcommand;
use xshell::Shell;

use crate::{
    config::Config,
    config_files::ConfigFiles,
    error::Error,
    git::{Git, GitCmd},
    output::Output,
    platform::Platform,
    prompt::{DryRunPrompter, PreApplyDecision, Prompter, TerminalPrompter, YesPrompter},
};

/// The host-environment inputs every command handler needs: the
/// detected [`Platform`] (filesystem roots, binary search path,
/// identity, capabilities) and the parsed CLI args. Constructed once at
/// startup in `main.rs` (or in a `TestEnv` for integration tests) and
/// threaded by reference into [`real_main`] and every subcommand entry
/// point.
///
/// `output` is intentionally NOT a member — it's a sink, not an input.
pub struct HostInputs<'a> {
    /// The host as zenops sees it.
    pub platform: &'a Platform,
    /// Parsed CLI arguments (color choice, terminal hints).
    pub args: &'a Args,
}

/// User-facing color policy for the renderer and prompter, parsed from
/// `--color`. Resolve to a concrete on/off via [`ColorChoice::enabled`];
/// `Auto` honours `NO_COLOR` and the target stream's TTY-ness.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
#[clap(rename_all = "lower")]
pub enum ColorChoice {
    /// Color when the target stream is a TTY and `NO_COLOR` is unset.
    #[default]
    Auto,
    /// Force color regardless of TTY or `NO_COLOR`.
    Always,
    /// Never emit ANSI escapes.
    Never,
}

impl ColorChoice {
    /// Resolve to a concrete on/off decision. Pass `stream_is_terminal`
    /// for the stream colors will actually be emitted to. Everything
    /// `Output`-driven (the renderer and the prompter) writes to stdout;
    /// only `log::*!` and the top-level fatal-error `eprintln!` go to
    /// stderr, so callers almost always pass `stdout().is_terminal()`.
    pub fn enabled(self, stream_is_terminal: bool) -> bool {
        match self {
            Self::Always => true,
            Self::Never => false,
            Self::Auto => std::env::var_os("NO_COLOR").is_none() && stream_is_terminal,
        }
    }
}

/// Globals shared across every subcommand. Lives in its own struct so
/// subcommands can borrow it without redeclaring the flag.
#[derive(clap::Args, Debug)]
pub struct Args {
    /// When to colorize output
    #[clap(long, global = true, value_enum, default_value_t = ColorChoice::Auto)]
    pub color: ColorChoice,
    /// Whether stdin is attached to a TTY. Captured once in `main` and
    /// threaded through so subcommands don't reach back to global process
    /// state — tests construct `Args` with `stdin_is_terminal: false` and
    /// the bootstrap / interactive-apply paths see a non-TTY regardless of
    /// how `cargo test` was launched.
    #[clap(skip)]
    pub stdin_is_terminal: bool,
}

/// Top-level subcommand. The variants map 1:1 to user-visible commands;
/// each is dispatched by [`real_main`] (or, for `Completions`, by `main`
/// before `real_main` is reached).
#[derive(Subcommand, Debug)]
pub enum Cmd {
    /// Apply your config to this machine.
    ///
    /// Walks every change zenops would make — new files, symlink updates,
    /// package shell init — and prompts before each one. Pass `--yes` to
    /// apply everything without prompting (useful for automation), or
    /// `--dry-run` to see the prompts without applying.
    ///
    /// Refuses to run on a dirty zenops repo by default; pass
    /// `--allow-dirty` if you really want to apply uncommitted state.
    Apply {
        /// Pull the latest version of the config using git pull --rebase in the zenops config directory
        #[clap(long, short)]
        pull_config: bool,
        /// Apply every change without prompting.
        #[clap(long, short = 'y', conflicts_with = "dry_run")]
        yes: bool,
        /// Show each prompt with its diff, but apply nothing.
        #[clap(long, short = 'n')]
        dry_run: bool,
        /// Proceed even when the zenops config repo has uncommitted changes.
        /// Required alongside `--yes` when the repo is dirty; without it,
        /// `--yes` on a dirty repo aborts so automation surfaces divergence
        /// instead of silently applying uncommitted state.
        #[clap(long)]
        allow_dirty: bool,
    },
    /// Show what `zenops apply` would do, without doing it.
    /// Read-only and safe to run from anywhere.
    Status {
        /// Show a diff of what would change
        #[clap(long, short = 'd')]
        diff: bool,
        /// Also list items that already match the desired state
        #[clap(long, short = 'a')]
        all: bool,
    },
    /// List the packages in your config and whether each one is installed.
    ///
    /// Pass substring filters to narrow the list — `zenops pkg git curl`
    /// shows entries matching either name. Pass `--verbose` to see which
    /// detect rule matched, or `--all-hints` to see install commands for
    /// every supported package manager, not just yours.
    Pkg {
        /// Only list packages whose name or key contains one of these
        /// substrings (case-insensitive). Multiple patterns are ORed —
        /// `zenops pkg git curl` shows both.
        #[clap(value_name = "PATTERN")]
        pattern: Vec<String>,
        /// Include packages with `enable = "disabled"`
        #[clap(long)]
        all: bool,
        /// Show every install hint, not just the one for the detected package manager
        #[clap(long)]
        all_hints: bool,
        /// Show diagnostic details (the detect strategy that matched)
        #[clap(long, short)]
        verbose: bool,
    },
    /// Run git inside the zenops config repo.
    ///
    /// Lets you `commit`, `pull`, `push`, etc. without `cd`-ing into
    /// `~/.config/zenops`. Most operations are pass-throughs to git; a
    /// few add zenops-aware framing.
    Repo {
        /// Which git operation to dispatch in the config repo.
        #[command(subcommand)]
        command: GitCmd,
    },
    /// Set up `~/.config/zenops`.
    ///
    /// With a git URL, clones an existing zenops config repo. Without
    /// one, prompts for your shell, name, and email and writes a
    /// starter `config.toml` so you have somewhere to grow your config
    /// from.
    ///
    /// Pass `--apply` after cloning to immediately bring this machine
    /// into agreement with the cloned config. The bootstrap form (no
    /// URL) refuses to run if `~/.config/zenops` already exists; the
    /// clone form is happy to clone into an empty target.
    Init {
        /// Git URL to clone (SSH or HTTPS). Passed verbatim to `git clone`.
        /// Omit to bootstrap a fresh repo at `~/.config/zenops` instead of
        /// cloning.
        url: Option<String>,
        /// Check out this branch or tag after cloning (default: remote's HEAD).
        /// Only valid with a URL.
        #[clap(long, short, requires = "url")]
        branch: Option<String>,
        /// After cloning, run `zenops apply`.
        #[clap(long)]
        apply: bool,
        /// With `--apply`, apply every change without prompting (equivalent
        /// to `zenops apply --yes`). Only meaningful together with `--apply`.
        #[clap(long, short = 'y', requires = "apply")]
        yes: bool,
    },
    /// Take an existing dotfile directory into your zenops config.
    ///
    /// Copies the files into `~/.config/zenops/configs/<key>/`, replaces
    /// the originals with symlinks back to the repo, and appends a
    /// matching `[[pkg.<key>.configs]]` block to your `config.toml`.
    ///
    /// Re-running `import` on a directory you've already imported
    /// reconciles: new files get added to the entry, and files that
    /// are gone from your home get dropped from the repo too.
    Import {
        /// Path to take over. Absolute, cwd-relative, or shell-expanded
        /// (e.g. `~/.config/foo`). Must canonicalize to either
        /// `~/.config/<x>` or `~/.<x>`.
        #[clap(value_name = "PATH")]
        path: std::path::PathBuf,
        /// Override the derived pkg key. Defaults to `<x>` (with the
        /// leading dot stripped for `~/.<x>` shapes).
        #[clap(long)]
        pkg: Option<String>,
        /// Override the in-repo destination, relative to `~/.config/zenops`.
        /// Defaults to `configs/<pkg-key>`.
        #[clap(long)]
        source: Option<String>,
        /// Brew package(s) to record under `install_hint.brew.packages`.
        /// Repeatable. Required for new pkgs unless `--no-install-hint`.
        #[clap(long, value_name = "PKG")]
        brew: Vec<String>,
        /// For new pkgs, write `install_hint.brew.packages = []` instead
        /// of prompting for a brew package.
        #[clap(long, conflicts_with = "brew")]
        no_install_hint: bool,
        /// Accept every prompt with its default; required to run without
        /// a TTY when prompts would otherwise be needed.
        #[clap(long, short = 'y', conflicts_with = "dry_run")]
        yes: bool,
        /// Show the planned import without writing anything.
        #[clap(long, short = 'n')]
        dry_run: bool,
    },
    /// Diagnose the local environment.
    ///
    /// Walks config dir, git, shell, package manager, and per-package
    /// health, and reports what's set up and what isn't. Read-only and
    /// forgiving — keeps running even if `config.toml` is missing or
    /// invalid, so it's useful exactly when things have gone wrong.
    Doctor,
    /// Print zenops's JSON Schema bundle to stdout.
    ///
    /// Covers every structured surface zenops exposes: the
    /// `config.toml` input and the event types emitted in `-o json`
    /// mode. Useful for tooling that wants to validate or generate
    /// either side. The schema shape is versioned to the zenops crate
    /// version embedded in the bundle.
    Schema,
    /// Print a shell completion script for zenops to stdout.
    ///
    /// The built-in `zenops` package wires this in automatically, so
    /// you usually don't need to run it by hand.
    Completions {
        /// Shell to generate completions for
        shell: clap_complete::Shell,
    },
    /// Serve the embedded documentation site over HTTP on localhost.
    ///
    /// Bundles the configuration reference (driven by the same schema
    /// as `zenops schema`), the CLI reference, and the prose chapters.
    /// Works offline — every asset is embedded in the binary.
    Docs {
        /// Port to bind. Defaults to 0 (random ephemeral port); the bound
        /// URL is printed on startup.
        #[clap(long, short, default_value_t = 0)]
        port: u16,
        /// Open the served URL in the default browser after binding.
        #[clap(long)]
        open: bool,
    },
    /// Emit a Markdown CLI reference to stdout. Hidden because it's a
    /// build-time tool: `just docs-build` calls it to populate the docs
    /// site, not something users invoke by hand.
    #[clap(hide = true)]
    CliMarkdown,
}

/// Shared prelude for the config-loading subcommands (Apply/Status/Pkg):
/// open a shared [`Shell`] and parse `~/.config/zenops/config.toml`. `Init`,
/// `Doctor`, and `Schema` skip this because they're expected to work on a
/// fresh or broken machine.
struct CommandContext<'p> {
    sh: Shell,
    config: Config<'p>,
}

impl<'p> CommandContext<'p> {
    fn load(host: &HostInputs<'p>, pull_config: bool) -> Result<Self, Error> {
        let sh = Shell::new()?;
        let config = Config::load(host.platform, &sh, pull_config)?;
        Ok(Self { sh, config })
    }
}

fn build_prompter(
    yes: bool,
    dry_run: bool,
    color: bool,
    stdin_is_terminal: bool,
) -> Result<Box<dyn Prompter>, Error> {
    if dry_run {
        Ok(Box::new(DryRunPrompter::new(color)))
    } else if yes {
        Ok(Box::new(YesPrompter))
    } else if stdin_is_terminal {
        Ok(Box::new(TerminalPrompter::new(color)?))
    } else {
        Err(Error::ApplyNeedsYesOrTty)
    }
}

/// Dispatch a parsed [`Cmd`] to its module. `Init`, `Doctor`, `Schema`,
/// and `Docs` are handled before `Config::load` so they remain usable on
/// a fresh or broken machine; everything else loads the config first and
/// then routes through `Config` / [`ConfigFiles`].
///
/// `Completions` and `CliMarkdown` are no-ops here — `main` handles them
/// before calling in, because they need the top-level `Cli` for clap's
/// `CommandFactory`.
pub fn real_main(
    command: &Cmd,
    host: &HostInputs<'_>,
    output: &mut dyn Output,
) -> Result<(), Error> {
    match command {
        // Handled by main.rs where the top-level `Cli` is in scope;
        // real_main must not touch config because completions run at every
        // interactive shell startup.
        Cmd::Completions { .. } => Ok(()),
        // Same reason: needs the top-level `Cli` to drive clap-markdown.
        Cmd::CliMarkdown => Ok(()),
        Cmd::Docs { port, open } => docs::run(*port, *open),
        Cmd::Init {
            url,
            branch,
            apply,
            yes,
        } => init::run(
            url.as_deref(),
            branch.as_deref(),
            *apply,
            *yes,
            host,
            output,
        ),
        Cmd::Import {
            path,
            pkg,
            source,
            brew,
            no_install_hint,
            yes,
            dry_run,
        } => import::run(
            path,
            pkg.as_deref(),
            source.as_deref(),
            brew,
            *no_install_hint,
            *yes,
            *dry_run,
            host,
            output,
        ),
        // Doctor must survive a missing or broken config.toml — it's the
        // command the user runs when things are wrong, so it doesn't go
        // through `Config::load` here.
        Cmd::Doctor => {
            let sh = Shell::new()?;
            doctor::run(host, &sh, output)
        }
        Cmd::Schema => schema::run(&mut std::io::stdout().lock()),
        Cmd::Apply {
            pull_config,
            yes,
            dry_run,
            allow_dirty,
        } => {
            let ctx = CommandContext::load(host, *pull_config)?;
            let mut config_files = ConfigFiles::new(host.platform);
            let stdout_color = host.args.color.enabled(std::io::stdout().is_terminal());
            let mut prompter =
                build_prompter(*yes, *dry_run, stdout_color, host.args.stdin_is_terminal)?;
            ctx.config.push_pkg_health(output)?;

            let git = Git::new(host.platform.zenops_dir(), &ctx.sh);
            if git.is_git_repo()? && git.has_uncommitted_changes()? {
                ctx.config.check_own_status(&ctx.sh, output)?;
                // `--yes` without `--allow-dirty` aborts so CI/cron surface
                // divergence instead of silently applying uncommitted state.
                // `--dry-run` writes nothing, so it's always safe to continue.
                // `--allow-dirty` in any mode bypasses the prompt entirely.
                if *yes && !*allow_dirty {
                    return Err(Error::DirtyRepoRequiresAllowDirty(
                        host.platform.zenops_dir().to_path_buf(),
                    ));
                }
                if !*allow_dirty {
                    git.print_pre_apply_summary(stdout_color)?;
                    match prompter.confirm_pre_apply()? {
                        PreApplyDecision::CommitAndPush { message } => {
                            git.commit_all_and_push(&message)?;
                        }
                        PreApplyDecision::Continue => {}
                        PreApplyDecision::Abort => return Ok(()),
                    }
                }
            }

            ctx.config.update_config_files(&ctx.sh, &mut config_files)?;
            config_files.apply_changes(output, prompter.as_mut())?;
            Ok(())
        }
        Cmd::Status { diff: _, all: _ } => {
            let ctx = CommandContext::load(host, false)?;
            let mut config_files = ConfigFiles::new(host.platform);
            ctx.config.push_pkg_health(output)?;
            ctx.config.check_own_status(&ctx.sh, output)?;
            ctx.config.update_config_files(&ctx.sh, &mut config_files)?;
            config_files.check_status(output)?;
            Ok(())
        }
        Cmd::Pkg {
            pattern,
            all,
            all_hints,
            verbose,
        } => {
            let ctx = CommandContext::load(host, false)?;
            pkg_list::push(
                &ctx.config,
                pkg_list::Options {
                    pattern: pattern.clone(),
                    all: *all,
                    all_hints: *all_hints,
                    verbose: *verbose,
                },
                output,
            )?;
            Ok(())
        }
        Cmd::Repo { command } => {
            let sh = Shell::new()?;
            command.passthru_dispatch_in(host.platform.zenops_dir(), &sh)?;
            Ok(())
        }
    }
}