Skip to main content

dev_prune/
lib.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4pub mod adapters;
5pub mod channel;
6pub mod commands;
7pub mod config;
8pub mod constants;
9pub mod daemon;
10pub mod declared;
11pub mod discovery;
12pub mod engine;
13pub mod help;
14pub mod history;
15pub mod i18n;
16pub mod json;
17pub mod output;
18pub mod pathenv;
19pub mod receipt;
20pub mod scanner;
21pub mod setup;
22pub mod spawn;
23pub mod tui;
24pub mod workspace;
25
26use clap::{Parser, Subcommand};
27
28/// Process exit codes, so scripts and CI can branch on the outcome.
29///
30/// These are part of the tool's contract and are documented in `docs/CLI_REFERENCE.md`;
31/// changing one is a breaking change.
32pub mod exit_code {
33    /// The command did what it was asked to do. A prune that deleted nothing because
34    /// nothing was idle is still a success.
35    pub const OK: i32 = 0;
36    /// The command failed. The reason is on stderr.
37    pub const FAILURE: i32 = 1;
38    /// The arguments were not usable. Emitted by clap, listed here so the set is complete.
39    pub const USAGE: i32 = 2;
40}
41
42/// The machine's own architecture, reported only when it differs from this build's.
43///
44/// `std::env::consts::ARCH` is baked in at compile time, so a 32-bit build on a 64-bit
45/// machine reports `x86` and looks, to anyone reading it, like a claim about the
46/// hardware. Windows sets [`constants::ENV_NATIVE_ARCH`] under WOW64 and under ARM64
47/// emulation; it is the only thing an emulated process can ask. The names are mapped to
48/// Rust's spellings so the two halves of "x86, but this machine is x86_64" match.
49///
50/// `None` means the build and the machine agree, or the question cannot be answered —
51/// both of which are reported as nothing at all rather than as a guess.
52pub fn native_arch_if_emulated() -> Option<String> {
53    let native = std::env::var(constants::ENV_NATIVE_ARCH).ok()?;
54    let native = native.trim();
55    if native.is_empty() {
56        return None;
57    }
58    let mapped = match native.to_ascii_uppercase().as_str() {
59        "AMD64" => "x86_64".to_string(),
60        "ARM64" => "aarch64".to_string(),
61        "X86" => "x86".to_string(),
62        other => other.to_ascii_lowercase(),
63    };
64    (mapped != std::env::consts::ARCH).then_some(mapped)
65}
66
67/// Marker for errors that are usage mistakes rather than runtime failures.
68///
69/// clap exits `USAGE` for conflicts it can see at parse time; combinations only the
70/// command logic can judge — `run --json` with neither `--dry-run` nor `--yes` — used
71/// to exit `FAILURE`, which told a script "the prune broke" when the truth was "the
72/// command line was incomplete". Raising this instead routes them to `USAGE`.
73#[derive(Debug)]
74pub struct UsageError(pub String);
75
76impl std::fmt::Display for UsageError {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        f.write_str(&self.0)
79    }
80}
81
82impl std::error::Error for UsageError {}
83
84/// Restore the default disposition for `SIGPIPE`.
85///
86/// Rust ignores `SIGPIPE` at startup, which turns `devp status | head` into a panic —
87/// "failed printing to stdout" plus a backtrace — where every other Unix tool simply
88/// stops. Putting the default back makes dev-prune behave like `ls` in a pipeline.
89#[cfg(unix)]
90fn restore_sigpipe() {
91    // SAFETY: `signal` with SIG_DFL is async-signal-safe and this runs before any
92    // thread is spawned.
93    unsafe {
94        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
95    }
96}
97
98#[cfg(not(unix))]
99fn restore_sigpipe() {}
100
101/// Explain the rename, then answer the question the user was really asking.
102///
103/// Nobody types `--force` for fun. They type it because something was not pruned and
104/// they want the tool to stop arguing — so a bare "the flag moved" note would leave
105/// them exactly as stuck as before. The list below is every reason a directory gets
106/// skipped, with the fix, because six of the seven are not what `--force` was for.
107///
108/// Goes to stderr with the rest of the diagnostics, so `--json` stays parseable.
109fn print_force_help() {
110    output::print_notice(
111        "`--force` is now `--ignore-idle`, which is what it has always actually done. \
112         The old spelling still works.",
113    );
114    eprintln!(
115        "
116  Reaching for --force usually means something did not get pruned. It is one of these:
117
118    Not idle yet          A commit or a source edit inside idle_days (15 by default).
119                          This is the one --ignore-idle is for.
120    Lockfile unusable     The package manager could not confirm it. Run the command
121                          dev-prune printed, then try again. No flag skips this check.
122    Opted out             `ignore.devprune.json` in the root, or `\"ignore\": true`
123                          in `.devprune.json`.
124    Under the size floor  Smaller than min_size_mb. `--min-size 0` includes it.
125    Not registered        `devp link .` first; `devp status` shows what is tracked.
126    Nested or symlinked   A submodule is pruned as itself, never as part of its
127                          parent, and a linked directory is refused. By design.
128    Too deep              Beyond scan_depth (6 levels). `devp config set scan_depth N`.
129
130  `devp run --dry-run` names the actual reason, per repository.
131
132  Still stuck? Ask your AI assistant — `devp skill` hands it the full troubleshooting
133  tree, including this list. It has read it. It wrote it.
134"
135    );
136}
137
138/// Whether a failure is just the reader at the other end of a pipe hanging up.
139///
140/// `devp status | head -5` is a normal thing to type, and the closed pipe it produces is
141/// not an error worth printing — printing it would itself fail.
142fn is_broken_pipe(err: &anyhow::Error) -> bool {
143    err.chain().any(|cause| {
144        cause
145            .downcast_ref::<std::io::Error>()
146            .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::BrokenPipe)
147    })
148}
149
150/// Universal, lockfile-safe workspace pruner and background dependency cleaner.
151///
152/// Note: `dev-prune` and `devp` are interchangeable binary aliases.
153#[derive(Parser, Debug)]
154#[command(name = constants::APP_NAME)]
155#[command(version = constants::VERSION)]
156#[command(author = constants::AUTHOR)]
157#[command(long_version = constants::LONG_VERSION.as_str())]
158// The default help lists twenty commands as one flat block. The template swaps
159// clap's subcommand list for the grouped, coloured one `help.rs` builds — the same
160// grouping as the manual's contents page — and the styles colour every page.
161#[command(styles = help::HELP_STYLES)]
162#[command(help_template = help::ROOT_HELP_TEMPLATE.as_str())]
163#[command(
164    about = "Universal, lockfile-safe workspace pruner and background dependency cleaner\nNote: `dev-prune` and `devp` are interchangeable binary aliases."
165)]
166#[command(after_help = help::ROOT_AFTER_HELP.as_str())]
167pub struct Cli {
168    #[command(subcommand)]
169    command: Commands,
170
171    /// Simulate pruning without deleting any files.
172    #[arg(long, global = true)]
173    dry_run: bool,
174
175    /// Prune repositories you are still working in, ignoring the idle-day threshold.
176    ///
177    /// This is the *only* check it lifts. Lockfile verification, `ignore.devprune.json`,
178    /// `"ignore": true`, symlink refusal and nested-repository refusal all still apply.
179    #[arg(long, global = true)]
180    ignore_idle: bool,
181
182    /// Deprecated spelling of `--ignore-idle`.
183    ///
184    /// Renamed because "force" reads like "override the safety checks", which it never
185    /// did — it only ever skipped the idle-day wait. Still accepted; prints a note.
186    #[arg(long, global = true)]
187    force: bool,
188
189    /// Bypass interactive confirmation prompts.
190    #[arg(long, short = 'y', global = true)]
191    yes: bool,
192}
193
194#[derive(Subcommand, Debug)]
195pub enum Commands {
196    /// Workspace onboarding & discovery: crawl paths for Git repositories and register them.
197    #[command(alias = "scan", alias = "onboard")]
198    #[command(long_about = help::INIT_LONG, after_long_help = help::INIT_EXAMPLES)]
199    Init {
200        /// Paths to scan for Git repositories (defaults to current directory).
201        #[arg(default_value = ".")]
202        paths: Vec<String>,
203
204        /// Work out where the repositories are instead of being told, and register
205        /// everything found. Ignores PATHS.
206        #[arg(long)]
207        auto: bool,
208    },
209
210    /// Register a single Git repository for pruning (defaults to current directory `.`).
211    #[command(long_about = help::LINK_LONG, after_long_help = help::LINK_EXAMPLES)]
212    Link {
213        /// Path to the Git repository to register.
214        #[arg(default_value = ".")]
215        path: String,
216
217        /// Suppress output and skip repos that set `disable_hooks`. Used by the Git hook.
218        #[arg(long)]
219        quiet: bool,
220    },
221
222    /// Remove a repository from the dev-prune registry (does not delete workspace files).
223    #[command(long_about = help::UNLINK_LONG, after_long_help = help::UNLINK_EXAMPLES)]
224    Unlink {
225        /// Path to the Git repository to unregister.
226        #[arg(default_value = ".")]
227        path: String,
228
229        /// Unregister every path that no longer exists, instead of one named repository.
230        #[arg(long, conflicts_with = "path")]
231        missing: bool,
232    },
233
234    /// Revert the most recent init or link action.
235    //
236    // Off the front page since 1.17.0: it covers ground `devp restore` also covers,
237    // but it shipped in 1.0.0 and the CLI surface is a contract, so it keeps
238    // working — its own `--help`, `devp man undo`, the reference — until 2.x, which
239    // is when it actually goes. `help::HIDDEN_FROM_HELP` keeps the grouped help in
240    // step with this flag.
241    #[command(hide = true)]
242    #[command(long_about = help::UNDO_LONG, after_long_help = help::UNDO_EXAMPLES)]
243    Undo,
244
245    /// Run a prune pass across all registered repositories or a target directory (`devp run .`).
246    #[command(long_about = help::RUN_LONG, after_long_help = help::RUN_EXAMPLES)]
247    Run {
248        /// Optional target workspace path. If omitted, runs across all registered repositories.
249        target_path: Option<String>,
250
251        /// Mark this as the scheduled background pass. Repositories that set
252        /// `disable_daemon` in `.devprune.json` are skipped. Set by the installed scheduler.
253        #[arg(long)]
254        daemon: bool,
255
256        /// Act only on these package managers (comma-separated),
257        /// e.g. `--only npm,pnpm`. Unknown names are an error.
258        #[arg(long, value_name = "ADAPTERS", conflicts_with = "skip")]
259        only: Option<String>,
260
261        /// Leave these package managers alone (comma-separated), e.g. `--skip cargo`.
262        #[arg(long, value_name = "ADAPTERS")]
263        skip: Option<String>,
264
265        /// Ignore bloat directories smaller than this many MiB. Overrides `min_size_mb`.
266        #[arg(long, value_name = "MIB")]
267        min_size: Option<u64>,
268
269        /// Prune everything except these repositories (comma-separated paths or names).
270        ///
271        /// The safe way to express "clean up but keep the API project": that project is
272        /// never verified, never deleted and never reinstalled, instead of being pruned
273        /// and then restored over the network.
274        #[arg(long, value_name = "REPOS")]
275        except: Option<String>,
276
277        /// Emit one JSON document instead of the human report. Implies non-interactive.
278        #[arg(long)]
279        json: bool,
280
281        /// Explain every decision instead of pruning: each repository and directory,
282        /// with the reason it would or would not be touched — including the states a
283        /// normal pass keeps quiet about (still active, opted out, under the size
284        /// floor). Read-only; nothing is verified or deleted.
285        #[arg(long, conflicts_with = "json")]
286        explain: bool,
287    },
288
289    /// View system dashboard: registered repos, background daemon, Git hooks & space metrics.
290    #[command(long_about = help::STATUS_LONG, after_long_help = help::STATUS_EXAMPLES)]
291    Status {
292        /// Show only the N repositories with the most reclaimable space.
293        ///
294        /// The dashboard lists every registered repository, which on a machine with a
295        /// hundred of them buries the handful actually worth pruning. Applies to the TUI,
296        /// the plain table and `--json` alike.
297        ///
298        /// Zero is rejected up front: "show the top 0" can only be a typo, and an empty
299        /// dashboard that looks like an empty registry is worse than a usage error.
300        #[arg(long, value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
301        top: Option<u64>,
302
303        /// Report lockfile drift instead of the dashboard: environments holding packages
304        /// their lockfile never recorded — the installs a prune would refuse to delete
305        /// because nothing could bring them back.
306        ///
307        /// A pure read: no package manager runs, nothing is written. Checked where a
308        /// file-level comparison exists — npm, uv and venv projects.
309        #[arg(long, conflicts_with = "top")]
310        drift: bool,
311
312        /// Emit the dashboard as one JSON document instead of the TUI or text table.
313        #[arg(long)]
314        json: bool,
315    },
316
317    /// List every prune pass, and open one up to see what it deleted and what asked it to.
318    #[command(long_about = help::HISTORY_LONG, after_long_help = help::HISTORY_EXAMPLES)]
319    History {
320        /// Show one pass in full. 1 is the most recent, matching the numbers in the list.
321        #[arg(long, value_name = "N", conflicts_with = "all")]
322        pass: Option<usize>,
323
324        /// How many passes to list. Defaults to the 20 most recent.
325        #[arg(long, value_name = "N", conflicts_with_all = ["all", "pass"])]
326        limit: Option<usize>,
327
328        /// List every recorded pass rather than the most recent few.
329        #[arg(long)]
330        all: bool,
331
332        /// Emit the whole log as one JSON document instead of the text report.
333        #[arg(long)]
334        json: bool,
335
336        /// Write the JSON document to a file. Bare, it goes to your documents folder.
337        #[arg(long, value_name = "PATH", num_args = 0..=1)]
338        export: Option<Option<std::path::PathBuf>>,
339    },
340
341    /// Show lifetime space reclaimed, recent prune passes, and the biggest repositories.
342    #[command(long_about = help::STATS_LONG, after_long_help = help::STATS_EXAMPLES)]
343    Stats {
344        /// Emit the figures as one JSON document instead of the text report.
345        #[arg(long)]
346        json: bool,
347    },
348
349    /// Report what dev-prune is allowed to do on this machine, and what it has been given permission to do.
350    #[command(long_about = help::TRUST_LONG, after_long_help = help::TRUST_EXAMPLES)]
351    Trust {
352        /// Emit the report as one JSON document instead of the table.
353        #[arg(long)]
354        json: bool,
355
356        /// Let Git read registered repositories it currently refuses on ownership.
357        #[arg(long, conflicts_with = "json")]
358        fix_ownership: bool,
359
360        /// Answer yes to the confirmation `--fix-ownership` asks.
361        #[arg(long, requires = "fix_ownership")]
362        yes: bool,
363    },
364
365    /// Print a shell completion script for bash, zsh, fish, PowerShell or elvish.
366    #[command(long_about = help::COMPLETIONS_LONG, after_long_help = help::COMPLETIONS_EXAMPLES)]
367    Completions {
368        /// Shell to generate for.
369        shell: clap_complete::Shell,
370    },
371
372    /// Print or write man pages, generated from the same definitions `--help` prints.
373    #[command(long_about = help::MAN_LONG, after_long_help = help::MAN_EXAMPLES)]
374    Man {
375        /// The command whose page to read, e.g. `devp man run`. Omit for the
376        /// contents page.
377        command: Option<String>,
378
379        /// Write `devp.1` plus one `devp-<command>.1` per subcommand into this
380        /// directory, instead of rendering the main page to stdout.
381        #[arg(long, value_name = "DIR")]
382        dir: Option<String>,
383
384        /// Print the roff source even when stdout is a terminal, instead of the
385        /// readable manual.
386        #[arg(long)]
387        roff: bool,
388    },
389
390    /// Report the size of every package manager cache on this machine (read-only unless you ask for `clear`).
391    #[command(long_about = help::CACHES_LONG, after_long_help = help::CACHES_EXAMPLES)]
392    Caches {
393        /// Emit the report as one JSON document instead of the table.
394        ///
395        /// Global within `caches` so it can be written after the subcommand too —
396        /// `devp caches clear npm --json` is what everyone types.
397        #[arg(long, global = true)]
398        json: bool,
399
400        /// Report only the caches that sit on one drive or filesystem: `--volume V:`,
401        /// `--volume /mnt/data`, or any path on it. `--drive` is the same flag.
402        ///
403        /// Not global: it narrows the report, and there is nothing for it to narrow in
404        /// `clear`, `docker` or `containers`, so pairing it with one is a usage error
405        /// rather than a flag that looks accepted and does nothing.
406        #[arg(long, visible_alias = "drive", value_name = "VOLUME")]
407        volume: Option<String>,
408
409        #[command(subcommand)]
410        action: Option<CachesAction>,
411    },
412
413    /// Manage global settings, background daemon, Git hooks, custom icons, or per-project .devprune.json.
414    #[command(long_about = help::CONFIG_LONG, after_long_help = help::CONFIG_EXAMPLES)]
415    Config {
416        #[command(subcommand)]
417        action: Option<ConfigAction>,
418    },
419
420    /// Restore dependencies in a project using its lockfile (npm ci, pnpm install, uv sync).
421    #[command(long_about = help::RESTORE_LONG, after_long_help = help::RESTORE_EXAMPLES)]
422    Restore {
423        /// Path to the project to restore (defaults to current directory).
424        path: Option<String>,
425
426        /// Put back exactly what the most recent prune pass deleted, in every repository
427        /// it touched. The undo for a `run`.
428        #[arg(long, conflicts_with = "path")]
429        last_run: bool,
430    },
431
432    /// Print the installed version, check for a newer release, and show how to upgrade.
433    #[command(long_about = help::UPDATE_LONG, after_long_help = help::UPDATE_EXAMPLES)]
434    Update {
435        /// Skip the release check for this run. The check is the only thing in dev-prune
436        /// that opens a network connection; `devp config set update_check false` turns
437        /// it off for good.
438        #[arg(long)]
439        offline: bool,
440
441        /// Download and install the newer release without asking. Plain `devp update`
442        /// offers the same install with a `[y/N]` prompt when a newer release exists
443        /// and stdin is a terminal; `-y` answers that prompt. Needs the network, so it
444        /// cannot be combined with `--offline`.
445        #[arg(long, conflicts_with = "offline")]
446        install: bool,
447
448        /// Print the upgrade command for every channel dev-prune ships through, instead
449        /// of only the one that installed this copy. Touches nothing and needs no
450        /// network — useful when the machine in front of you is not the one that has
451        /// the stale copy.
452        #[arg(long, conflicts_with_all = ["offline", "install"])]
453        channels: bool,
454    },
455
456    /// Export SKILL.md and display ready-to-copy AI Agent onboarding & skill import prompts.
457    #[command(long_about = help::SKILL_LONG, after_long_help = help::SKILL_EXAMPLES)]
458    Skill {
459        /// Write rules for one editor's agent into the current repository instead.
460        /// Each value below names the exact file it writes. Five of them —
461        /// `agents-md`, `copilot`, `gemini`, `junie`, `zed` — share a file with
462        /// other tools, so dev-prune owns a marked block inside it and leaves every
463        /// byte outside the markers as found. Claude Code needs no per-repo file:
464        /// plain `devp skill` installs its skill globally.
465        #[arg(long, value_enum, value_name = "EDITOR")]
466        agent: Option<commands::skill::AgentEditor>,
467    },
468
469    /// Install whatever dev-prune integration is missing: alias, SKILL.md, Git hooks, scheduler.
470    #[command(long_about = help::SETUP_LONG, after_long_help = help::SETUP_EXAMPLES)]
471    Setup {
472        /// Report what is installed without changing anything.
473        #[arg(long)]
474        status: bool,
475    },
476
477    /// Diagnose the installation, or one repository if given a path (`devp doctor .`).
478    #[command(long_about = help::DOCTOR_LONG, after_long_help = help::DOCTOR_EXAMPLES)]
479    Doctor {
480        /// Repository to diagnose. Omit to check the installation itself.
481        path: Option<String>,
482
483        /// Repair what the installation check finds broken: refresh a stale or missing
484        /// `devp` twin, re-export SKILL.md, re-register a scheduler or Git hooks whose
485        /// binary moved, and drop registry entries whose repository is gone.
486        ///
487        /// Repairs only what was installed and has since broken — it never installs an
488        /// integration that was never set up (that is `devp setup`), and it cannot fix a
489        /// corrupt registry file, which needs a human decision.
490        #[arg(long, conflicts_with = "path")]
491        fix: bool,
492    },
493
494    /// Move this install to another package manager: `devp install --channel uv`.
495    //
496    // Off the front page since 1.17.0: the name reads like "install the tool", and
497    // what it does is *move* an installation between package managers. The honest fix
498    // is a rename, which the 1.0.0 CLI contract defers to 2.x — until then it works
499    // exactly as before, just not in `devp --help`.
500    #[command(hide = true)]
501    #[command(long_about = help::INSTALL_LONG, after_long_help = help::INSTALL_EXAMPLES)]
502    Install {
503        /// The package manager to move this installation to. Omit to print which one
504        /// owns the running copy, and the names this flag accepts.
505        #[arg(long, value_enum, value_name = "NAME")]
506        channel: Option<commands::install::TargetChannel>,
507
508        /// Print the commands that would run, and run none of them.
509        #[arg(long)]
510        dry_run: bool,
511    },
512
513    /// Remove dev-prune: scheduler, hooks, PATH entry, agent skill, and every copy of the binary.
514    #[command(long_about = help::UNINSTALL_LONG, after_long_help = help::UNINSTALL_EXAMPLES)]
515    Uninstall {
516        /// Perform a deep uninstall (wipe configuration folder and .devprune.json files).
517        #[arg(long)]
518        deep: bool,
519    },
520}
521
522impl Commands {
523    /// Whether this command's stdout is something another program reads.
524    ///
525    /// Two cases. `--json` promises stdout carries one document and nothing else, and
526    /// `completions` prints a script that gets sourced — a stray line in either is a
527    /// parse error rather than a nicety. `link --quiet` is the Git hook path, which runs
528    /// inside somebody's commit.
529    ///
530    /// Everything else defers to [`output::print_attribution`], which prints only when
531    /// stdout is a terminal. Neither function checks that the line is intact, and nothing
532    /// downstream depends on it having been printed.
533    fn suppresses_attribution(&self) -> bool {
534        match self {
535            Commands::Completions { .. } | Commands::Man { .. } => true,
536            Commands::Run { json, .. }
537            | Commands::Status { json, .. }
538            | Commands::Stats { json }
539            | Commands::History { json, .. }
540            | Commands::Trust { json, .. }
541            | Commands::Caches { json, .. } => *json,
542            Commands::Link { quiet, .. } => *quiet,
543            _ => false,
544        }
545    }
546}
547
548#[derive(Subcommand, Debug)]
549pub enum CachesAction {
550    /// Empty one manager's cache, or every one of them, after showing what goes and asking.
551    #[command(long_about = help::CACHES_CLEAR_LONG, after_long_help = help::CACHES_CLEAR_EXAMPLES)]
552    Clear {
553        /// Which cache to empty: a manager name (npm, go, cargo, gradle, …) or `all`.
554        #[arg(value_name = "MANAGER")]
555        target: String,
556
557        /// Only empty caches that are over the size cap set for them in
558        /// `cache_max_gb`. Without a cap set for anything, this clears nothing.
559        #[arg(long)]
560        over_cap: bool,
561
562        /// Only empty caches that no registered repository uses. Refuses to run when
563        /// there are no registered repositories to check against.
564        #[arg(long)]
565        unused: bool,
566    },
567
568    /// What Docker is holding: images, containers, volumes and build cache (read-only).
569    #[command(long_about = help::CACHES_DOCKER_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
570    Docker,
571
572    /// What Podman is holding: images, containers, volumes and build cache (read-only).
573    #[command(long_about = help::CACHES_DOCKER_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
574    Podman,
575
576    /// The same report for every container engine found, or for the one you name.
577    #[command(long_about = help::CACHES_CONTAINERS_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
578    Containers {
579        /// docker, podman, nerdctl, finch or container. Omit for every one installed.
580        #[arg(value_name = "ENGINE")]
581        engine: Option<String>,
582    },
583}
584
585#[derive(Subcommand, Debug)]
586pub enum ConfigAction {
587    /// Display a global configuration value.
588    #[command(long_about = help::CONFIG_GET_LONG, after_long_help = help::CONFIG_GET_EXAMPLES)]
589    Get {
590        /// Any key `devp config show` lists — idle_days, min_size_mb, auto_update,
591        /// disabled_adapters and the rest. `devp config show` prints every key with
592        /// its current value.
593        key: String,
594    },
595    /// Set a global configuration value.
596    #[command(long_about = help::CONFIG_SET_LONG, after_long_help = help::CONFIG_SET_EXAMPLES)]
597    Set {
598        /// Configuration key.
599        key: String,
600        /// New value.
601        value: String,
602    },
603    /// Show all global configuration values or sync per-repo configurations.
604    #[command(long_about = help::CONFIG_SHOW_LONG, after_long_help = help::CONFIG_SHOW_EXAMPLES)]
605    Show {
606        /// Force update/sync pass across all registered repos.
607        #[arg(long, short)]
608        update: bool,
609    },
610    /// Turn on everything the first run recommends, in one command.
611    #[command(long_about = help::CONFIG_RECOMMENDED_LONG, after_long_help = help::CONFIG_RECOMMENDED_EXAMPLES)]
612    Recommended {
613        /// Include the recommendations that come with something to know first.
614        #[arg(long)]
615        with_cautious: bool,
616    },
617    /// Inspect or initialize per-repository config (.devprune.json) for a workspace path.
618    #[command(long_about = help::CONFIG_PROJECT_LONG, after_long_help = help::CONFIG_PROJECT_EXAMPLES)]
619    Project {
620        /// Path to the repository (defaults to current directory).
621        #[arg(default_value = ".")]
622        path: String,
623        /// Force update/sync pass on this project config.
624        #[arg(long, short)]
625        update: bool,
626        /// Act on the committed project.devprune.json instead of the personal file.
627        #[arg(long)]
628        team: bool,
629    },
630    /// Configure OS background daemon scheduler globally or for a workspace path.
631    #[command(long_about = help::CONFIG_DAEMON_LONG, after_long_help = help::CONFIG_DAEMON_EXAMPLES)]
632    Daemon {
633        /// Optional workspace path or sub-action (enable, disable, status).
634        target: Option<String>,
635        /// Sub-action if path was provided (enable, disable, status).
636        sub_action: Option<String>,
637    },
638    /// Configure non-blocking global Git background auto-registration hooks globally or for a workspace path.
639    #[command(long_about = help::CONFIG_HOOK_LONG, after_long_help = help::CONFIG_HOOK_EXAMPLES)]
640    Hook {
641        /// Optional workspace path or sub-action (enable, disable, status).
642        target: Option<String>,
643        /// Sub-action if path was provided (enable, disable, status).
644        sub_action: Option<String>,
645        /// Install in front of the hooks directory already configured, forwarding to it,
646        /// instead of refusing to take a slot another tool is using.
647        #[arg(long)]
648        chain: bool,
649    },
650    /// Register a file-manager icon for .devprune.json, and print an editor snippet.
651    #[command(long_about = help::CONFIG_ICON_LONG, after_long_help = help::CONFIG_ICON_EXAMPLES)]
652    Icon,
653    /// Walk through every global setting, confirming or changing each one.
654    #[command(long_about = help::CONFIG_WIZARD_LONG, after_long_help = help::CONFIG_WIZARD_EXAMPLES)]
655    Wizard {
656        /// Ask one question per line instead of opening the full-screen configurator.
657        #[arg(long)]
658        no_tui: bool,
659    },
660}
661
662/// Print rich version & system environment details for -v / -V / --version.
663///
664/// This, not clap, is what `devp --version` actually runs — [`normalize_args`] catches the
665/// flag first. The author and repository are printed here because a copy of this binary
666/// found on a machine with no package manager record should still be able to say where it
667/// came from, and `--version` is the first thing anyone runs on an unknown executable.
668pub fn print_version_info() {
669    use colored::Colorize;
670    output::print_banner();
671    println!(
672        "dev-prune (devp) {}",
673        format!("v{}", constants::VERSION).green().bold()
674    );
675    println!(
676        "  Binary Aliases:  {} | {}",
677        "dev-prune".cyan(),
678        "devp".cyan()
679    );
680    // These lines are facts, not status, so most of them stay in the terminal's own
681    // colour. The author line was turquoise and the OS and architecture yellow, which
682    // marked nothing and put five hues on one short screen; yellow now only ever means a
683    // warning, and cyan is reserved for the two things worth clicking.
684    println!("  Author:          {}", constants::AUTHOR);
685    println!(
686        "  Repository:      {}",
687        constants::REPO_URL.cyan().underline()
688    );
689    println!(
690        "  Homepage:        {}",
691        constants::HOMEPAGE_URL.cyan().underline()
692    );
693    println!("  Target OS:       {}", std::env::consts::OS);
694    match native_arch_if_emulated() {
695        // Without this the line reads as a statement about the machine, and a 32-bit
696        // build on a 64-bit laptop looks like the laptop is 32-bit.
697        Some(native) => println!(
698            "  Architecture:    {} {}",
699            std::env::consts::ARCH,
700            format!(
701                "(this build — the machine is {native}; `devp update` installs the native one)"
702            )
703            .yellow()
704        ),
705        None => println!("  Architecture:    {}", std::env::consts::ARCH),
706    }
707    println!(
708        "  Compiler:        Rust {}+ (edition 2024)",
709        constants::MSRV
710    );
711    println!("  License:         Apache-2.0");
712    println!();
713    let reg_path = config::Registry::registry_path()
714        .map(output::styled_path)
715        .unwrap_or_else(|_| "unknown".to_string());
716    println!("  Config Path:     {reg_path}");
717
718    if let Ok(exe) = std::env::current_exe()
719        && let Some(exe_dir) = exe.parent()
720    {
721        let exe_dir_str = output::clean_path(exe_dir);
722        // The same tolerant comparison the PATH writer uses — a trailing backslash or a
723        // case difference must not turn the audit line red on a healthy install.
724        let path_var = std::env::var("PATH").unwrap_or_default();
725        let exe_dir_entry = exe_dir.to_string_lossy();
726        let is_in_path = path_var
727            .split(if cfg!(windows) { ';' } else { ':' })
728            .any(|p| pathenv::entries_equal(p, &exe_dir_entry));
729
730        println!("  Binary Dir:      {}", exe_dir_str.cyan());
731        if is_in_path {
732            println!(
733                "  PATH Audit:      {}",
734                "✓ Executable directory is active in system PATH.".green()
735            );
736        } else {
737            println!(
738                "  PATH Audit:      {}",
739                "⚠ Executable directory is NOT in system PATH!".yellow()
740            );
741            println!(
742                "                   Add `{}` to Environment Variables.",
743                exe_dir_str.cyan()
744            );
745        }
746    }
747}
748
749/// Case-insensitive subcommand normalizer and status alias router.
750fn normalize_args() -> Vec<String> {
751    let args: Vec<String> = std::env::args().collect();
752    if args.len() == 2 && (args[1] == "-v" || args[1] == "-V" || args[1] == "--version") {
753        print_version_info();
754        std::process::exit(exit_code::OK);
755    }
756    if args.len() <= 1
757        || args
758            .iter()
759            .any(|a| a == "-h" || a == "--help" || a == "help")
760    {
761        output::print_banner();
762    }
763    if args.len() <= 1 {
764        return args;
765    }
766
767    let mut normalized = vec![args[0].clone()];
768    for (i, arg) in args.iter().enumerate().skip(1) {
769        if i == 1 && !arg.starts_with('-') {
770            normalized.push(arg.to_lowercase());
771        } else {
772            normalized.push(arg.clone());
773        }
774    }
775
776    // Map `devp daemon|hook|icon [ARGS...]` -> `devp config daemon|hook|icon [ARGS...]`
777    //
778    // These live under `config` because that is where the rest of the persistent
779    // settings live, but nobody types `devp config hook install` when they mean
780    // "install the hook" — and the tool's own output has always said `devp hook
781    // install`. Accepting both costs one insert and removes a papercut.
782    if matches!(normalized[1].as_str(), "daemon" | "hook" | "icon") {
783        normalized.insert(1, "config".to_string());
784    }
785
786    // Map `devp status [PATH] daemon` -> `devp config daemon [PATH] status`
787    // Map `devp status [PATH] hook`   -> `devp config hook [PATH] status`
788    //
789    // Exactly one optional PATH, and never a flag: `devp status --json daemon` must
790    // reach clap as typed and fail there, not be rewritten with `--json` as a path.
791    if normalized[1] == "status"
792        && (normalized.len() == 3 || (normalized.len() == 4 && !normalized[2].starts_with('-')))
793    {
794        let last = normalized
795            .last()
796            .map(|s| s.to_lowercase())
797            .unwrap_or_default();
798        if last == "daemon" || last == "hook" {
799            let mut rewrited = vec![normalized[0].clone(), "config".to_string(), last];
800            if normalized.len() > 3 {
801                rewrited.push(normalized[2].clone());
802            }
803            rewrited.push("status".to_string());
804            return rewrited;
805        }
806    }
807
808    // Map `devp config [PATH] daemon [ACTION]` -> `devp config daemon [PATH] [ACTION]`
809    // Map `devp config [PATH] hook [ACTION]`   -> `devp config hook [PATH] [ACTION]`
810    //
811    // Only when the second argument can actually be a path — a flag there means the
812    // user is talking to `config` itself and the rewrite would misfile it.
813    if normalized.len() >= 4 && normalized[1] == "config" && !normalized[2].starts_with('-') {
814        let third = normalized[3].to_lowercase();
815        if third == "daemon" || third == "hook" {
816            let mut rewrited = vec![
817                normalized[0].clone(),
818                "config".to_string(),
819                third,
820                normalized[2].clone(),
821            ];
822            for extra in &normalized[4..] {
823                rewrited.push(extra.clone());
824            }
825            return rewrited;
826        }
827    }
828
829    normalized
830}
831
832/// Whether the automatic setup pass may run for this invocation.
833///
834/// Two callers are excluded on purpose. The Git hook runs `link --quiet` with no
835/// terminal attached and inside someone's commit; the scheduler runs `run --daemon` the
836/// same way. An integration pass nobody can see is one nobody can refuse, so both wait
837/// for the next command a human types. `uninstall` is excluded for the obvious reason,
838/// and `setup` because it is the pass, run deliberately.
839fn auto_setup_allowed(args: &[String]) -> bool {
840    let subcommand = args.get(1).map(String::as_str).unwrap_or("");
841    // `--json` means a program is parsing stdout; the setup report and the first-run
842    // wizard would land inside the document. That invocation waits too.
843    !matches!(subcommand, "uninstall" | "setup")
844        && !args
845            .iter()
846            .any(|a| a == "--quiet" || a == "--daemon" || a == "--json")
847}
848
849/// Run the CLI application.
850pub fn run_cli() {
851    restore_sigpipe();
852
853    let args = normalize_args();
854    if auto_setup_allowed(&args) {
855        setup::auto_setup_if_due();
856    }
857    let cli = Cli::parse_from(args);
858
859    // After parsing, so `--version` and `--help` never pay for it, and before anything
860    // is printed, because every heading past this line is drawn in whatever it settles
861    // on. `Registry::load` is a pure read, and a registry that will not load is not a
862    // reason to refuse to print in English — the command below reports that failure
863    // properly.
864    i18n::init(
865        config::Registry::load()
866            .ok()
867            .map(|registry| registry.settings.language)
868            .as_deref(),
869    );
870
871    // Both spellings mean the same thing; the old one just says so first.
872    let ignore_idle = cli.ignore_idle || cli.force;
873    if cli.force {
874        print_force_help();
875    }
876
877    // Decided before the match, because that is where `cli.command` is consumed.
878    let credit_the_author = !cli.command.suppresses_attribution();
879
880    // Every path the user typed passes through `expand_tilde` on the way in. PowerShell
881    // and cmd hand us `~/Code` verbatim, so without this the documented one-liner
882    // registers a directory literally named `~`.
883    let result = match cli.command {
884        Commands::Init { paths, auto } => {
885            let paths: Vec<String> = paths.iter().map(|p| config::expand_tilde(p)).collect();
886            commands::init::run(&paths, cli.dry_run, auto)
887        }
888        Commands::Link { path, quiet } => {
889            commands::link::run_link(&config::expand_tilde(&path), quiet)
890        }
891        Commands::Unlink { path, missing } => {
892            if missing {
893                commands::link::run_unlink_missing()
894            } else {
895                commands::link::run_unlink(&config::expand_tilde(&path))
896            }
897        }
898        Commands::Undo => commands::undo::run(),
899        Commands::Run {
900            target_path,
901            daemon,
902            only,
903            skip,
904            min_size,
905            except,
906            json,
907            explain,
908        } => {
909            let target_path = target_path.map(|p| config::expand_tilde(&p));
910            commands::run::run(commands::run::RunArgs {
911                target_path: target_path.as_deref(),
912                dry_run: cli.dry_run,
913                force: ignore_idle,
914                yes: cli.yes,
915                daemon,
916                only: only.as_deref(),
917                skip: skip.as_deref(),
918                min_size_mb: min_size,
919                except: except.as_deref(),
920                json,
921                explain,
922            })
923        }
924        Commands::Status { top, drift, json } => {
925            commands::status::run(top.map(|n| n as usize), drift, json)
926        }
927        Commands::History {
928            pass,
929            limit,
930            all,
931            json,
932            export,
933        } => commands::history::run(&commands::history::HistoryArgs {
934            pass,
935            limit,
936            all,
937            json,
938            export,
939        }),
940        Commands::Stats { json } => commands::stats::run(json),
941        Commands::Completions { shell } => commands::completions::run(shell),
942        Commands::Man { command, dir, roff } => {
943            commands::man::run(command.as_deref(), dir.as_deref(), roff)
944        }
945        Commands::Trust {
946            json,
947            fix_ownership,
948            yes,
949        } => {
950            if fix_ownership {
951                commands::trust::fix_ownership(yes)
952            } else {
953                commands::trust::run(json)
954            }
955        }
956        Commands::Caches {
957            json,
958            volume,
959            action,
960        } => match action {
961            // Refused rather than ignored. `--volume` reads as "act on this drive
962            // only", and a `clear` that silently emptied every drive after being
963            // handed one would be the worst possible way to learn the flag does not
964            // reach here.
965            Some(_) if volume.is_some() => Err(anyhow::Error::new(UsageError(
966                "`--volume` narrows the report and has nothing to narrow in a subcommand. \
967                 Run `devp caches --volume <VOLUME>` on its own to see what is on one \
968                 drive; `devp caches clear <manager>` then empties that manager \
969                 wherever it is."
970                    .to_string(),
971            ))),
972            Some(CachesAction::Clear {
973                target,
974                over_cap,
975                unused,
976            }) => {
977                commands::caches::run_clear(&target, over_cap, unused, cli.yes, cli.dry_run, json)
978            }
979            Some(CachesAction::Docker) => commands::containers::run(Some("docker"), json),
980            Some(CachesAction::Podman) => commands::containers::run(Some("podman"), json),
981            Some(CachesAction::Containers { engine }) => {
982                commands::containers::run(engine.as_deref(), json)
983            }
984            None => commands::caches::run(json, volume.as_deref()),
985        },
986        Commands::Config { action } => match action {
987            Some(ConfigAction::Get { key }) => commands::config::run_get(&key),
988            Some(ConfigAction::Set { key, value }) => commands::config::run_set(&key, &value),
989            Some(ConfigAction::Show { update: true }) => commands::config::run_global_update(),
990            Some(ConfigAction::Show { update: false }) | None => commands::config::run_show(),
991            Some(ConfigAction::Recommended { with_cautious }) => {
992                commands::config::run_recommended(with_cautious)
993            }
994            Some(ConfigAction::Project { path, update, team }) => {
995                commands::config::run_path_config(&config::expand_tilde(&path), update, team)
996            }
997            Some(ConfigAction::Daemon { target, sub_action }) => {
998                // A toggle word (`on`, `off`) never starts with `~`, so expanding the
999                // target before the match cannot turn one into a path.
1000                let target = target.map(|t| config::expand_tilde(&t));
1001                let (path, action) = match (target.as_deref(), sub_action.as_deref()) {
1002                    (Some(t), Some(a)) => (Some(t), a),
1003                    (Some(t), None) if commands::config::is_toggle_word(t) => (None, t),
1004                    (Some(t), None) => (Some(t), "status"),
1005                    (None, Some(a)) => (None, a),
1006                    (None, None) => (None, "status"),
1007                };
1008                commands::config::run_daemon_toggle(path, action)
1009            }
1010            Some(ConfigAction::Hook {
1011                target,
1012                sub_action,
1013                chain,
1014            }) => {
1015                let target = target.map(|t| config::expand_tilde(&t));
1016                let (path, action) = match (target.as_deref(), sub_action.as_deref()) {
1017                    (Some(t), Some(a)) => (Some(t), a),
1018                    (Some(t), None) if commands::config::is_toggle_word(t) => (None, t),
1019                    (Some(t), None) => (Some(t), "status"),
1020                    (None, Some(a)) => (None, a),
1021                    // `--chain` on its own is an install instruction, not a status query.
1022                    (None, None) if chain => (None, "install"),
1023                    (None, None) => (None, "status"),
1024                };
1025                commands::config::run_hook_toggle(path, action, chain)
1026            }
1027            Some(ConfigAction::Icon) => commands::icon::run_install(),
1028            Some(ConfigAction::Wizard { no_tui }) => {
1029                commands::config::run_wizard(no_tui, commands::config::Opened::ByRequest)
1030                    .map(|_| ())
1031            }
1032        },
1033        Commands::Restore { path, last_run } => {
1034            if last_run {
1035                commands::restore::run_last_run()
1036            } else {
1037                commands::restore::run(&config::expand_tilde(path.as_deref().unwrap_or(".")))
1038            }
1039        }
1040        Commands::Update {
1041            offline,
1042            install,
1043            channels,
1044        } => commands::update::run(offline, install, channels, cli.yes),
1045        Commands::Skill { agent } => commands::skill::run(agent),
1046        Commands::Setup { status } => commands::setup::run(status),
1047        Commands::Doctor { path, fix } => {
1048            let path = path.map(|p| config::expand_tilde(&p));
1049            commands::doctor::run(path.as_deref(), fix)
1050        }
1051        Commands::Install { channel, dry_run } => commands::install::run(channel, dry_run, cli.yes),
1052        Commands::Uninstall { deep } => commands::uninstall::run(deep, cli.yes),
1053    };
1054
1055    if let Err(e) = result {
1056        if is_broken_pipe(&e) {
1057            std::process::exit(exit_code::OK);
1058        }
1059        output::print_error(&format!("{e:#}"));
1060        if e.downcast_ref::<UsageError>().is_some() {
1061            std::process::exit(exit_code::USAGE);
1062        }
1063        std::process::exit(exit_code::FAILURE);
1064    }
1065
1066    // Only on the way out of a successful run: nobody reading an error message needs a
1067    // credit under it.
1068    if credit_the_author {
1069        output::print_attribution();
1070    }
1071}
1072
1073#[cfg(test)]
1074mod tests {
1075    use super::auto_setup_allowed;
1076
1077    fn args(rest: &[&str]) -> Vec<String> {
1078        std::iter::once("devp")
1079            .chain(rest.iter().copied())
1080            .map(String::from)
1081            .collect()
1082    }
1083
1084    #[test]
1085    fn ordinary_interactive_commands_may_auto_setup() {
1086        assert!(auto_setup_allowed(&args(&["status"])));
1087        assert!(auto_setup_allowed(&args(&["run", "--dry-run"])));
1088        assert!(auto_setup_allowed(&args(&[])));
1089    }
1090
1091    #[test]
1092    fn unattended_and_machine_read_invocations_may_not() {
1093        // The Git hook, the scheduler, and any `--json` consumer: a setup pass nobody
1094        // can see is one nobody can refuse, and setup output inside a JSON document is
1095        // a parse error.
1096        assert!(!auto_setup_allowed(&args(&["link", ".", "--quiet"])));
1097        assert!(!auto_setup_allowed(&args(&["run", "--daemon"])));
1098        assert!(!auto_setup_allowed(&args(&["status", "--json"])));
1099        assert!(!auto_setup_allowed(&args(&["uninstall"])));
1100        assert!(!auto_setup_allowed(&args(&["setup"])));
1101    }
1102}