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/reset.py ADDED
@@ -0,0 +1,328 @@
1
+ """Factory-reset advisor.
2
+
3
+ There is no single "factory reset" across the *nix world, and on most systems it
4
+ is irreversible. So cleanix does not *perform* a reset — it detects your system's
5
+ reset capability and produces a **tiered, copy-pasteable plan**, loudest about
6
+ the safeguards. Declarative/image-based systems (NixOS, rpm-ostree, Guix,
7
+ MicroOS) have a genuine, reversible factory reset; traditional distros do not,
8
+ and the plan says so honestly.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import socket
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Callable, List, Tuple
17
+
18
+ from cleanix.core.platform import MACOS, current_distro, current_os
19
+ from cleanix.core.utils import which
20
+
21
+
22
+ @dataclass
23
+ class ResetAction:
24
+ """A reversible reset command cleanix is allowed to *execute*."""
25
+
26
+ description: str
27
+ command: List[str]
28
+ requires_root: bool = True
29
+ undo: str = ""
30
+
31
+
32
+ @dataclass
33
+ class Tier:
34
+ key: str # user | packages | system
35
+ title: str
36
+ warning: str
37
+ steps: List[str] = field(default_factory=list)
38
+
39
+
40
+ @dataclass
41
+ class ResetPlan:
42
+ strategy: str
43
+ reversible: bool
44
+ summary: str
45
+ prerequisites: List[str] = field(default_factory=list)
46
+ tiers: List[Tier] = field(default_factory=list)
47
+ # Only populated for reversible strategies; these are the ONLY commands
48
+ # cleanix will run for --execute. Irreversible steps stay advisory-only.
49
+ actions: List[ResetAction] = field(default_factory=list)
50
+
51
+
52
+ def confirmation_phrase() -> str:
53
+ """The exact phrase a user must type to authorize execution."""
54
+ try:
55
+ host = socket.gethostname() or "this-system"
56
+ except Exception: # noqa: BLE001
57
+ host = "this-system"
58
+ return f"reset {host}"
59
+
60
+
61
+ def execute_actions(
62
+ plan: ResetPlan, runner: Callable[[List[str]], int]
63
+ ) -> List[Tuple[ResetAction, int]]:
64
+ """Run the plan's reversible actions in order, stopping on first failure.
65
+
66
+ ``runner`` executes an argv and returns a process exit code; injecting it
67
+ keeps this testable and keeps subprocess concerns in the CLI layer.
68
+ """
69
+ results: List[Tuple[ResetAction, int]] = []
70
+ for action in plan.actions:
71
+ code = runner(action.command)
72
+ results.append((action, code))
73
+ if code != 0:
74
+ break
75
+ return results
76
+
77
+
78
+ def _detect_strategy() -> str:
79
+ if current_os() == MACOS:
80
+ return "macos"
81
+ if Path("/etc/NIXOS").exists() or current_distro() == "nixos":
82
+ return "nixos"
83
+ if Path("/run/ostree-booted").exists() or which("rpm-ostree"):
84
+ return "ostree"
85
+ if which("transactional-update"):
86
+ return "microos"
87
+ if which("guix") and Path("/run/current-system").exists():
88
+ return "guix"
89
+ return "traditional"
90
+
91
+
92
+ # --- per-strategy tier builders ---------------------------------------------
93
+ def _user_tier(distro_hint: str = "") -> Tier:
94
+ return Tier(
95
+ key="user",
96
+ title="User environment reset (per account)",
97
+ warning="Removes desktop/app settings, extensions, keyrings and caches. "
98
+ "Documents/Downloads/Pictures are preserved. Not reversible without the backup.",
99
+ steps=[
100
+ "Back up first: tar czf ~/dotfiles-backup.tgz -C $HOME .config .local .cache .mozilla .gnupg .ssh",
101
+ "Preview what cleanix would remove: cleanix clean --current-user",
102
+ "Then reset the shell/app state to defaults, e.g.:",
103
+ " rm -rf ~/.config ~/.local/share ~/.cache ~/.local/state",
104
+ " (keep ~/.ssh, ~/.gnupg unless you truly want new keys)",
105
+ "Log out and back in — the DE recreates default settings.",
106
+ ],
107
+ )
108
+
109
+
110
+ def build_plan(scope: str) -> ResetPlan:
111
+ strategy = _detect_strategy()
112
+ common_prereq = [
113
+ "Take a full snapshot/backup you can boot from (Timeshift, btrfs/ZFS "
114
+ "snapshot, or a full image). cleanix will not do this for you.",
115
+ "Close all apps and save your work; a reset cannot be undone mid-way.",
116
+ ]
117
+
118
+ if strategy == "nixos":
119
+ plan = ResetPlan(
120
+ strategy="NixOS (declarative)",
121
+ reversible=True,
122
+ summary="NixOS is fully declarative: the system is rebuilt from "
123
+ "configuration.nix, and every rebuild is a bootable generation. A "
124
+ "true, reversible factory reset.",
125
+ prerequisites=common_prereq,
126
+ tiers=[
127
+ _user_tier(),
128
+ Tier(
129
+ "packages",
130
+ "Package/system state reset",
131
+ "Reverts the system to a pristine configuration and drops all "
132
+ "extra generations.",
133
+ [
134
+ "Restore a minimal/original configuration.nix (or generation 1).",
135
+ "sudo nixos-rebuild switch # rebuild from that config",
136
+ "sudo nix-collect-garbage -d # delete old generations",
137
+ "sudo nixos-rebuild boot --rollback # or pick generation 1 in the boot menu",
138
+ ],
139
+ ),
140
+ Tier(
141
+ "system",
142
+ "Deep reset",
143
+ "Wipes mutable state not tracked by Nix.",
144
+ [
145
+ "Remove /home/<user> state (see user tier) for a like-new account.",
146
+ "Optionally re-run the installer for a bit-for-bit factory image.",
147
+ ],
148
+ ),
149
+ ],
150
+ actions=[
151
+ ResetAction(
152
+ "Roll back to the previous NixOS generation",
153
+ ["nixos-rebuild", "switch", "--rollback"],
154
+ requires_root=True,
155
+ undo="pick a newer generation at boot, or run nixos-rebuild switch",
156
+ ),
157
+ ],
158
+ )
159
+ return _filter(plan, scope)
160
+
161
+ if strategy == "ostree":
162
+ return _filter(ResetPlan(
163
+ strategy="rpm-ostree / OSTree image-based (Silverblue, Kinoite, IoT)",
164
+ reversible=True,
165
+ summary="The base OS is an immutable image; your changes are layers "
166
+ "and overrides on top. Resetting the layers gives a genuine, "
167
+ "reversible factory image.",
168
+ prerequisites=common_prereq,
169
+ tiers=[
170
+ _user_tier(),
171
+ Tier("packages", "Drop layered packages & overrides",
172
+ "Returns the OS layer to the pristine base image.",
173
+ [
174
+ "rpm-ostree reset # remove all layered pkgs + overrides",
175
+ "rpm-ostree rollback # or return to the previous deployment",
176
+ "flatpak uninstall --all # optional: remove all Flatpak apps",
177
+ ]),
178
+ Tier("system", "Reset /etc & redeploy",
179
+ "OSTree 3-way merges /etc; review and discard local changes.",
180
+ [
181
+ "ostree admin config-diff # see your /etc changes vs base",
182
+ "Revert unwanted /etc edits, then reboot into the clean deployment.",
183
+ ]),
184
+ ],
185
+ actions=[
186
+ ResetAction(
187
+ "Remove all layered packages and overrides (reset to base image)",
188
+ ["rpm-ostree", "reset"],
189
+ requires_root=True,
190
+ undo="rpm-ostree rollback (the prior deployment is still bootable)",
191
+ ),
192
+ ],
193
+ ), scope)
194
+
195
+ if strategy == "microos":
196
+ return _filter(ResetPlan(
197
+ strategy="openSUSE MicroOS / Aeon (transactional, btrfs)",
198
+ reversible=True,
199
+ summary="Transactional-update with btrfs snapshots: every change is a "
200
+ "snapshot you can roll back to. Factory reset = roll back to the first.",
201
+ prerequisites=common_prereq,
202
+ tiers=[
203
+ _user_tier(),
204
+ Tier("packages", "Roll back the system",
205
+ "Returns to an earlier (or the first) transactional snapshot.",
206
+ [
207
+ "snapper list # find the earliest snapshot",
208
+ "sudo snapper rollback <number> # roll back to it",
209
+ "sudo transactional-update cleanup # drop old snapshots",
210
+ "reboot",
211
+ ]),
212
+ ],
213
+ actions=[
214
+ ResetAction(
215
+ "Roll back to the last known-good snapshot",
216
+ ["snapper", "rollback"],
217
+ requires_root=True,
218
+ undo="snapper rollback <previous-number> (all snapshots are retained)",
219
+ ),
220
+ ],
221
+ ), scope)
222
+
223
+ if strategy == "guix":
224
+ return _filter(ResetPlan(
225
+ strategy="Guix System (declarative)",
226
+ reversible=True,
227
+ summary="Like NixOS: declarative generations you can roll back to.",
228
+ prerequisites=common_prereq,
229
+ tiers=[
230
+ _user_tier(),
231
+ Tier("packages", "Roll back / reconfigure",
232
+ "Return to a pristine system definition.",
233
+ [
234
+ "sudo guix system roll-back # previous generation",
235
+ "sudo guix system reconfigure <pristine-config.scm>",
236
+ "guix gc # collect garbage",
237
+ ]),
238
+ ],
239
+ actions=[
240
+ ResetAction(
241
+ "Roll back to the previous system generation",
242
+ ["guix", "system", "roll-back"],
243
+ requires_root=True,
244
+ undo="guix system switch-generation <n> (generations are retained)",
245
+ ),
246
+ ],
247
+ ), scope)
248
+
249
+ if strategy == "macos":
250
+ return _filter(ResetPlan(
251
+ strategy="macOS",
252
+ reversible=False,
253
+ summary="macOS has a built-in factory reset ('Erase All Content and "
254
+ "Settings') that is the correct, supported path — far safer than "
255
+ "deleting files by hand.",
256
+ prerequisites=["Back up with Time Machine first."],
257
+ tiers=[
258
+ _user_tier(),
259
+ Tier("system", "Full erase (recommended)",
260
+ "The supported factory reset.",
261
+ [
262
+ "System Settings → General → Transfer or Reset → Erase All Content and Settings",
263
+ "Or boot into Recovery (⌘R) → Disk Utility → erase → reinstall macOS.",
264
+ ]),
265
+ ],
266
+ ), scope)
267
+
268
+ # traditional
269
+ distro = current_distro()
270
+ pkg_steps: List[str]
271
+ if which("apt-get"):
272
+ pkg_steps = [
273
+ "apt-mark showmanual > ~/manual-packages.txt # review what you added",
274
+ "Remove packages you installed, keeping the base seed; then:",
275
+ "sudo apt-get autoremove --purge && sudo apt-get clean",
276
+ "There is no supported 'reset to install state' — a reinstall is the reliable path.",
277
+ ]
278
+ elif which("dnf"):
279
+ pkg_steps = [
280
+ "dnf history list # find the first (install) transaction",
281
+ "sudo dnf history rollback 1 # undo everything since install (best effort)",
282
+ "sudo dnf autoremove && sudo dnf distro-sync",
283
+ ]
284
+ elif which("pacman"):
285
+ pkg_steps = [
286
+ "pacman -Qqe > ~/explicit-packages.txt # your explicit installs",
287
+ "Reduce to base: pacman -Qqe | grep -vx -f <(pacman -Qqg base base-devel) | sudo pacman -Rns -",
288
+ "Restore packaged configs: sudo pacman -Qkk then reinstall changed pkgs.",
289
+ ]
290
+ else:
291
+ pkg_steps = ["Use your package manager to remove non-base packages; no universal reset exists."]
292
+
293
+ return _filter(ResetPlan(
294
+ strategy=f"Traditional distribution ({distro or current_os()})",
295
+ reversible=False,
296
+ summary="Traditional distros have NO true factory reset. The reliable "
297
+ "options are (a) restore a pre-existing snapshot/backup, or (b) reinstall. "
298
+ "The steps below approximate a reset but cannot guarantee an install-clean state.",
299
+ prerequisites=common_prereq + [
300
+ "STRONGLY consider a reinstall or snapshot restore instead of the steps below.",
301
+ ],
302
+ tiers=[
303
+ _user_tier(distro),
304
+ Tier("packages", "Approximate package reset",
305
+ "Removes user-installed packages; cannot perfectly restore the install set.",
306
+ pkg_steps),
307
+ Tier("system", "Reset system configuration",
308
+ "Restore /etc toward packaged defaults.",
309
+ [
310
+ "Run cleanix's config-residue cleaner: sudo cleanix clean --only config_leftovers --execute",
311
+ "Review remaining /etc changes against packaged defaults and revert them.",
312
+ "Re-run cleanix aggressively: cleanix clean --all-users --execute "
313
+ "(after enabling include_offline_repos / purge_unused_locales if desired).",
314
+ ]),
315
+ ],
316
+ ), scope)
317
+
318
+
319
+ def _filter(plan: ResetPlan, scope: str) -> ResetPlan:
320
+ if scope == "full":
321
+ return plan
322
+ wanted = {scope}
323
+ if scope == "system":
324
+ wanted = {"user", "packages", "system"}
325
+ if scope == "packages":
326
+ wanted = {"user", "packages"}
327
+ plan.tiers = [t for t in plan.tiers if t.key in wanted]
328
+ return plan
@@ -0,0 +1 @@
1
+ """Scheduling support (systemd user timers)."""
@@ -0,0 +1,160 @@
1
+ """Install/uninstall a systemd *user* timer that periodically scans.
2
+
3
+ Scheduled runs only **analyze** and write a report + desktop notification; they
4
+ never delete anything. Using a user timer keeps everything inside the user's
5
+ own session — no root required, no system-wide units touched.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ from pathlib import Path
14
+ from typing import Optional, Tuple
15
+
16
+ SERVICE_NAME = "cleanix-scan.service"
17
+ TIMER_NAME = "cleanix-scan.timer"
18
+
19
+ # Map friendly frequencies to systemd OnCalendar expressions.
20
+ FREQUENCIES = {
21
+ "hourly": "hourly",
22
+ "daily": "daily",
23
+ "weekly": "weekly",
24
+ "monthly": "monthly",
25
+ }
26
+
27
+
28
+ def _user_unit_dir() -> Path:
29
+ base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
30
+ return Path(base) / "systemd" / "user"
31
+
32
+
33
+ def _report_dir() -> Path:
34
+ base = os.environ.get("XDG_STATE_HOME") or os.path.expanduser(
35
+ "~/.local/state"
36
+ )
37
+ return Path(base) / "cleanix"
38
+
39
+
40
+ def _cleanix_exe() -> str:
41
+ return shutil.which("cleanix") or "cleanix"
42
+
43
+
44
+ def _systemctl(*args: str) -> Tuple[int, str, str]:
45
+ try:
46
+ proc = subprocess.run(
47
+ ["systemctl", "--user", *args],
48
+ capture_output=True,
49
+ text=True,
50
+ check=False,
51
+ )
52
+ return proc.returncode, proc.stdout, proc.stderr
53
+ except FileNotFoundError:
54
+ return 127, "", "systemctl not found"
55
+
56
+
57
+ def systemd_available() -> Optional[str]:
58
+ if not shutil.which("systemctl"):
59
+ return "systemctl not found (systemd required for scheduling)"
60
+ return None
61
+
62
+
63
+ def _service_unit() -> str:
64
+ exe = _cleanix_exe()
65
+ report_dir = _report_dir()
66
+ report_file = report_dir / "last-scan.json"
67
+ # ExecStartPost sends a desktop notification summarizing the scan.
68
+ notify = (
69
+ "/bin/sh -c '"
70
+ f"command -v notify-send >/dev/null 2>&1 && "
71
+ f"notify-send \"Cleanix\" "
72
+ f"\"$(cleanix scan --quiet --summary 2>/dev/null || echo scan complete)\" "
73
+ "|| true'"
74
+ )
75
+ return f"""[Unit]
76
+ Description=Cleanix scheduled analysis (read-only, no deletion)
77
+ Documentation=man:cleanix(1)
78
+
79
+ [Service]
80
+ Type=oneshot
81
+ ExecStart={exe} scan --json --output {report_file}
82
+ ExecStartPost={notify}
83
+ Nice=15
84
+ IOSchedulingClass=idle
85
+ """
86
+
87
+
88
+ def _timer_unit(calendar: str) -> str:
89
+ return f"""[Unit]
90
+ Description=Run Cleanix analysis on a schedule
91
+
92
+ [Timer]
93
+ OnCalendar={calendar}
94
+ Persistent=true
95
+ RandomizedDelaySec=300
96
+
97
+ [Install]
98
+ WantedBy=timers.target
99
+ """
100
+
101
+
102
+ def install(frequency: str = "weekly") -> str:
103
+ err = systemd_available()
104
+ if err:
105
+ raise RuntimeError(err)
106
+
107
+ calendar = FREQUENCIES.get(frequency)
108
+ if calendar is None:
109
+ raise ValueError(
110
+ f"unknown frequency {frequency!r}; choose one of "
111
+ f"{', '.join(FREQUENCIES)}"
112
+ )
113
+
114
+ unit_dir = _user_unit_dir()
115
+ unit_dir.mkdir(parents=True, exist_ok=True)
116
+ _report_dir().mkdir(parents=True, exist_ok=True)
117
+
118
+ (unit_dir / SERVICE_NAME).write_text(_service_unit())
119
+ (unit_dir / TIMER_NAME).write_text(_timer_unit(calendar))
120
+
121
+ _systemctl("daemon-reload")
122
+ code, _out, serr = _systemctl("enable", "--now", TIMER_NAME)
123
+ if code != 0:
124
+ raise RuntimeError(f"failed to enable timer: {serr.strip()}")
125
+ return (
126
+ f"Installed {TIMER_NAME} ({frequency}). Reports are written to "
127
+ f"{_report_dir() / 'last-scan.json'}."
128
+ )
129
+
130
+
131
+ def uninstall() -> str:
132
+ err = systemd_available()
133
+ if err:
134
+ raise RuntimeError(err)
135
+
136
+ _systemctl("disable", "--now", TIMER_NAME)
137
+ unit_dir = _user_unit_dir()
138
+ removed = []
139
+ for name in (TIMER_NAME, SERVICE_NAME):
140
+ unit = unit_dir / name
141
+ if unit.exists():
142
+ unit.unlink()
143
+ removed.append(name)
144
+ _systemctl("daemon-reload")
145
+ if removed:
146
+ return f"Removed {', '.join(removed)}."
147
+ return "Nothing to remove (timer was not installed)."
148
+
149
+
150
+ def status() -> str:
151
+ err = systemd_available()
152
+ if err:
153
+ return err
154
+ installed = (_user_unit_dir() / TIMER_NAME).exists()
155
+ if not installed:
156
+ return "Cleanix schedule: not installed."
157
+ _code, out, _serr = _systemctl(
158
+ "list-timers", TIMER_NAME, "--no-pager", "--all"
159
+ )
160
+ return out.strip() or "Cleanix schedule: installed."