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