cleanix-cli 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. cleanix/__init__.py +4 -0
  2. cleanix/__main__.py +6 -0
  3. cleanix/cleaners/__init__.py +269 -0
  4. cleanix/cleaners/ai_cli.py +193 -0
  5. cleanix/cleaners/ai_tools.py +224 -0
  6. cleanix/cleaners/app_cruft.py +201 -0
  7. cleanix/cleaners/apple_litter.py +41 -0
  8. cleanix/cleaners/apps.py +89 -0
  9. cleanix/cleaners/apt.py +70 -0
  10. cleanix/cleaners/base.py +173 -0
  11. cleanix/cleaners/broken_symlinks.py +51 -0
  12. cleanix/cleaners/browsers.py +68 -0
  13. cleanix/cleaners/bsd.py +108 -0
  14. cleanix/cleaners/containers.py +82 -0
  15. cleanix/cleaners/coredumps.py +32 -0
  16. cleanix/cleaners/desktop_extras.py +42 -0
  17. cleanix/cleaners/dev_caches.py +57 -0
  18. cleanix/cleaners/distro_pkg.py +127 -0
  19. cleanix/cleaners/dnf.py +56 -0
  20. cleanix/cleaners/editor_litter.py +115 -0
  21. cleanix/cleaners/font_cache.py +29 -0
  22. cleanix/cleaners/ide.py +87 -0
  23. cleanix/cleaners/kernels.py +115 -0
  24. cleanix/cleaners/lang_caches.py +70 -0
  25. cleanix/cleaners/linux_extras.py +77 -0
  26. cleanix/cleaners/localizations.py +70 -0
  27. cleanix/cleaners/logs.py +80 -0
  28. cleanix/cleaners/macos.py +166 -0
  29. cleanix/cleaners/macos_extra.py +125 -0
  30. cleanix/cleaners/memory.py +110 -0
  31. cleanix/cleaners/more_pkg.py +168 -0
  32. cleanix/cleaners/npm_cache.py +36 -0
  33. cleanix/cleaners/packaging_extras.py +140 -0
  34. cleanix/cleaners/pacman.py +63 -0
  35. cleanix/cleaners/pip_cache.py +27 -0
  36. cleanix/cleaners/snapshots.py +126 -0
  37. cleanix/cleaners/sys_extras.py +109 -0
  38. cleanix/cleaners/temp_files.py +48 -0
  39. cleanix/cleaners/thumbnails.py +31 -0
  40. cleanix/cleaners/trash.py +47 -0
  41. cleanix/cleaners/user_cache.py +69 -0
  42. cleanix/cleaners/virtualization.py +76 -0
  43. cleanix/cli.py +810 -0
  44. cleanix/completion.py +131 -0
  45. cleanix/config.py +225 -0
  46. cleanix/core/__init__.py +1 -0
  47. cleanix/core/context.py +147 -0
  48. cleanix/core/engine.py +155 -0
  49. cleanix/core/history.py +55 -0
  50. cleanix/core/models.py +141 -0
  51. cleanix/core/platform.py +117 -0
  52. cleanix/core/quarantine.py +147 -0
  53. cleanix/core/registry.py +58 -0
  54. cleanix/core/report.py +130 -0
  55. cleanix/core/safety.py +166 -0
  56. cleanix/core/utils.py +244 -0
  57. cleanix/reset.py +328 -0
  58. cleanix/scheduler/__init__.py +1 -0
  59. cleanix/scheduler/systemd.py +160 -0
  60. cleanix_cli-1.0.1.dist-info/METADATA +436 -0
  61. cleanix_cli-1.0.1.dist-info/RECORD +64 -0
  62. cleanix_cli-1.0.1.dist-info/WHEEL +5 -0
  63. cleanix_cli-1.0.1.dist-info/entry_points.txt +2 -0
  64. cleanix_cli-1.0.1.dist-info/top_level.txt +1 -0
cleanix/cli.py ADDED
@@ -0,0 +1,810 @@
1
+ """Command-line interface for cleanix.
2
+
3
+ Subcommands:
4
+ list show available cleaners
5
+ scan analyze the system (read-only)
6
+ clean remove junk (dry-run unless --execute; confirmation required)
7
+ schedule install/uninstall/status of the systemd analysis timer
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import sys
14
+ from pathlib import Path
15
+ from typing import List, Optional
16
+
17
+ from rich.console import Console
18
+ from rich.prompt import Confirm, Prompt
19
+
20
+ from cleanix import __version__
21
+ from cleanix.config import Config
22
+ from cleanix.core.engine import Engine
23
+ from cleanix.core.models import ScanResult
24
+ from cleanix.core.registry import build_cleaners, describe_all, unknown_ids
25
+ from cleanix.core.report import (
26
+ render_clean_summary,
27
+ render_report_only,
28
+ render_scan_table,
29
+ scan_to_json,
30
+ )
31
+ from cleanix.core.utils import human_size, is_root
32
+
33
+
34
+ def _split_csv(value: Optional[str]) -> Optional[List[str]]:
35
+ if not value:
36
+ return None
37
+ return [v.strip() for v in value.split(",") if v.strip()]
38
+
39
+
40
+ def _load_config() -> Config:
41
+ return Config.load()
42
+
43
+
44
+ def _configure_scope(args: argparse.Namespace) -> None:
45
+ """Decide whose homes to scan and apply it to the context layer."""
46
+ from cleanix.core import context
47
+
48
+ all_users: Optional[bool] = None # None => all users iff root
49
+ if getattr(args, "all_users", False):
50
+ all_users = True
51
+ elif getattr(args, "current_user", False):
52
+ all_users = False
53
+ context.configure(all_users=all_users, min_uid=getattr(args, "min_uid", None))
54
+
55
+
56
+ def _scope_note(console: Console) -> None:
57
+ from cleanix.core import context
58
+
59
+ if context.scanning_all_users():
60
+ users = context.get_target_users()
61
+ names = ", ".join(u.name for u in users)
62
+ console.print(
63
+ f"[cyan]Scanning {len(users)} users system-wide:[/cyan] {names}"
64
+ )
65
+ elif not context.is_effective_root():
66
+ # Hint that more is available with sudo.
67
+ pass
68
+
69
+
70
+ def _make_engine(
71
+ config: Config, only: Optional[List[str]], exclude: Optional[List[str]]
72
+ ) -> Engine:
73
+ for group in (only, exclude):
74
+ if group:
75
+ bad = unknown_ids(group)
76
+ if bad:
77
+ raise SystemExit(
78
+ f"unknown cleaner id(s): {', '.join(bad)}. "
79
+ f"Run `cleanix list` to see valid ids."
80
+ )
81
+ # Apply the user's extra protected-paths to the safety guard.
82
+ from cleanix.core import safety
83
+ safety.set_protected_globs(config.protected_globs)
84
+
85
+ cleaners = build_cleaners(config, only=only, exclude=exclude)
86
+ if not cleaners:
87
+ raise SystemExit("no cleaners selected")
88
+ return Engine(cleaners)
89
+
90
+
91
+ def _scan(engine: Engine, console: Console, *, quiet: bool = False):
92
+ """Scan with a live progress bar when attached to a terminal."""
93
+ if quiet or not console.is_terminal:
94
+ return engine.scan()
95
+ from rich.progress import (
96
+ BarColumn,
97
+ Progress,
98
+ SpinnerColumn,
99
+ TextColumn,
100
+ )
101
+
102
+ with Progress(
103
+ SpinnerColumn(),
104
+ TextColumn("[progress.description]{task.description}"),
105
+ BarColumn(),
106
+ TextColumn("{task.completed}/{task.total}"),
107
+ console=console,
108
+ transient=True,
109
+ ) as progress:
110
+ task = progress.add_task("Scanning", total=len(engine.cleaners))
111
+
112
+ def cb(name: str) -> None:
113
+ progress.update(task, advance=1, description=f"Scanning {name}")
114
+
115
+ return engine.scan(progress=cb)
116
+
117
+
118
+ # -- commands ---------------------------------------------------------------
119
+ def cmd_list(args: argparse.Namespace, console: Console) -> int:
120
+ from rich.table import Table
121
+
122
+ from cleanix.core.platform import ALL, os_label
123
+
124
+ config = _load_config()
125
+ table = Table(title=f"Cleaners (this system: {os_label()})")
126
+ table.add_column("id", style="cyan")
127
+ table.add_column("name")
128
+ table.add_column("root?", justify="center")
129
+ table.add_column("platforms", style="magenta")
130
+ table.add_column("here?", justify="center")
131
+ table.add_column("description", style="dim")
132
+ for cid, cleaner in describe_all(config).items():
133
+ plats = "all" if ALL in cleaner.platforms else ",".join(cleaner.platforms)
134
+ here = cleaner.supported()
135
+ if not args.all and not here:
136
+ continue
137
+ table.add_row(
138
+ cid,
139
+ cleaner.name,
140
+ "yes" if cleaner.requires_root else "no",
141
+ plats,
142
+ "[green]✓[/green]" if here else "[dim]–[/dim]",
143
+ cleaner.description,
144
+ )
145
+ console.print(table)
146
+ if not args.all:
147
+ console.print(
148
+ "[dim]Showing cleaners for this OS. Use --all to list every "
149
+ "platform's cleaners.[/dim]"
150
+ )
151
+ return 0
152
+
153
+
154
+ def _run_scan(args: argparse.Namespace, console: Console) -> ScanResult:
155
+ _configure_scope(args)
156
+ config = _load_config()
157
+ engine = _make_engine(config, _split_csv(args.only), _split_csv(args.exclude))
158
+ return _scan(engine, console, quiet=args.summary or args.json)
159
+
160
+
161
+ def cmd_scan(args: argparse.Namespace, console: Console) -> int:
162
+ result = _run_scan(args, console)
163
+
164
+ if not args.summary and not args.json:
165
+ _scope_note(console)
166
+
167
+ if args.summary:
168
+ # One-liner, e.g. for desktop notifications.
169
+ print(
170
+ f"{result.total_items} item(s), "
171
+ f"{human_size(result.total_size)} reclaimable"
172
+ )
173
+ return 0
174
+
175
+ if args.json:
176
+ payload = scan_to_json(result)
177
+ if args.output:
178
+ Path(args.output).expanduser().write_text(payload)
179
+ if not args.quiet:
180
+ console.print(f"[green]Wrote report to {args.output}[/green]")
181
+ else:
182
+ print(payload)
183
+ return 0
184
+
185
+ if not args.quiet:
186
+ render_scan_table(
187
+ result, console,
188
+ sort=getattr(args, "sort", "none"),
189
+ top=getattr(args, "top", 0),
190
+ )
191
+ if result.report_only_items():
192
+ console.print()
193
+ render_report_only(result, console)
194
+ if result.cleanable_items():
195
+ console.print(
196
+ "\nRun [bold]cleanix clean[/bold] to preview removal, or "
197
+ "[bold]cleanix clean --execute[/bold] to reclaim this space."
198
+ )
199
+ return 0
200
+
201
+
202
+ def cmd_clean(args: argparse.Namespace, console: Console) -> int:
203
+ _configure_scope(args)
204
+ config = _load_config()
205
+ engine = _make_engine(config, _split_csv(args.only), _split_csv(args.exclude))
206
+
207
+ _scope_note(console)
208
+ scan = _scan(engine, console)
209
+
210
+ if scan.total_items == 0:
211
+ console.print("[green]Nothing to clean — system is tidy.[/green]")
212
+ return 0
213
+
214
+ render_scan_table(scan, console)
215
+ if scan.report_only_items():
216
+ console.print()
217
+ render_report_only(scan, console)
218
+
219
+ # Report-only items are never deleted — exclude them from the clean set.
220
+ items = scan.cleanable_items()
221
+ if not items:
222
+ console.print(
223
+ "\n[green]Nothing to clean.[/green] (Any findings above are "
224
+ "report-only and must be removed manually.)"
225
+ )
226
+ return 0
227
+ root_items = [i for i in items if i.requires_root]
228
+ if root_items and not is_root():
229
+ console.print(
230
+ f"\n[yellow]{len(root_items)} item(s) require root and will be "
231
+ f"skipped. Re-run with sudo to include them.[/yellow]"
232
+ )
233
+
234
+ dry_run = not args.execute
235
+ if dry_run:
236
+ result = engine.clean(items, dry_run=True)
237
+ console.print()
238
+ render_clean_summary(result, console)
239
+ console.print(
240
+ "\n[dim]This was a dry run. Add [bold]--execute[/bold] to actually "
241
+ "remove these items.[/dim]"
242
+ )
243
+ return 0
244
+
245
+ # Real deletion — require confirmation unless --yes.
246
+ if not args.yes:
247
+ console.print()
248
+ confirmed = Confirm.ask(
249
+ f"Permanently remove {len(items)} item(s) and reclaim up to "
250
+ f"{human_size(scan.cleanable_size)}?",
251
+ default=False,
252
+ )
253
+ if not confirmed:
254
+ console.print("Aborted. Nothing was deleted.")
255
+ return 1
256
+
257
+ quarantine = None
258
+ if args.quarantine:
259
+ from cleanix.core import quarantine as qmod
260
+ quarantine = qmod.new_run()
261
+
262
+ with console.status("Cleaning..."):
263
+ result = engine.clean(items, dry_run=False, quarantine=quarantine)
264
+ console.print()
265
+ render_clean_summary(result, console)
266
+
267
+ # Record history and finalize quarantine.
268
+ from cleanix.core import history
269
+ history.record(result.freed, result.removed_count,
270
+ mode="quarantine" if quarantine else "delete")
271
+ if quarantine is not None and quarantine.items:
272
+ quarantine.save()
273
+ console.print(
274
+ f"\n[cyan]Moved {len(quarantine.items)} item(s) to quarantine "
275
+ f"'{quarantine.run_id}'.[/cyan] Space is reclaimed once you run "
276
+ f"[bold]cleanix quarantine empty[/bold]; undo with "
277
+ f"[bold]cleanix restore[/bold]."
278
+ )
279
+ return 0 if not result.errors else 2
280
+
281
+
282
+ def cmd_config(args: argparse.Namespace, console: Console) -> int:
283
+ from rich.table import Table
284
+
285
+ from cleanix import config as cfgmod
286
+
287
+ action = args.config_action
288
+ path = cfgmod.config_file_path()
289
+
290
+ if action == "path":
291
+ console.print(str(path))
292
+ return 0
293
+
294
+ if action == "list":
295
+ overrides = cfgmod.read_user_overrides()
296
+ effective = Config.load()
297
+ defaults = Config()
298
+ table = Table(title=f"Cleanix configuration ({path})")
299
+ table.add_column("key", style="cyan")
300
+ table.add_column("value", style="green")
301
+ table.add_column("source")
302
+ table.add_column("description", style="dim")
303
+ for name in cfgmod.field_names():
304
+ value = getattr(effective, name)
305
+ overridden = name in overrides
306
+ table.add_row(
307
+ name,
308
+ _fmt_value(value),
309
+ "[yellow]set[/yellow]" if overridden else "default",
310
+ cfgmod.FIELD_HELP.get(name, ""),
311
+ )
312
+ console.print(table)
313
+ return 0
314
+
315
+ if action == "get":
316
+ effective = Config.load()
317
+ if args.key not in cfgmod.field_names():
318
+ console.print(f"[red]unknown key: {args.key}[/red]")
319
+ return 1
320
+ console.print(_fmt_value(getattr(effective, args.key)))
321
+ return 0
322
+
323
+ if action == "set":
324
+ try:
325
+ value = cfgmod.coerce_value(args.key, args.value)
326
+ except KeyError:
327
+ console.print(f"[red]unknown key: {args.key}[/red]")
328
+ return 1
329
+ except ValueError as exc:
330
+ console.print(f"[red]{exc}[/red]")
331
+ return 1
332
+ cfgmod.write_user_override(args.key, value)
333
+ console.print(f"[green]{args.key}[/green] = {_fmt_value(value)} ({path})")
334
+ return 0
335
+
336
+ if action == "unset":
337
+ if cfgmod.remove_user_override(args.key):
338
+ console.print(f"[green]reverted {args.key} to its default[/green]")
339
+ else:
340
+ console.print(f"[dim]{args.key} was not overridden[/dim]")
341
+ return 0
342
+
343
+ return 1
344
+
345
+
346
+ def _fmt_value(value) -> str:
347
+ if isinstance(value, bool):
348
+ return "true" if value else "false"
349
+ if isinstance(value, list):
350
+ return ", ".join(str(v) for v in value) if value else "[]"
351
+ return str(value)
352
+
353
+
354
+ def _run_reset_command(cmd: List[str]) -> int:
355
+ """Execute a reset command with inherited stdio (patchable for tests)."""
356
+ import subprocess
357
+
358
+ return subprocess.run(cmd).returncode
359
+
360
+
361
+ def _execute_reset(args: argparse.Namespace, console: Console, plan) -> int:
362
+ import sys as _sys
363
+
364
+ from cleanix import reset as resetmod
365
+
366
+ # 1) Only reversible strategies with defined actions may execute.
367
+ if not plan.reversible or not plan.actions:
368
+ console.print(
369
+ "\n[red]Execution is only available on reversible systems[/red] "
370
+ "(NixOS, rpm-ostree, openSUSE MicroOS, Guix). This system's reset is "
371
+ "not reversible, so cleanix will not run it — use the plan above with "
372
+ "a snapshot restore or reinstall."
373
+ )
374
+ return 1
375
+
376
+ # 2) Show exactly what will run and how to undo it.
377
+ from rich.panel import Panel
378
+
379
+ lines = []
380
+ for a in plan.actions:
381
+ lines.append(f"[cyan]$ {' '.join(a.command)}[/cyan]")
382
+ lines.append(f" [dim]{a.description}[/dim]")
383
+ if a.undo:
384
+ lines.append(f" [dim]undo: {a.undo}[/dim]")
385
+ console.print(
386
+ Panel("\n".join(lines), title="Reversible actions to execute",
387
+ border_style="red")
388
+ )
389
+
390
+ # 3) Privilege check.
391
+ needs_root = any(a.requires_root for a in plan.actions)
392
+ if needs_root and not is_root():
393
+ console.print(
394
+ "[red]These actions require root — re-run with sudo.[/red]"
395
+ )
396
+ return 1
397
+
398
+ # 4) Refuse non-interactive execution; require a typed confirmation phrase.
399
+ if not _sys.stdin.isatty():
400
+ console.print(
401
+ "[red]Refusing to reset non-interactively.[/red] Run in a terminal."
402
+ )
403
+ return 1
404
+ phrase = resetmod.confirmation_phrase()
405
+ console.print(
406
+ "\n[bold red]This will change your system state.[/bold red] It is "
407
+ "reversible (see 'undo' above), but take a snapshot first if unsure."
408
+ )
409
+ answer = Prompt.ask(f'Type [bold]{phrase}[/bold] to proceed (anything else aborts)')
410
+ if answer.strip() != phrase:
411
+ console.print("Aborted. Nothing was changed.")
412
+ return 1
413
+
414
+ # 5) Run.
415
+ results = resetmod.execute_actions(plan, _run_reset_command)
416
+ failed = [(a, c) for a, c in results if c != 0]
417
+ for a, c in results:
418
+ status = "[green]ok[/green]" if c == 0 else f"[red]failed (exit {c})[/red]"
419
+ console.print(f" {status}: {' '.join(a.command)}")
420
+ if failed:
421
+ console.print("[red]Reset stopped on failure.[/red]")
422
+ return 2
423
+ console.print(
424
+ "\n[green]Reset actions completed.[/green] Reboot to boot the reset "
425
+ "state; use the 'undo' commands above to revert if needed."
426
+ )
427
+ return 0
428
+
429
+
430
+ def cmd_factory_reset(args: argparse.Namespace, console: Console) -> int:
431
+ from rich.panel import Panel
432
+
433
+ from cleanix.reset import build_plan
434
+
435
+ plan = build_plan(args.scope)
436
+ rev = (
437
+ "[green]reversible[/green]" if plan.reversible
438
+ else "[red]NOT reversible[/red]"
439
+ )
440
+ console.print(
441
+ Panel(
442
+ f"[bold]Detected:[/bold] {plan.strategy} ({rev})\n\n{plan.summary}",
443
+ title="Factory-reset plan (advisory — cleanix will NOT run these)",
444
+ border_style="red",
445
+ )
446
+ )
447
+ console.print("\n[bold]Before you start:[/bold]")
448
+ for pre in plan.prerequisites:
449
+ console.print(f" [yellow]•[/yellow] {pre}")
450
+
451
+ for i, tier in enumerate(plan.tiers, 1):
452
+ body = f"[dim]{tier.warning}[/dim]\n"
453
+ for step in tier.steps:
454
+ if step.startswith(" ") or any(
455
+ step.startswith(c) for c in ("sudo ", "rm ", "tar ", "cleanix ",
456
+ "rpm-ostree", "snapper", "guix",
457
+ "nixos", "apt", "dnf", "pacman",
458
+ "flatpak", "ostree", "System Settings")
459
+ ):
460
+ body += f"\n [cyan]$ {step.strip()}[/cyan]"
461
+ else:
462
+ body += f"\n {step}"
463
+ console.print(Panel(body, title=f"Tier {i}: {tier.title}", border_style="yellow"))
464
+
465
+ if args.execute:
466
+ return _execute_reset(args, console, plan)
467
+
468
+ if plan.reversible and plan.actions:
469
+ console.print(
470
+ "\n[dim]This is a plan. To have cleanix run the reversible "
471
+ "rollback for you, re-run with [bold]--execute[/bold].[/dim]"
472
+ )
473
+ else:
474
+ console.print(
475
+ "\n[dim]This is a plan only. This system's reset is not reversible, "
476
+ "so cleanix will not run it — use a snapshot restore or reinstall.[/dim]"
477
+ )
478
+ return 0
479
+
480
+
481
+ def _fmt_time(ts: float) -> str:
482
+ import datetime as _dt
483
+
484
+ if not ts:
485
+ return "never"
486
+ return _dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
487
+
488
+
489
+ def cmd_info(args: argparse.Namespace, console: Console) -> int:
490
+ import platform as _plat
491
+
492
+ from rich.table import Table
493
+
494
+ from cleanix import __version__, config as cfgmod
495
+ from cleanix.core import context, history, quarantine
496
+ from cleanix.core.platform import current_distro, os_label
497
+ from cleanix.core.registry import describe_all
498
+ from cleanix.core.utils import is_root, which
499
+ from cleanix.cleaners.base import SCOPE_SYSTEM
500
+
501
+ config = _load_config()
502
+ cleaners = describe_all(config)
503
+ applicable = [c for c in cleaners.values() if c.supported()]
504
+ sys_n = sum(1 for c in applicable if c.scope == SCOPE_SYSTEM)
505
+
506
+ pkg_mgrs = [
507
+ m for m in (
508
+ "apt-get", "dnf", "yum", "pacman", "zypper", "apk", "xbps-install",
509
+ "emerge", "eopkg", "swupd", "flatpak", "snap", "nix", "guix",
510
+ "brew", "port", "pkg", "conda", "mamba",
511
+ ) if which(m)
512
+ ]
513
+
514
+ st = history.stats()
515
+ tbl = Table(title=f"Cleanix {__version__}", show_header=False)
516
+ tbl.add_column("k", style="cyan", no_wrap=True)
517
+ tbl.add_column("v")
518
+ tbl.add_row("Operating system", f"{os_label()} (kernel {_plat.release()})")
519
+ tbl.add_row("Running as", "root" if is_root() else context.invoking_user().name)
520
+ tbl.add_row("Applicable cleaners", f"{len(applicable)} ({sys_n} system, "
521
+ f"{len(applicable)-sys_n} per-user) of {len(cleaners)} total")
522
+ tbl.add_row("Package managers", ", ".join(pkg_mgrs) or "none detected")
523
+ tbl.add_row("Config file", str(cfgmod.config_file_path()))
524
+ tbl.add_row("Lifetime cleaned", f"{human_size(st['total_freed'])} across "
525
+ f"{st['runs']} run(s); last {_fmt_time(st['last_time'])}")
526
+ tbl.add_row("Quarantine", f"{human_size(quarantine.total_size())} in "
527
+ f"{len(quarantine.list_runs())} run(s)")
528
+ console.print(tbl)
529
+ return 0
530
+
531
+
532
+ def cmd_stats(args: argparse.Namespace, console: Console) -> int:
533
+ from cleanix.core import history
534
+
535
+ st = history.stats()
536
+ console.print(
537
+ f"[green]Lifetime:[/green] {human_size(st['total_freed'])} freed across "
538
+ f"{st['total_items']} item(s) in {st['runs']} run(s)."
539
+ )
540
+ for e in st["entries"][-10:]:
541
+ console.print(
542
+ f" {_fmt_time(e.get('time', 0))} "
543
+ f"{human_size(e.get('freed', 0)):>10} "
544
+ f"{e.get('items', 0):>4} items ({e.get('mode', 'delete')})"
545
+ )
546
+ return 0
547
+
548
+
549
+ def cmd_restore(args: argparse.Namespace, console: Console) -> int:
550
+ from cleanix.core import quarantine
551
+
552
+ run_id = args.run_id or quarantine.latest_run()
553
+ if not run_id:
554
+ console.print("[yellow]Nothing in quarantine to restore.[/yellow]")
555
+ return 1
556
+ try:
557
+ res = quarantine.restore(run_id)
558
+ except FileNotFoundError as exc:
559
+ console.print(f"[red]{exc}[/red]")
560
+ return 1
561
+ console.print(
562
+ f"[green]Restored {len(res['restored'])} item(s)[/green] from '{run_id}'."
563
+ )
564
+ for path, why in res["failed"]:
565
+ console.print(f" [red]![/red] {path}: {why}")
566
+ return 0 if not res["failed"] else 2
567
+
568
+
569
+ def cmd_quarantine(args: argparse.Namespace, console: Console) -> int:
570
+ from rich.table import Table
571
+
572
+ from cleanix.core import quarantine
573
+
574
+ if args.quarantine_action == "list":
575
+ runs = quarantine.list_runs()
576
+ if not runs:
577
+ console.print("[dim]Quarantine is empty.[/dim]")
578
+ return 0
579
+ tbl = Table(title="Quarantine runs")
580
+ tbl.add_column("run id", style="cyan")
581
+ tbl.add_column("when")
582
+ tbl.add_column("items", justify="right")
583
+ tbl.add_column("size", justify="right", style="green")
584
+ for r in runs:
585
+ tbl.add_row(r["run_id"], _fmt_time(r["created"]),
586
+ str(r["count"]), human_size(r["size"]))
587
+ console.print(tbl)
588
+ return 0
589
+
590
+ # empty
591
+ if args.all or not args.run_id:
592
+ freed = quarantine.purge_all()
593
+ console.print(f"[green]Emptied quarantine, reclaimed {human_size(freed)}.[/green]")
594
+ else:
595
+ freed = quarantine.purge(args.run_id)
596
+ console.print(f"[green]Removed run '{args.run_id}', reclaimed {human_size(freed)}.[/green]")
597
+ return 0
598
+
599
+
600
+ def cmd_completion(args: argparse.Namespace, console: Console) -> int:
601
+ from cleanix.completion import generate
602
+
603
+ # Print raw script to stdout so it can be redirected/sourced.
604
+ print(generate(args.shell))
605
+ return 0
606
+
607
+
608
+ def cmd_schedule(args: argparse.Namespace, console: Console) -> int:
609
+ from cleanix.scheduler import systemd
610
+
611
+ try:
612
+ if args.action == "install":
613
+ console.print(systemd.install(args.frequency))
614
+ elif args.action == "uninstall":
615
+ console.print(systemd.uninstall())
616
+ else: # status
617
+ console.print(systemd.status())
618
+ except (RuntimeError, ValueError) as exc:
619
+ console.print(f"[red]{exc}[/red]")
620
+ return 1
621
+ return 0
622
+
623
+
624
+ # -- parser -----------------------------------------------------------------
625
+ def build_parser() -> argparse.ArgumentParser:
626
+ parser = argparse.ArgumentParser(
627
+ prog="cleanix",
628
+ description="A safe, thorough scheduled system cleaner for Linux, macOS and BSD.",
629
+ )
630
+ parser.add_argument(
631
+ "--version", action="version", version=f"cleanix {__version__}"
632
+ )
633
+ sub = parser.add_subparsers(dest="command", required=True)
634
+
635
+ def add_selection(p: argparse.ArgumentParser) -> None:
636
+ p.add_argument(
637
+ "--only",
638
+ metavar="IDS",
639
+ help="comma-separated cleaner ids to include exclusively",
640
+ )
641
+ p.add_argument(
642
+ "--exclude",
643
+ metavar="IDS",
644
+ help="comma-separated cleaner ids to skip",
645
+ )
646
+ scope = p.add_mutually_exclusive_group()
647
+ scope.add_argument(
648
+ "--all-users",
649
+ action="store_true",
650
+ help="scan every user's home + the whole system (default when root)",
651
+ )
652
+ scope.add_argument(
653
+ "--current-user",
654
+ action="store_true",
655
+ help="only scan the invoking user's home (even when running as root)",
656
+ )
657
+ p.add_argument(
658
+ "--min-uid",
659
+ type=int,
660
+ default=None,
661
+ metavar="N",
662
+ help="lowest uid treated as a real user when scanning all users",
663
+ )
664
+
665
+ p_list = sub.add_parser("list", help="list available cleaners")
666
+ p_list.add_argument(
667
+ "--all",
668
+ action="store_true",
669
+ help="include cleaners for other operating systems",
670
+ )
671
+ p_list.set_defaults(func=cmd_list)
672
+
673
+ p_scan = sub.add_parser("scan", help="analyze the system (read-only)")
674
+ add_selection(p_scan)
675
+ p_scan.add_argument("--json", action="store_true", help="emit JSON")
676
+ p_scan.add_argument(
677
+ "--output", metavar="FILE", help="write JSON report to FILE"
678
+ )
679
+ p_scan.add_argument(
680
+ "--quiet", action="store_true", help="suppress the human-readable table"
681
+ )
682
+ p_scan.add_argument(
683
+ "--summary",
684
+ action="store_true",
685
+ help="print a one-line summary (for notifications)",
686
+ )
687
+ p_scan.add_argument(
688
+ "--sort",
689
+ choices=["none", "size", "name"],
690
+ default="none",
691
+ help="sort the results table",
692
+ )
693
+ p_scan.add_argument(
694
+ "--top",
695
+ type=int,
696
+ default=0,
697
+ metavar="N",
698
+ help="show only the N cleaners with the most to reclaim",
699
+ )
700
+ p_scan.set_defaults(func=cmd_scan)
701
+
702
+ p_clean = sub.add_parser(
703
+ "clean", help="remove junk (dry-run unless --execute)"
704
+ )
705
+ add_selection(p_clean)
706
+ p_clean.add_argument(
707
+ "--execute",
708
+ action="store_true",
709
+ help="actually delete (default is a dry-run preview)",
710
+ )
711
+ p_clean.add_argument(
712
+ "--yes",
713
+ action="store_true",
714
+ help="skip the confirmation prompt (implies non-interactive)",
715
+ )
716
+ p_clean.add_argument(
717
+ "--quarantine",
718
+ action="store_true",
719
+ help="move items to a reversible quarantine instead of deleting "
720
+ "(undo with `cleanix restore`)",
721
+ )
722
+ p_clean.set_defaults(func=cmd_clean)
723
+
724
+ p_sched = sub.add_parser(
725
+ "schedule", help="manage the periodic analysis timer"
726
+ )
727
+ p_sched.add_argument(
728
+ "action", choices=["install", "uninstall", "status"]
729
+ )
730
+ p_sched.add_argument(
731
+ "--frequency",
732
+ default="weekly",
733
+ choices=["hourly", "daily", "weekly", "monthly"],
734
+ help="how often to run the analysis (default: weekly)",
735
+ )
736
+ p_sched.set_defaults(func=cmd_schedule)
737
+
738
+ # config
739
+ p_cfg = sub.add_parser("config", help="view and change configuration")
740
+ cfg_sub = p_cfg.add_subparsers(dest="config_action", required=True)
741
+ cfg_sub.add_parser("list", help="show all settings, values, and sources")
742
+ cfg_sub.add_parser("path", help="print the config file path")
743
+ cfg_get = cfg_sub.add_parser("get", help="print one setting's value")
744
+ cfg_get.add_argument("key")
745
+ cfg_set = cfg_sub.add_parser("set", help="change a setting")
746
+ cfg_set.add_argument("key")
747
+ cfg_set.add_argument("value")
748
+ cfg_unset = cfg_sub.add_parser("unset", help="revert a setting to its default")
749
+ cfg_unset.add_argument("key")
750
+ p_cfg.set_defaults(func=cmd_config)
751
+
752
+ # completion
753
+ p_comp = sub.add_parser("completion", help="print a shell-completion script")
754
+ p_comp.add_argument("shell", choices=["bash", "zsh", "fish"])
755
+ p_comp.set_defaults(func=cmd_completion)
756
+
757
+ # info / stats
758
+ p_info = sub.add_parser("info", help="show environment & cleanix status")
759
+ p_info.set_defaults(func=cmd_info)
760
+ p_stats = sub.add_parser("stats", help="show lifetime clean statistics")
761
+ p_stats.set_defaults(func=cmd_stats)
762
+
763
+ # restore / quarantine
764
+ p_restore = sub.add_parser("restore", help="undo a clean from quarantine")
765
+ p_restore.add_argument("run_id", nargs="?", help="run id (default: latest)")
766
+ p_restore.set_defaults(func=cmd_restore)
767
+
768
+ p_quar = sub.add_parser("quarantine", help="manage the quarantine store")
769
+ quar_sub = p_quar.add_subparsers(dest="quarantine_action", required=True)
770
+ quar_sub.add_parser("list", help="list quarantine runs")
771
+ q_empty = quar_sub.add_parser("empty", help="permanently reclaim quarantined space")
772
+ q_empty.add_argument("run_id", nargs="?", help="run id (default: all)")
773
+ q_empty.add_argument("--all", action="store_true", help="empty every run")
774
+ p_quar.set_defaults(func=cmd_quarantine)
775
+
776
+ # factory-reset (advisory plan)
777
+ p_reset = sub.add_parser(
778
+ "factory-reset",
779
+ help="show a plan to restore the OS toward factory settings",
780
+ )
781
+ p_reset.add_argument(
782
+ "--scope",
783
+ choices=["user", "packages", "system", "full"],
784
+ default="full",
785
+ help="how much to reset (default: full)",
786
+ )
787
+ p_reset.add_argument(
788
+ "--execute",
789
+ action="store_true",
790
+ help="run the reversible rollback (only on NixOS/rpm-ostree/MicroOS/Guix; "
791
+ "requires a typed confirmation)",
792
+ )
793
+ p_reset.set_defaults(func=cmd_factory_reset)
794
+
795
+ return parser
796
+
797
+
798
+ def main(argv: Optional[List[str]] = None) -> int:
799
+ parser = build_parser()
800
+ args = parser.parse_args(argv)
801
+ console = Console()
802
+ try:
803
+ return args.func(args, console)
804
+ except KeyboardInterrupt:
805
+ console.print("\n[yellow]Interrupted.[/yellow]")
806
+ return 130
807
+
808
+
809
+ if __name__ == "__main__":
810
+ sys.exit(main())