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/core/safety.py ADDED
@@ -0,0 +1,166 @@
1
+ """The last line of defense against deleting something important.
2
+
3
+ Every deletion in cleanix funnels through :func:`safe_rmtree` /
4
+ :func:`safe_unlink`, which refuse to act on protected paths. This is
5
+ intentionally paranoid: a cleaner bug should never be able to wipe ``/`` or a
6
+ user's home directory.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from pathlib import Path
13
+ from typing import Iterable
14
+
15
+
16
+ class UnsafePathError(Exception):
17
+ """Raised when a delete target is protected or malformed."""
18
+
19
+
20
+ # User-configured extra protection (globs). Set once at startup from config.
21
+ _EXTRA_GLOBS: list = []
22
+
23
+
24
+ def set_protected_globs(globs) -> None:
25
+ """Register additional never-delete globs from user config."""
26
+ import os as _os
27
+
28
+ global _EXTRA_GLOBS
29
+ _EXTRA_GLOBS = [
30
+ _os.path.expanduser(_os.path.expandvars(str(g))) for g in (globs or [])
31
+ ]
32
+
33
+
34
+ def _matches_extra_glob(resolved: "Path") -> bool:
35
+ import fnmatch
36
+
37
+ s = str(resolved)
38
+ for pattern in _EXTRA_GLOBS:
39
+ if fnmatch.fnmatch(s, pattern) or s == pattern:
40
+ return True
41
+ return False
42
+
43
+
44
+ def _expand(p: str | os.PathLike) -> Path:
45
+ return Path(os.path.expandvars(os.path.expanduser(str(p)))).resolve()
46
+
47
+
48
+ # Absolute paths that must never be deleted, nor have their *contents* wiped as
49
+ # a whole. Cleaners may still delete files *inside* some of these (e.g. an
50
+ # individual file under /var/log), but never the directory itself.
51
+ _PROTECTED = {
52
+ "/",
53
+ # Linux / generic Unix
54
+ "/bin", "/boot", "/dev", "/etc", "/lib", "/lib32", "/lib64", "/libx32",
55
+ "/proc", "/root", "/run", "/sbin", "/srv", "/sys", "/usr", "/opt",
56
+ "/var", "/var/lib", "/var/log", "/var/db",
57
+ "/home",
58
+ # macOS
59
+ "/System", "/Library", "/Applications", "/Users", "/cores", "/Volumes",
60
+ "/private", "/private/etc", "/private/var", "/private/tmp",
61
+ # BSD
62
+ "/rescue", "/boot/kernel", "/usr/ports", "/usr/src", "/usr/obj",
63
+ "/compat", "/net", "/export",
64
+ }
65
+
66
+
67
+ # Per-home subdirectories whose wholesale deletion would be catastrophic.
68
+ _HOME_PROTECTED = (
69
+ ".config", ".local", ".local/share",
70
+ "Library", "Documents", "Desktop", "Downloads", "Pictures",
71
+ )
72
+
73
+
74
+ def _home_dirs() -> list:
75
+ """Every home directory in scope (all target users, plus the process home)."""
76
+ homes = []
77
+ try:
78
+ from cleanix.core.context import get_target_users
79
+
80
+ homes.extend(u.home for u in get_target_users())
81
+ except Exception: # noqa: BLE001 - safety must never depend on context
82
+ pass
83
+ fallback = os.path.expanduser("~")
84
+ if fallback and fallback != "~":
85
+ homes.append(Path(fallback))
86
+ return homes
87
+
88
+
89
+ def _protected_roots() -> set:
90
+ roots = {Path(p) for p in _PROTECTED}
91
+ for home in _home_dirs():
92
+ try:
93
+ home_path = Path(home).resolve()
94
+ except OSError:
95
+ continue
96
+ roots.add(home_path) # never delete a $HOME itself
97
+ for rel in _HOME_PROTECTED:
98
+ roots.add(home_path / rel)
99
+ return roots
100
+
101
+
102
+ def assert_safe_to_delete(target: str | os.PathLike) -> Path:
103
+ """Return the resolved path if it is safe to delete, else raise.
104
+
105
+ A path is unsafe when it *is* a protected root, or when it is an ancestor
106
+ of one (deleting it would take the protected root with it).
107
+ """
108
+ resolved = _expand(target)
109
+
110
+ if str(resolved) in ("", "/"):
111
+ raise UnsafePathError(f"refusing to delete filesystem root: {resolved}")
112
+
113
+ if _matches_extra_glob(resolved):
114
+ raise UnsafePathError(
115
+ f"refusing to delete {resolved}: matches a user protected_globs entry"
116
+ )
117
+
118
+ protected = _protected_roots()
119
+ if resolved in protected:
120
+ raise UnsafePathError(f"refusing to delete protected path: {resolved}")
121
+
122
+ # Refuse if the target is an ancestor of any protected root.
123
+ for root in protected:
124
+ try:
125
+ root.relative_to(resolved)
126
+ except ValueError:
127
+ continue
128
+ raise UnsafePathError(
129
+ f"refusing to delete {resolved}: it contains protected path {root}"
130
+ )
131
+
132
+ return resolved
133
+
134
+
135
+ def is_safe_to_delete(target: str | os.PathLike) -> bool:
136
+ try:
137
+ assert_safe_to_delete(target)
138
+ return True
139
+ except UnsafePathError:
140
+ return False
141
+
142
+
143
+ def safe_unlink(target: str | os.PathLike) -> None:
144
+ """Delete a single file/symlink after the safety check."""
145
+ resolved = _expand(target)
146
+ assert_safe_to_delete(resolved)
147
+ if resolved.is_dir() and not resolved.is_symlink():
148
+ raise UnsafePathError(f"{resolved} is a directory; use safe_rmtree")
149
+ resolved.unlink(missing_ok=True)
150
+
151
+
152
+ def safe_rmtree(target: str | os.PathLike) -> None:
153
+ """Recursively delete a directory (or file) after the safety check."""
154
+ import shutil
155
+
156
+ resolved = _expand(target)
157
+ assert_safe_to_delete(resolved)
158
+ if resolved.is_symlink() or resolved.is_file():
159
+ resolved.unlink(missing_ok=True)
160
+ elif resolved.is_dir():
161
+ shutil.rmtree(resolved, ignore_errors=True)
162
+
163
+
164
+ def filter_safe(paths: Iterable[str | os.PathLike]) -> list[Path]:
165
+ """Keep only the paths that pass the safety check."""
166
+ return [_expand(p) for p in paths if is_safe_to_delete(p)]
cleanix/core/utils.py ADDED
@@ -0,0 +1,244 @@
1
+ """Small helpers: sizes, path walking, age filtering, command running."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Iterator, Optional, Sequence
11
+
12
+
13
+ def human_size(num_bytes: int) -> str:
14
+ """Format a byte count like ``1.4 GiB``."""
15
+ size = float(num_bytes)
16
+ for unit in ("B", "KiB", "MiB", "GiB", "TiB", "PiB"):
17
+ if abs(size) < 1024.0 or unit == "PiB":
18
+ if unit == "B":
19
+ return f"{int(size)} {unit}"
20
+ return f"{size:.1f} {unit}"
21
+ size /= 1024.0
22
+ return f"{size:.1f} PiB"
23
+
24
+
25
+ def _allocated_bytes(st: os.stat_result) -> int:
26
+ """Actual on-disk usage of a stat result.
27
+
28
+ We use allocated blocks (``st_blocks`` * 512) rather than the apparent
29
+ ``st_size`` so that sparse files — whose apparent size can be terabytes
30
+ while occupying almost no disk — do not wildly overstate reclaimable space.
31
+ Falls back to ``st_size`` on platforms without ``st_blocks``.
32
+ """
33
+ blocks = getattr(st, "st_blocks", None)
34
+ if blocks is None:
35
+ return st.st_size
36
+ return blocks * 512
37
+
38
+
39
+ def path_size(path: str | os.PathLike) -> int:
40
+ """Actual on-disk size of a file or directory tree in bytes (best effort)."""
41
+ p = Path(path)
42
+ try:
43
+ if p.is_symlink():
44
+ return 0
45
+ if p.is_file():
46
+ return _allocated_bytes(p.stat())
47
+ except OSError:
48
+ return 0
49
+
50
+ total = 0
51
+ for root, dirs, files in os.walk(p, onerror=lambda e: None):
52
+ # Do not follow symlinked directories.
53
+ dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(root, d))]
54
+ for name in files:
55
+ fp = os.path.join(root, name)
56
+ try:
57
+ if os.path.islink(fp):
58
+ continue
59
+ total += _allocated_bytes(os.lstat(fp))
60
+ except OSError:
61
+ continue
62
+ return total
63
+
64
+
65
+ def iter_children(path: str | os.PathLike) -> Iterator[Path]:
66
+ """Yield immediate children of a directory, ignoring errors."""
67
+ try:
68
+ with os.scandir(path) as it:
69
+ for entry in it:
70
+ yield Path(entry.path)
71
+ except OSError:
72
+ return
73
+
74
+
75
+ def older_than(path: str | os.PathLike, days: float) -> bool:
76
+ """True if the path's mtime is older than ``days`` days."""
77
+ if days <= 0:
78
+ return True
79
+ try:
80
+ mtime = os.lstat(path).st_mtime
81
+ except OSError:
82
+ return False
83
+ return (time.time() - mtime) > days * 86400
84
+
85
+
86
+ def _mtime(path: str | os.PathLike) -> float:
87
+ try:
88
+ return os.lstat(path).st_mtime
89
+ except OSError:
90
+ return 0.0
91
+
92
+
93
+ def surplus_after_keeping(paths, keep: int) -> list:
94
+ """Return the paths to remove when keeping only the ``keep`` newest.
95
+
96
+ Given rolling backups/snapshots, keep the ``keep`` most recently modified
97
+ and return the older surplus (the ones safe to delete). Implements the
98
+ common "keep max N backups" retention policy.
99
+ """
100
+ ordered = sorted(paths, key=_mtime, reverse=True) # newest first
101
+ if keep <= 0:
102
+ return list(ordered)
103
+ return list(ordered[keep:])
104
+
105
+
106
+ def modified_within(path: str | os.PathLike, minutes: float) -> bool:
107
+ """True if the path was modified within the last ``minutes`` minutes.
108
+
109
+ Used as an "in use" guard: a file being actively written (e.g. another
110
+ program's scratch file) has a very recent mtime and should be left alone.
111
+ """
112
+ if minutes <= 0:
113
+ return False
114
+ try:
115
+ mtime = os.lstat(path).st_mtime
116
+ except OSError:
117
+ return False
118
+ return (time.time() - mtime) < minutes * 60
119
+
120
+
121
+ def exists(path: str | os.PathLike) -> bool:
122
+ try:
123
+ return Path(os.path.expanduser(str(path))).exists()
124
+ except OSError:
125
+ return False
126
+
127
+
128
+ def which(cmd: str) -> Optional[str]:
129
+ return shutil.which(cmd)
130
+
131
+
132
+ def has_any(*cmds: str) -> bool:
133
+ return any(shutil.which(c) for c in cmds)
134
+
135
+
136
+ def is_broken_symlink(path: str | os.PathLike) -> bool:
137
+ """True if ``path`` is a symlink whose target does not exist."""
138
+ return os.path.islink(path) and not os.path.exists(path)
139
+
140
+
141
+ # Directory names pruned when walking a home tree, to keep scans fast and to
142
+ # avoid descending into unrelated package/VCS trees.
143
+ _PRUNE_DIRS = {
144
+ ".git", ".hg", ".svn", "node_modules", ".cache", "Library",
145
+ ".venv", "venv", "__pycache__", ".tox", ".mypy_cache", "Photos Library.photoslibrary",
146
+ }
147
+
148
+
149
+ def walk_pruned(root: str | os.PathLike, prune: Optional[set] = None):
150
+ """os.walk a tree, skipping large/irrelevant subdirectories and errors."""
151
+ prune = prune if prune is not None else _PRUNE_DIRS
152
+ for dirpath, dirnames, filenames in os.walk(root, onerror=lambda e: None):
153
+ dirnames[:] = [
154
+ d
155
+ for d in dirnames
156
+ if d not in prune and not os.path.islink(os.path.join(dirpath, d))
157
+ ]
158
+ yield dirpath, dirnames, filenames
159
+
160
+
161
+ def is_root() -> bool:
162
+ return hasattr(os, "geteuid") and os.geteuid() == 0
163
+
164
+
165
+ def home() -> Path:
166
+ """Home directory of the user currently being scanned (context-aware)."""
167
+ from cleanix.core.context import current_user
168
+
169
+ return current_user().home
170
+
171
+
172
+ def current_uid() -> Optional[int]:
173
+ """uid of the user currently being scanned."""
174
+ from cleanix.core.context import current_user
175
+
176
+ return current_user().uid
177
+
178
+
179
+ def _xdg_dir(env_var: str, default_sub: str) -> Path:
180
+ """Resolve an XDG dir for the current user.
181
+
182
+ The invoker's own XDG_* environment is honored only for an unprivileged,
183
+ single-user run. When sweeping multiple users (root), the standard default
184
+ (``$HOME/<sub>``) is always used, since root's environment must not be
185
+ projected onto other users' homes.
186
+ """
187
+ from cleanix.core.context import current_user
188
+
189
+ user = current_user()
190
+ if user.is_invoker and not is_root():
191
+ val = os.environ.get(env_var)
192
+ if val:
193
+ return Path(val)
194
+ return user.home / default_sub
195
+
196
+
197
+ def cache_dir() -> Path:
198
+ return _xdg_dir("XDG_CACHE_HOME", ".cache")
199
+
200
+
201
+ def config_dir() -> Path:
202
+ return _xdg_dir("XDG_CONFIG_HOME", ".config")
203
+
204
+
205
+ def data_dir() -> Path:
206
+ return _xdg_dir("XDG_DATA_HOME", ".local/share")
207
+
208
+
209
+ def state_dir() -> Path:
210
+ return _xdg_dir("XDG_STATE_HOME", ".local/state")
211
+
212
+
213
+ def expand(path: str | os.PathLike) -> Path:
214
+ """Expand ``~``/vars against the *current* user's home (context-aware)."""
215
+ from cleanix.core.context import current_user
216
+
217
+ s = os.path.expandvars(str(path))
218
+ if s == "~":
219
+ return current_user().home
220
+ if s.startswith("~/"):
221
+ return current_user().home / s[2:]
222
+ return Path(s)
223
+
224
+
225
+ def run_command(
226
+ command: Sequence[str], timeout: int = 120
227
+ ) -> tuple[int, str, str]:
228
+ """Run a command, returning ``(returncode, stdout, stderr)``.
229
+
230
+ Never raises on a non-zero exit; callers inspect the return code.
231
+ """
232
+ try:
233
+ proc = subprocess.run(
234
+ list(command),
235
+ capture_output=True,
236
+ text=True,
237
+ timeout=timeout,
238
+ check=False,
239
+ )
240
+ return proc.returncode, proc.stdout, proc.stderr
241
+ except FileNotFoundError:
242
+ return 127, "", f"command not found: {command[0]}"
243
+ except subprocess.TimeoutExpired:
244
+ return 124, "", f"command timed out: {' '.join(command)}"