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, through whichever package manager
442 /// installed this copy (cargo, npm, bun, pnpm, yarn, uv, pipx, or the installer
443 /// script). Needs the network, so it cannot be combined with `--offline`.
444 #[arg(long, conflicts_with = "offline")]
445 install: bool,
446
447 /// Print the upgrade command for every channel dev-prune ships through, instead
448 /// of only the one that installed this copy. Touches nothing and needs no
449 /// network — useful when the machine in front of you is not the one that has
450 /// the stale copy.
451 #[arg(long, conflicts_with_all = ["offline", "install"])]
452 channels: bool,
453 },
454
455 /// Export SKILL.md and display ready-to-copy AI Agent onboarding & skill import prompts.
456 #[command(long_about = help::SKILL_LONG, after_long_help = help::SKILL_EXAMPLES)]
457 Skill {
458 /// Write rules for one editor's agent into the current repository instead.
459 /// Each value below names the exact file it writes. Five of them —
460 /// `agents-md`, `copilot`, `gemini`, `junie`, `zed` — share a file with
461 /// other tools, so dev-prune owns a marked block inside it and leaves every
462 /// byte outside the markers as found. Claude Code needs no per-repo file:
463 /// plain `devp skill` installs its skill globally.
464 #[arg(long, value_enum, value_name = "EDITOR")]
465 agent: Option<commands::skill::AgentEditor>,
466 },
467
468 /// Install whatever dev-prune integration is missing: alias, SKILL.md, Git hooks, scheduler.
469 #[command(long_about = help::SETUP_LONG, after_long_help = help::SETUP_EXAMPLES)]
470 Setup {
471 /// Report what is installed without changing anything.
472 #[arg(long)]
473 status: bool,
474 },
475
476 /// Diagnose the installation, or one repository if given a path (`devp doctor .`).
477 #[command(long_about = help::DOCTOR_LONG, after_long_help = help::DOCTOR_EXAMPLES)]
478 Doctor {
479 /// Repository to diagnose. Omit to check the installation itself.
480 path: Option<String>,
481
482 /// Repair what the installation check finds broken: refresh a stale or missing
483 /// `devp` twin, re-export SKILL.md, re-register a scheduler or Git hooks whose
484 /// binary moved, and drop registry entries whose repository is gone.
485 ///
486 /// Repairs only what was installed and has since broken — it never installs an
487 /// integration that was never set up (that is `devp setup`), and it cannot fix a
488 /// corrupt registry file, which needs a human decision.
489 #[arg(long, conflicts_with = "path")]
490 fix: bool,
491 },
492
493 /// Move this install to another package manager: `devp install --channel uv`.
494 //
495 // Off the front page since 1.17.0: the name reads like "install the tool", and
496 // what it does is *move* an installation between package managers. The honest fix
497 // is a rename, which the 1.0.0 CLI contract defers to 2.x — until then it works
498 // exactly as before, just not in `devp --help`.
499 #[command(hide = true)]
500 #[command(long_about = help::INSTALL_LONG, after_long_help = help::INSTALL_EXAMPLES)]
501 Install {
502 /// The package manager to move this installation to. Omit to print which one
503 /// owns the running copy, and the names this flag accepts.
504 #[arg(long, value_enum, value_name = "NAME")]
505 channel: Option<commands::install::TargetChannel>,
506
507 /// Print the commands that would run, and run none of them.
508 #[arg(long)]
509 dry_run: bool,
510 },
511
512 /// Remove dev-prune: scheduler, hooks, PATH entry, agent skill, and every copy of the binary.
513 #[command(long_about = help::UNINSTALL_LONG, after_long_help = help::UNINSTALL_EXAMPLES)]
514 Uninstall {
515 /// Perform a deep uninstall (wipe configuration folder and .devprune.json files).
516 #[arg(long)]
517 deep: bool,
518 },
519}
520
521impl Commands {
522 /// Whether this command's stdout is something another program reads.
523 ///
524 /// Two cases. `--json` promises stdout carries one document and nothing else, and
525 /// `completions` prints a script that gets sourced — a stray line in either is a
526 /// parse error rather than a nicety. `link --quiet` is the Git hook path, which runs
527 /// inside somebody's commit.
528 ///
529 /// Everything else defers to [`output::print_attribution`], which prints only when
530 /// stdout is a terminal. Neither function checks that the line is intact, and nothing
531 /// downstream depends on it having been printed.
532 fn suppresses_attribution(&self) -> bool {
533 match self {
534 Commands::Completions { .. } | Commands::Man { .. } => true,
535 Commands::Run { json, .. }
536 | Commands::Status { json, .. }
537 | Commands::Stats { json }
538 | Commands::History { json, .. }
539 | Commands::Trust { json, .. }
540 | Commands::Caches { json, .. } => *json,
541 Commands::Link { quiet, .. } => *quiet,
542 _ => false,
543 }
544 }
545}
546
547#[derive(Subcommand, Debug)]
548pub enum CachesAction {
549 /// Empty one manager's cache, or every one of them, after showing what goes and asking.
550 #[command(long_about = help::CACHES_CLEAR_LONG, after_long_help = help::CACHES_CLEAR_EXAMPLES)]
551 Clear {
552 /// Which cache to empty: a manager name (npm, go, cargo, gradle, …) or `all`.
553 #[arg(value_name = "MANAGER")]
554 target: String,
555
556 /// Only empty caches that are over the size cap set for them in
557 /// `cache_max_gb`. Without a cap set for anything, this clears nothing.
558 #[arg(long)]
559 over_cap: bool,
560
561 /// Only empty caches that no registered repository uses. Refuses to run when
562 /// there are no registered repositories to check against.
563 #[arg(long)]
564 unused: bool,
565 },
566
567 /// What Docker is holding: images, containers, volumes and build cache (read-only).
568 #[command(long_about = help::CACHES_DOCKER_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
569 Docker,
570
571 /// What Podman is holding: images, containers, volumes and build cache (read-only).
572 #[command(long_about = help::CACHES_DOCKER_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
573 Podman,
574
575 /// The same report for every container engine found, or for the one you name.
576 #[command(long_about = help::CACHES_CONTAINERS_LONG, after_long_help = help::CACHES_CONTAINERS_EXAMPLES)]
577 Containers {
578 /// docker, podman, nerdctl, finch or container. Omit for every one installed.
579 #[arg(value_name = "ENGINE")]
580 engine: Option<String>,
581 },
582}
583
584#[derive(Subcommand, Debug)]
585pub enum ConfigAction {
586 /// Display a global configuration value.
587 #[command(long_about = help::CONFIG_GET_LONG, after_long_help = help::CONFIG_GET_EXAMPLES)]
588 Get {
589 /// Any key `devp config show` lists — idle_days, min_size_mb, auto_update,
590 /// disabled_adapters and the rest. `devp config show` prints every key with
591 /// its current value.
592 key: String,
593 },
594 /// Set a global configuration value.
595 #[command(long_about = help::CONFIG_SET_LONG, after_long_help = help::CONFIG_SET_EXAMPLES)]
596 Set {
597 /// Configuration key.
598 key: String,
599 /// New value.
600 value: String,
601 },
602 /// Show all global configuration values or sync per-repo configurations.
603 #[command(long_about = help::CONFIG_SHOW_LONG, after_long_help = help::CONFIG_SHOW_EXAMPLES)]
604 Show {
605 /// Force update/sync pass across all registered repos.
606 #[arg(long, short)]
607 update: bool,
608 },
609 /// Turn on everything the first run recommends, in one command.
610 #[command(long_about = help::CONFIG_RECOMMENDED_LONG, after_long_help = help::CONFIG_RECOMMENDED_EXAMPLES)]
611 Recommended {
612 /// Include the recommendations that come with something to know first.
613 #[arg(long)]
614 with_cautious: bool,
615 },
616 /// Inspect or initialize per-repository config (.devprune.json) for a workspace path.
617 #[command(long_about = help::CONFIG_PROJECT_LONG, after_long_help = help::CONFIG_PROJECT_EXAMPLES)]
618 Project {
619 /// Path to the repository (defaults to current directory).
620 #[arg(default_value = ".")]
621 path: String,
622 /// Force update/sync pass on this project config.
623 #[arg(long, short)]
624 update: bool,
625 /// Act on the committed project.devprune.json instead of the personal file.
626 #[arg(long)]
627 team: bool,
628 },
629 /// Configure OS background daemon scheduler globally or for a workspace path.
630 #[command(long_about = help::CONFIG_DAEMON_LONG, after_long_help = help::CONFIG_DAEMON_EXAMPLES)]
631 Daemon {
632 /// Optional workspace path or sub-action (enable, disable, status).
633 target: Option<String>,
634 /// Sub-action if path was provided (enable, disable, status).
635 sub_action: Option<String>,
636 },
637 /// Configure non-blocking global Git background auto-registration hooks globally or for a workspace path.
638 #[command(long_about = help::CONFIG_HOOK_LONG, after_long_help = help::CONFIG_HOOK_EXAMPLES)]
639 Hook {
640 /// Optional workspace path or sub-action (enable, disable, status).
641 target: Option<String>,
642 /// Sub-action if path was provided (enable, disable, status).
643 sub_action: Option<String>,
644 /// Install in front of the hooks directory already configured, forwarding to it,
645 /// instead of refusing to take a slot another tool is using.
646 #[arg(long)]
647 chain: bool,
648 },
649 /// Register a file-manager icon for .devprune.json, and print an editor snippet.
650 #[command(long_about = help::CONFIG_ICON_LONG, after_long_help = help::CONFIG_ICON_EXAMPLES)]
651 Icon,
652 /// Walk through every global setting, confirming or changing each one.
653 #[command(long_about = help::CONFIG_WIZARD_LONG, after_long_help = help::CONFIG_WIZARD_EXAMPLES)]
654 Wizard {
655 /// Ask one question per line instead of opening the full-screen configurator.
656 #[arg(long)]
657 no_tui: bool,
658 },
659}
660
661/// Print rich version & system environment details for -v / -V / --version.
662///
663/// This, not clap, is what `devp --version` actually runs — [`normalize_args`] catches the
664/// flag first. The author and repository are printed here because a copy of this binary
665/// found on a machine with no package manager record should still be able to say where it
666/// came from, and `--version` is the first thing anyone runs on an unknown executable.
667pub fn print_version_info() {
668 use colored::Colorize;
669 output::print_banner();
670 println!(
671 "dev-prune (devp) {}",
672 format!("v{}", constants::VERSION).green().bold()
673 );
674 println!(
675 " Binary Aliases: {} | {}",
676 "dev-prune".cyan(),
677 "devp".cyan()
678 );
679 // These lines are facts, not status, so most of them stay in the terminal's own
680 // colour. The author line was turquoise and the OS and architecture yellow, which
681 // marked nothing and put five hues on one short screen; yellow now only ever means a
682 // warning, and cyan is reserved for the two things worth clicking.
683 println!(" Author: {}", constants::AUTHOR);
684 println!(
685 " Repository: {}",
686 constants::REPO_URL.cyan().underline()
687 );
688 println!(
689 " Homepage: {}",
690 constants::HOMEPAGE_URL.cyan().underline()
691 );
692 println!(" Target OS: {}", std::env::consts::OS);
693 match native_arch_if_emulated() {
694 // Without this the line reads as a statement about the machine, and a 32-bit
695 // build on a 64-bit laptop looks like the laptop is 32-bit.
696 Some(native) => println!(
697 " Architecture: {} {}",
698 std::env::consts::ARCH,
699 format!(
700 "(this build — the machine is {native}; `devp update` installs the native one)"
701 )
702 .yellow()
703 ),
704 None => println!(" Architecture: {}", std::env::consts::ARCH),
705 }
706 println!(
707 " Compiler: Rust {}+ (edition 2024)",
708 constants::MSRV
709 );
710 println!(" License: Apache-2.0");
711 println!();
712 let reg_path = config::Registry::registry_path()
713 .map(output::styled_path)
714 .unwrap_or_else(|_| "unknown".to_string());
715 println!(" Config Path: {reg_path}");
716
717 if let Ok(exe) = std::env::current_exe()
718 && let Some(exe_dir) = exe.parent()
719 {
720 let exe_dir_str = output::clean_path(exe_dir);
721 // The same tolerant comparison the PATH writer uses — a trailing backslash or a
722 // case difference must not turn the audit line red on a healthy install.
723 let path_var = std::env::var("PATH").unwrap_or_default();
724 let exe_dir_entry = exe_dir.to_string_lossy();
725 let is_in_path = path_var
726 .split(if cfg!(windows) { ';' } else { ':' })
727 .any(|p| pathenv::entries_equal(p, &exe_dir_entry));
728
729 println!(" Binary Dir: {}", exe_dir_str.cyan());
730 if is_in_path {
731 println!(
732 " PATH Audit: {}",
733 "✓ Executable directory is active in system PATH.".green()
734 );
735 } else {
736 println!(
737 " PATH Audit: {}",
738 "⚠ Executable directory is NOT in system PATH!".yellow()
739 );
740 println!(
741 " Add `{}` to Environment Variables.",
742 exe_dir_str.cyan()
743 );
744 }
745 }
746}
747
748/// Case-insensitive subcommand normalizer and status alias router.
749fn normalize_args() -> Vec<String> {
750 let args: Vec<String> = std::env::args().collect();
751 if args.len() == 2 && (args[1] == "-v" || args[1] == "-V" || args[1] == "--version") {
752 print_version_info();
753 std::process::exit(exit_code::OK);
754 }
755 if args.len() <= 1
756 || args
757 .iter()
758 .any(|a| a == "-h" || a == "--help" || a == "help")
759 {
760 output::print_banner();
761 }
762 if args.len() <= 1 {
763 return args;
764 }
765
766 let mut normalized = vec![args[0].clone()];
767 for (i, arg) in args.iter().enumerate().skip(1) {
768 if i == 1 && !arg.starts_with('-') {
769 normalized.push(arg.to_lowercase());
770 } else {
771 normalized.push(arg.clone());
772 }
773 }
774
775 // Map `devp daemon|hook|icon [ARGS...]` -> `devp config daemon|hook|icon [ARGS...]`
776 //
777 // These live under `config` because that is where the rest of the persistent
778 // settings live, but nobody types `devp config hook install` when they mean
779 // "install the hook" — and the tool's own output has always said `devp hook
780 // install`. Accepting both costs one insert and removes a papercut.
781 if matches!(normalized[1].as_str(), "daemon" | "hook" | "icon") {
782 normalized.insert(1, "config".to_string());
783 }
784
785 // Map `devp status [PATH] daemon` -> `devp config daemon [PATH] status`
786 // Map `devp status [PATH] hook` -> `devp config hook [PATH] status`
787 //
788 // Exactly one optional PATH, and never a flag: `devp status --json daemon` must
789 // reach clap as typed and fail there, not be rewritten with `--json` as a path.
790 if normalized[1] == "status"
791 && (normalized.len() == 3 || (normalized.len() == 4 && !normalized[2].starts_with('-')))
792 {
793 let last = normalized
794 .last()
795 .map(|s| s.to_lowercase())
796 .unwrap_or_default();
797 if last == "daemon" || last == "hook" {
798 let mut rewrited = vec![normalized[0].clone(), "config".to_string(), last];
799 if normalized.len() > 3 {
800 rewrited.push(normalized[2].clone());
801 }
802 rewrited.push("status".to_string());
803 return rewrited;
804 }
805 }
806
807 // Map `devp config [PATH] daemon [ACTION]` -> `devp config daemon [PATH] [ACTION]`
808 // Map `devp config [PATH] hook [ACTION]` -> `devp config hook [PATH] [ACTION]`
809 //
810 // Only when the second argument can actually be a path — a flag there means the
811 // user is talking to `config` itself and the rewrite would misfile it.
812 if normalized.len() >= 4 && normalized[1] == "config" && !normalized[2].starts_with('-') {
813 let third = normalized[3].to_lowercase();
814 if third == "daemon" || third == "hook" {
815 let mut rewrited = vec![
816 normalized[0].clone(),
817 "config".to_string(),
818 third,
819 normalized[2].clone(),
820 ];
821 for extra in &normalized[4..] {
822 rewrited.push(extra.clone());
823 }
824 return rewrited;
825 }
826 }
827
828 normalized
829}
830
831/// Whether the automatic setup pass may run for this invocation.
832///
833/// Two callers are excluded on purpose. The Git hook runs `link --quiet` with no
834/// terminal attached and inside someone's commit; the scheduler runs `run --daemon` the
835/// same way. An integration pass nobody can see is one nobody can refuse, so both wait
836/// for the next command a human types. `uninstall` is excluded for the obvious reason,
837/// and `setup` because it is the pass, run deliberately.
838fn auto_setup_allowed(args: &[String]) -> bool {
839 let subcommand = args.get(1).map(String::as_str).unwrap_or("");
840 // `--json` means a program is parsing stdout; the setup report and the first-run
841 // wizard would land inside the document. That invocation waits too.
842 !matches!(subcommand, "uninstall" | "setup")
843 && !args
844 .iter()
845 .any(|a| a == "--quiet" || a == "--daemon" || a == "--json")
846}
847
848/// Run the CLI application.
849pub fn run_cli() {
850 restore_sigpipe();
851
852 let args = normalize_args();
853 if auto_setup_allowed(&args) {
854 setup::auto_setup_if_due();
855 }
856 let cli = Cli::parse_from(args);
857
858 // After parsing, so `--version` and `--help` never pay for it, and before anything
859 // is printed, because every heading past this line is drawn in whatever it settles
860 // on. `Registry::load` is a pure read, and a registry that will not load is not a
861 // reason to refuse to print in English — the command below reports that failure
862 // properly.
863 i18n::init(
864 config::Registry::load()
865 .ok()
866 .map(|registry| registry.settings.language)
867 .as_deref(),
868 );
869
870 // Both spellings mean the same thing; the old one just says so first.
871 let ignore_idle = cli.ignore_idle || cli.force;
872 if cli.force {
873 print_force_help();
874 }
875
876 // Decided before the match, because that is where `cli.command` is consumed.
877 let credit_the_author = !cli.command.suppresses_attribution();
878
879 // Every path the user typed passes through `expand_tilde` on the way in. PowerShell
880 // and cmd hand us `~/Code` verbatim, so without this the documented one-liner
881 // registers a directory literally named `~`.
882 let result = match cli.command {
883 Commands::Init { paths, auto } => {
884 let paths: Vec<String> = paths.iter().map(|p| config::expand_tilde(p)).collect();
885 commands::init::run(&paths, cli.dry_run, auto)
886 }
887 Commands::Link { path, quiet } => {
888 commands::link::run_link(&config::expand_tilde(&path), quiet)
889 }
890 Commands::Unlink { path, missing } => {
891 if missing {
892 commands::link::run_unlink_missing()
893 } else {
894 commands::link::run_unlink(&config::expand_tilde(&path))
895 }
896 }
897 Commands::Undo => commands::undo::run(),
898 Commands::Run {
899 target_path,
900 daemon,
901 only,
902 skip,
903 min_size,
904 except,
905 json,
906 explain,
907 } => {
908 let target_path = target_path.map(|p| config::expand_tilde(&p));
909 commands::run::run(commands::run::RunArgs {
910 target_path: target_path.as_deref(),
911 dry_run: cli.dry_run,
912 force: ignore_idle,
913 yes: cli.yes,
914 daemon,
915 only: only.as_deref(),
916 skip: skip.as_deref(),
917 min_size_mb: min_size,
918 except: except.as_deref(),
919 json,
920 explain,
921 })
922 }
923 Commands::Status { top, drift, json } => {
924 commands::status::run(top.map(|n| n as usize), drift, json)
925 }
926 Commands::History {
927 pass,
928 limit,
929 all,
930 json,
931 export,
932 } => commands::history::run(&commands::history::HistoryArgs {
933 pass,
934 limit,
935 all,
936 json,
937 export,
938 }),
939 Commands::Stats { json } => commands::stats::run(json),
940 Commands::Completions { shell } => commands::completions::run(shell),
941 Commands::Man { command, dir, roff } => {
942 commands::man::run(command.as_deref(), dir.as_deref(), roff)
943 }
944 Commands::Trust {
945 json,
946 fix_ownership,
947 yes,
948 } => {
949 if fix_ownership {
950 commands::trust::fix_ownership(yes)
951 } else {
952 commands::trust::run(json)
953 }
954 }
955 Commands::Caches {
956 json,
957 volume,
958 action,
959 } => match action {
960 // Refused rather than ignored. `--volume` reads as "act on this drive
961 // only", and a `clear` that silently emptied every drive after being
962 // handed one would be the worst possible way to learn the flag does not
963 // reach here.
964 Some(_) if volume.is_some() => Err(anyhow::Error::new(UsageError(
965 "`--volume` narrows the report and has nothing to narrow in a subcommand. \
966 Run `devp caches --volume <VOLUME>` on its own to see what is on one \
967 drive; `devp caches clear <manager>` then empties that manager \
968 wherever it is."
969 .to_string(),
970 ))),
971 Some(CachesAction::Clear {
972 target,
973 over_cap,
974 unused,
975 }) => {
976 commands::caches::run_clear(&target, over_cap, unused, cli.yes, cli.dry_run, json)
977 }
978 Some(CachesAction::Docker) => commands::containers::run(Some("docker"), json),
979 Some(CachesAction::Podman) => commands::containers::run(Some("podman"), json),
980 Some(CachesAction::Containers { engine }) => {
981 commands::containers::run(engine.as_deref(), json)
982 }
983 None => commands::caches::run(json, volume.as_deref()),
984 },
985 Commands::Config { action } => match action {
986 Some(ConfigAction::Get { key }) => commands::config::run_get(&key),
987 Some(ConfigAction::Set { key, value }) => commands::config::run_set(&key, &value),
988 Some(ConfigAction::Show { update: true }) => commands::config::run_global_update(),
989 Some(ConfigAction::Show { update: false }) | None => commands::config::run_show(),
990 Some(ConfigAction::Recommended { with_cautious }) => {
991 commands::config::run_recommended(with_cautious)
992 }
993 Some(ConfigAction::Project { path, update, team }) => {
994 commands::config::run_path_config(&config::expand_tilde(&path), update, team)
995 }
996 Some(ConfigAction::Daemon { target, sub_action }) => {
997 // A toggle word (`on`, `off`) never starts with `~`, so expanding the
998 // target before the match cannot turn one into a path.
999 let target = target.map(|t| config::expand_tilde(&t));
1000 let (path, action) = match (target.as_deref(), sub_action.as_deref()) {
1001 (Some(t), Some(a)) => (Some(t), a),
1002 (Some(t), None) if commands::config::is_toggle_word(t) => (None, t),
1003 (Some(t), None) => (Some(t), "status"),
1004 (None, Some(a)) => (None, a),
1005 (None, None) => (None, "status"),
1006 };
1007 commands::config::run_daemon_toggle(path, action)
1008 }
1009 Some(ConfigAction::Hook {
1010 target,
1011 sub_action,
1012 chain,
1013 }) => {
1014 let target = target.map(|t| config::expand_tilde(&t));
1015 let (path, action) = match (target.as_deref(), sub_action.as_deref()) {
1016 (Some(t), Some(a)) => (Some(t), a),
1017 (Some(t), None) if commands::config::is_toggle_word(t) => (None, t),
1018 (Some(t), None) => (Some(t), "status"),
1019 (None, Some(a)) => (None, a),
1020 // `--chain` on its own is an install instruction, not a status query.
1021 (None, None) if chain => (None, "install"),
1022 (None, None) => (None, "status"),
1023 };
1024 commands::config::run_hook_toggle(path, action, chain)
1025 }
1026 Some(ConfigAction::Icon) => commands::icon::run_install(),
1027 Some(ConfigAction::Wizard { no_tui }) => {
1028 commands::config::run_wizard(no_tui, commands::config::Opened::ByRequest)
1029 .map(|_| ())
1030 }
1031 },
1032 Commands::Restore { path, last_run } => {
1033 if last_run {
1034 commands::restore::run_last_run()
1035 } else {
1036 commands::restore::run(&config::expand_tilde(path.as_deref().unwrap_or(".")))
1037 }
1038 }
1039 Commands::Update {
1040 offline,
1041 install,
1042 channels,
1043 } => commands::update::run(offline, install, channels),
1044 Commands::Skill { agent } => commands::skill::run(agent),
1045 Commands::Setup { status } => commands::setup::run(status),
1046 Commands::Doctor { path, fix } => {
1047 let path = path.map(|p| config::expand_tilde(&p));
1048 commands::doctor::run(path.as_deref(), fix)
1049 }
1050 Commands::Install { channel, dry_run } => commands::install::run(channel, dry_run, cli.yes),
1051 Commands::Uninstall { deep } => commands::uninstall::run(deep, cli.yes),
1052 };
1053
1054 if let Err(e) = result {
1055 if is_broken_pipe(&e) {
1056 std::process::exit(exit_code::OK);
1057 }
1058 output::print_error(&format!("{e:#}"));
1059 if e.downcast_ref::<UsageError>().is_some() {
1060 std::process::exit(exit_code::USAGE);
1061 }
1062 std::process::exit(exit_code::FAILURE);
1063 }
1064
1065 // Only on the way out of a successful run: nobody reading an error message needs a
1066 // credit under it.
1067 if credit_the_author {
1068 output::print_attribution();
1069 }
1070}
1071
1072#[cfg(test)]
1073mod tests {
1074 use super::auto_setup_allowed;
1075
1076 fn args(rest: &[&str]) -> Vec<String> {
1077 std::iter::once("devp")
1078 .chain(rest.iter().copied())
1079 .map(String::from)
1080 .collect()
1081 }
1082
1083 #[test]
1084 fn ordinary_interactive_commands_may_auto_setup() {
1085 assert!(auto_setup_allowed(&args(&["status"])));
1086 assert!(auto_setup_allowed(&args(&["run", "--dry-run"])));
1087 assert!(auto_setup_allowed(&args(&[])));
1088 }
1089
1090 #[test]
1091 fn unattended_and_machine_read_invocations_may_not() {
1092 // The Git hook, the scheduler, and any `--json` consumer: a setup pass nobody
1093 // can see is one nobody can refuse, and setup output inside a JSON document is
1094 // a parse error.
1095 assert!(!auto_setup_allowed(&args(&["link", ".", "--quiet"])));
1096 assert!(!auto_setup_allowed(&args(&["run", "--daemon"])));
1097 assert!(!auto_setup_allowed(&args(&["status", "--json"])));
1098 assert!(!auto_setup_allowed(&args(&["uninstall"])));
1099 assert!(!auto_setup_allowed(&args(&["setup"])));
1100 }
1101}