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
@@ -0,0 +1,115 @@
1
+ """Editor swap/undo files, build litter, loose core dumps, backup files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ from cleanix.cleaners.base import Cleaner
10
+ from cleanix.core.models import CleanableItem
11
+ from cleanix.core.utils import home, iter_children, older_than, path_size, walk_pruned
12
+
13
+
14
+ class EditorStateCleaner(Cleaner):
15
+ id = "editor_state"
16
+ name = "Editor swap/undo state"
17
+ description = "Vim/Neovim swap, undo and backup state (rebuildable)"
18
+ requires_root = False
19
+
20
+ def find_items(self) -> Iterable[CleanableItem]:
21
+ h = home()
22
+ for base in (
23
+ h / ".local" / "state" / "nvim",
24
+ h / ".local" / "share" / "nvim",
25
+ h / ".vim",
26
+ h / ".config" / "nvim",
27
+ ):
28
+ for sub in ("swap", "undo", "backup"):
29
+ target = base / sub
30
+ if target.is_dir():
31
+ for child in iter_children(target):
32
+ # A .swp for an open buffer is recent; leave it be.
33
+ if older_than(child, 1):
34
+ item = self.path_item(child, f"Editor {sub}: {child.name}")
35
+ if item:
36
+ yield item
37
+
38
+
39
+ class BuildLitterCleaner(Cleaner):
40
+ id = "build_litter"
41
+ name = "Build & test litter"
42
+ description = "__pycache__, .pytest_cache, .mypy_cache, .ruff_cache, .tox"
43
+ requires_root = False
44
+
45
+ _DIRS = {
46
+ "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache",
47
+ ".tox", ".hypothesis", ".ipynb_checkpoints",
48
+ }
49
+
50
+ def find_items(self) -> Iterable[CleanableItem]:
51
+ root = home()
52
+ for dirpath, dirs, _files in walk_pruned(root):
53
+ for d in list(dirs):
54
+ if d in self._DIRS:
55
+ p = os.path.join(dirpath, d)
56
+ item = self.path_item(p, f"Build litter: {p}")
57
+ if item:
58
+ yield item
59
+ # Don't descend into what we've already offered.
60
+ dirs.remove(d)
61
+
62
+
63
+ class HomeCoreDumpCleaner(Cleaner):
64
+ id = "home_coredumps"
65
+ name = "Loose core dumps"
66
+ description = "core / core.<pid> crash dumps left in the home tree"
67
+ requires_root = False
68
+
69
+ def find_items(self) -> Iterable[CleanableItem]:
70
+ root = home()
71
+ for dirpath, _dirs, files in walk_pruned(root):
72
+ for name in files:
73
+ if name == "core" or name.startswith("core."):
74
+ p = Path(dirpath, name)
75
+ try:
76
+ if not p.is_file() or p.is_symlink():
77
+ continue
78
+ except OSError:
79
+ continue
80
+ # A real core dump is large and binary; skip tiny files
81
+ # named "core" that are probably source (e.g. "core.py"→no,
82
+ # startswith core. would match core.py; require no dot-ext).
83
+ if "." in name and not name.split(".", 1)[1].isdigit():
84
+ continue
85
+ if path_size(p) < 4096:
86
+ continue
87
+ item = self.path_item(p, f"Core dump: {p}")
88
+ if item:
89
+ yield item
90
+
91
+
92
+ class BackupFileCleaner(Cleaner):
93
+ id = "backup_files"
94
+ name = "Editor backup files"
95
+ description = "*~, *.orig, *.bak, *.rej litter (opt-in)"
96
+ requires_root = False
97
+
98
+ _SUFFIXES = (".orig", ".bak", ".rej")
99
+
100
+ def available(self):
101
+ if not self.config.remove_backup_files:
102
+ return "disabled in config (remove_backup_files=false)"
103
+ return None
104
+
105
+ def find_items(self) -> Iterable[CleanableItem]:
106
+ root = home()
107
+ for dirpath, _dirs, files in walk_pruned(root):
108
+ for name in files:
109
+ if name.endswith("~") or name.endswith(self._SUFFIXES):
110
+ p = Path(dirpath, name)
111
+ if p.is_symlink() or not p.is_file():
112
+ continue
113
+ item = self.path_item(p, f"Backup file: {p}")
114
+ if item:
115
+ yield item
@@ -0,0 +1,29 @@
1
+ """Fontconfig cache (``~/.cache/fontconfig``) — regenerated on demand."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ from cleanix.cleaners.base import Cleaner
10
+ from cleanix.core.models import CleanableItem
11
+ from cleanix.core.platform import XDG_PLATFORMS
12
+ from cleanix.core.utils import cache_dir
13
+ from cleanix.core.utils import home, path_size
14
+
15
+
16
+ class FontCacheCleaner(Cleaner):
17
+ id = "font_cache"
18
+ name = "Font cache"
19
+ description = "Fontconfig cache under ~/.cache/fontconfig"
20
+ requires_root = False
21
+ platforms = XDG_PLATFORMS
22
+
23
+ def find_items(self) -> Iterable[CleanableItem]:
24
+ cache = str(cache_dir())
25
+ fc = Path(cache) / "fontconfig"
26
+ if fc.exists() and path_size(fc) > 0:
27
+ item = self.path_item(fc, "Fontconfig cache")
28
+ if item:
29
+ yield item
@@ -0,0 +1,87 @@
1
+ """IDE / code-editor leftovers.
2
+
3
+ Targets IDE-specific junk that the generic ~/.cache and Electron-cache cleaners
4
+ don't cover: VS Code-family logs/extension VSIX cache/stale workspace storage,
5
+ Sublime, Atom, Emacs native-comp cache, Zed logs, Android Studio, Qt Creator,
6
+ Godot, Unity. Installed extensions, settings and history are left alone.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Iterable, List, Tuple
13
+
14
+ from cleanix.cleaners.base import Cleaner
15
+ from cleanix.core.models import CleanableItem
16
+ from cleanix.core.platform import XDG_PLATFORMS
17
+ from cleanix.core.utils import config_dir, home, iter_children, older_than, path_size
18
+
19
+ # VS Code and its many forks all share the same layout under ~/.config/<App>/.
20
+ _VSCODE_APPS = (
21
+ "Code", "Code - Insiders", "Code - OSS", "VSCodium", "Cursor", "Windsurf",
22
+ "Positron", "Trae",
23
+ )
24
+
25
+
26
+ class IdeCleaner(Cleaner):
27
+ id = "ide_caches"
28
+ name = "IDE caches & logs"
29
+ description = "VS Code/Sublime/Atom/Emacs/Zed/etc. logs and rebuildable caches"
30
+ requires_root = False
31
+ platforms = XDG_PLATFORMS
32
+
33
+ def _vscode_items(self) -> Iterable[CleanableItem]:
34
+ cfg = config_dir()
35
+ for app in _VSCODE_APPS:
36
+ base = cfg / app
37
+ if not base.is_dir():
38
+ continue
39
+ for rel in ("logs", "CachedExtensionVSIXs", "CachedProfilesData",
40
+ "clp"):
41
+ target = base / rel
42
+ if target.is_dir() and path_size(target) > 0:
43
+ item = self.path_item(target, f"{app}: {rel}")
44
+ if item:
45
+ yield item
46
+ # Stale per-workspace storage (rebuildable indexes/state).
47
+ ws = base / "User" / "workspaceStorage"
48
+ if ws.is_dir():
49
+ for entry in iter_children(ws):
50
+ if older_than(entry, 30):
51
+ item = self.path_item(entry, f"{app}: stale workspace state")
52
+ if item:
53
+ yield item
54
+
55
+ def _simple_dirs(self) -> Iterable[Tuple[Path, str]]:
56
+ h = home()
57
+ cfg = config_dir()
58
+ # Sublime Text
59
+ for st in ("sublime-text", "sublime-text-3"):
60
+ yield cfg / st / "Cache", f"Sublime {st}: Cache"
61
+ yield cfg / st / "Index", f"Sublime {st}: Index"
62
+ # Atom (legacy)
63
+ yield h / ".atom" / "compile-cache", "Atom compile cache"
64
+ yield h / ".atom" / "blob-store", "Atom blob store"
65
+ # Emacs native-compilation cache & autosaves
66
+ yield h / ".emacs.d" / "eln-cache", "Emacs native-comp cache"
67
+ yield h / ".emacs.d" / "auto-save-list", "Emacs autosave list"
68
+ yield cfg / "emacs" / "eln-cache", "Emacs native-comp cache"
69
+ # Zed logs
70
+ yield h / ".local" / "share" / "zed" / "logs", "Zed logs"
71
+ # Qt Creator
72
+ yield h / ".local" / "share" / "QtProject" / "qtcreator" / "cache", "Qt Creator cache"
73
+ # Godot logs & shader cache
74
+ yield h / ".local" / "share" / "godot" / "app_userdata", "Godot logs/state"
75
+ # Unity editor logs
76
+ yield cfg / "unity3d" / "Editor.log", "Unity editor log"
77
+
78
+ def find_items(self) -> Iterable[CleanableItem]:
79
+ yield from self._vscode_items()
80
+ seen = set()
81
+ for path, label in self._simple_dirs():
82
+ if path in seen or not path.exists() or path_size(path) <= 0:
83
+ continue
84
+ seen.add(path)
85
+ item = self.path_item(path, label)
86
+ if item:
87
+ yield item
@@ -0,0 +1,115 @@
1
+ """Old-kernel removal.
2
+
3
+ Kernels pile up in ``/boot`` and ``/lib/modules`` and are a classic cause of a
4
+ full ``/boot``. This is inherently sensitive, so cleanix is conservative:
5
+
6
+ - Removal always goes through the **package manager**, which refuses to remove
7
+ the running kernel and fixes up bootloader entries.
8
+ - The currently-running kernel (``uname -r``) is always excluded.
9
+ - The newest ``keep_kernels`` versions are always kept.
10
+ - Disabled entirely with ``remove_old_kernels: false``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import platform
16
+ import re
17
+ from typing import Iterable, List, Tuple
18
+
19
+ from cleanix.cleaners.base import Cleaner, SCOPE_SYSTEM
20
+ from cleanix.core.models import CleanableItem
21
+ from cleanix.core.platform import LINUX
22
+ from cleanix.core.utils import run_command, which
23
+
24
+
25
+ def _version_key(v: str) -> Tuple:
26
+ """Best-effort natural sort key for a kernel version string."""
27
+ parts = re.split(r"[.\-+~]", v)
28
+ key = []
29
+ for p in parts:
30
+ key.append((0, int(p)) if p.isdigit() else (1, p))
31
+ return tuple(key)
32
+
33
+
34
+ class OldKernelCleaner(Cleaner):
35
+ id = "old_kernels"
36
+ name = "Old kernels"
37
+ description = "Superseded kernel packages (keeps running + newest N)"
38
+ requires_root = True
39
+ platforms = (LINUX,)
40
+ scope = SCOPE_SYSTEM
41
+
42
+ def available(self):
43
+ if not self.config.remove_old_kernels:
44
+ return "disabled in config (remove_old_kernels=false)"
45
+ if not (which("dpkg") or which("rpm")):
46
+ return "no supported package manager (dpkg/rpm) found"
47
+ return None
48
+
49
+ def _running(self) -> str:
50
+ return platform.release()
51
+
52
+ def _installed_debian(self) -> List[Tuple[str, str]]:
53
+ """Return (package, version) for installed linux-image packages."""
54
+ code, out, _ = run_command(
55
+ ["dpkg-query", "-W", "-f=${Package} ${Version}\n", "linux-image-*"],
56
+ timeout=30,
57
+ )
58
+ result = []
59
+ if code == 0:
60
+ for line in out.splitlines():
61
+ parts = line.split()
62
+ if len(parts) == 2 and parts[0].startswith("linux-image-"):
63
+ # skip meta-packages like linux-image-amd64
64
+ ver = parts[0][len("linux-image-"):]
65
+ if re.match(r"\d", ver):
66
+ result.append((parts[0], ver))
67
+ return result
68
+
69
+ def _installed_rpm(self) -> List[Tuple[str, str]]:
70
+ code, out, _ = run_command(
71
+ ["rpm", "-q", "kernel-core", "--qf", "%{VERSION}-%{RELEASE}.%{ARCH}\n"],
72
+ timeout=30,
73
+ )
74
+ result = []
75
+ if code == 0:
76
+ for line in out.splitlines():
77
+ line = line.strip()
78
+ if line and not line.startswith("package "):
79
+ result.append((f"kernel-core-{line}", line))
80
+ return result
81
+
82
+ def find_items(self) -> Iterable[CleanableItem]:
83
+ running = self._running()
84
+ keep = max(self.config.keep_kernels, 1)
85
+
86
+ if which("dpkg"):
87
+ installed = self._installed_debian()
88
+ purge_cmd = ["apt-get", "-y", "purge"]
89
+ elif which("rpm"):
90
+ installed = self._installed_rpm()
91
+ purge_cmd = None # handled below (dnf)
92
+ else:
93
+ return
94
+
95
+ if len(installed) <= keep:
96
+ return
97
+
98
+ # Sort newest-first; always keep the newest `keep` and the running one.
99
+ installed.sort(key=lambda pv: _version_key(pv[1]), reverse=True)
100
+ keep_set = {pv[0] for pv in installed[:keep]}
101
+ removable = [
102
+ pv for pv in installed
103
+ if pv[0] not in keep_set and running not in pv[1]
104
+ ]
105
+ if not removable:
106
+ return
107
+
108
+ for pkg, ver in removable:
109
+ if which("dpkg"):
110
+ cmd = ["apt-get", "-y", "purge", pkg]
111
+ else:
112
+ cmd = ["dnf", "-y", "remove", pkg]
113
+ yield self.command_item(
114
+ cmd, f"Remove old kernel {ver} ({pkg})"
115
+ )
@@ -0,0 +1,70 @@
1
+ """Language / toolchain download & module caches.
2
+
3
+ These are re-downloadable package caches (distinct from the build caches in
4
+ ``dev_caches``). Clearing them just forces a re-download next build.
5
+
6
+ "Offline repository" caches (Maven, Ivy, sbt, Coursier, NuGet, RubyGems) are
7
+ gated behind ``include_offline_repos`` because removing them can break offline
8
+ builds and trigger very large re-downloads.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from pathlib import Path
14
+ from typing import Iterable, List, Tuple
15
+
16
+ from cleanix.cleaners.base import Cleaner
17
+ from cleanix.core.models import CleanableItem
18
+ from cleanix.core.utils import home, path_size
19
+
20
+
21
+ class LangPackageCacheCleaner(Cleaner):
22
+ id = "lang_caches"
23
+ name = "Language package caches"
24
+ description = "Go/Rust/JS/.NET/etc. re-downloadable module & package caches"
25
+ requires_root = False
26
+
27
+ def _always(self) -> Iterable[Tuple[Path, str]]:
28
+ h = home()
29
+ cache = h / ".cache"
30
+ yield h / "go" / "pkg" / "mod" / "cache" / "download", "Go module download cache"
31
+ yield h / ".rustup" / "downloads", "rustup downloads"
32
+ yield h / ".rustup" / "tmp", "rustup temp"
33
+ yield cache / "deno", "Deno cache"
34
+ yield h / ".deno", "Deno cache"
35
+ yield h / ".bun" / "install" / "cache", "Bun install cache"
36
+ yield h / ".nvm" / ".cache", "nvm cache"
37
+ yield h / ".local" / "share" / "pnpm" / "store", "pnpm store"
38
+ yield h / ".pnpm-store", "pnpm store"
39
+ yield h / ".android" / "cache", "Android SDK cache"
40
+ yield h / ".android" / "build-cache", "Android build cache"
41
+ yield h / ".gradle" / "wrapper" / "dists", "Gradle wrapper distributions"
42
+ yield h / ".stack" / "pantry", "Haskell Stack pantry cache"
43
+ yield h / ".pub-cache", "Dart/Flutter pub cache"
44
+ yield h / ".cache" / "flutter", "Flutter engine cache"
45
+ yield h / ".cargo" / "registry" / "index", "Cargo registry index"
46
+
47
+ def _offline_repos(self) -> Iterable[Tuple[Path, str]]:
48
+ h = home()
49
+ yield h / ".m2" / "repository", "Maven local repository"
50
+ yield h / ".ivy2" / "cache", "Ivy cache"
51
+ yield h / ".sbt", "sbt cache"
52
+ yield h / ".coursier" / "cache", "Coursier cache"
53
+ yield h / ".cache" / "coursier", "Coursier cache"
54
+ yield h / ".nuget" / "packages", "NuGet package cache"
55
+ yield h / ".gem", "RubyGems cache"
56
+ yield h / ".bundle" / "cache", "Bundler cache"
57
+
58
+ def find_items(self) -> Iterable[CleanableItem]:
59
+ candidates: List[Tuple[Path, str]] = list(self._always())
60
+ if self.config.include_offline_repos:
61
+ candidates += list(self._offline_repos())
62
+
63
+ seen = set()
64
+ for path, label in candidates:
65
+ if path in seen or not path.exists() or path_size(path) <= 0:
66
+ continue
67
+ seen.add(path)
68
+ item = self.path_item(path, label)
69
+ if item:
70
+ yield item
@@ -0,0 +1,77 @@
1
+ """Linux-specific leftovers: crash dumps and package-update config residue."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ from cleanix.cleaners.base import Cleaner, SCOPE_SYSTEM
10
+ from cleanix.core.models import CleanableItem
11
+ from cleanix.core.platform import LINUX
12
+ from cleanix.core.utils import home, iter_children, older_than
13
+
14
+ # Files a package manager leaves next to config it couldn't safely overwrite.
15
+ # Removing these discards the *packaged* copy; your edited config is untouched.
16
+ _LEFTOVER_SUFFIXES = (
17
+ ".rpmnew", ".rpmsave", ".rpmorig", # RPM
18
+ ".pacnew", ".pacsave", ".pacorig", # pacman
19
+ ".dpkg-old", ".dpkg-dist", ".dpkg-new", ".dpkg-bak", # dpkg
20
+ ".ucf-old", ".ucf-dist", ".ucf-new", # ucf (Debian)
21
+ )
22
+
23
+
24
+ class ConfigLeftoverCleaner(Cleaner):
25
+ id = "config_leftovers"
26
+ scope = SCOPE_SYSTEM
27
+ name = "Package-update config residue"
28
+ description = (
29
+ "Leftover .rpmnew/.pacnew/.dpkg-old files from package upgrades"
30
+ )
31
+ requires_root = True
32
+ platforms = (LINUX,)
33
+
34
+ def available(self):
35
+ if not self.config.remove_config_leftovers:
36
+ return "disabled in config (remove_config_leftovers=false)"
37
+ return None
38
+
39
+ def find_items(self) -> Iterable[CleanableItem]:
40
+ for base in ("/etc", "/usr/etc", "/boot"):
41
+ root = Path(base)
42
+ if not root.exists():
43
+ continue
44
+ for dirpath, dirnames, files in os.walk(root, onerror=lambda e: None):
45
+ dirnames[:] = [
46
+ d
47
+ for d in dirnames
48
+ if not os.path.islink(os.path.join(dirpath, d))
49
+ ]
50
+ for name in files:
51
+ if name.endswith(_LEFTOVER_SUFFIXES):
52
+ p = os.path.join(dirpath, name)
53
+ item = self.path_item(p, f"Config residue: {p}")
54
+ if item:
55
+ yield item
56
+
57
+
58
+ class CrashReportCleaner(Cleaner):
59
+ id = "crash_reports"
60
+ scope = SCOPE_SYSTEM
61
+ name = "Crash reports"
62
+ description = "Application crash dumps under /var/crash"
63
+ requires_root = True
64
+ platforms = (LINUX,)
65
+
66
+ def find_items(self) -> Iterable[CleanableItem]:
67
+ for base in ("/var/crash", "/var/lib/apport/coredump"):
68
+ root = Path(base)
69
+ if not root.exists():
70
+ continue
71
+ for child in iter_children(root):
72
+ # Leave very fresh reports in case they are being written.
73
+ if not older_than(child, 0.02): # ~30 minutes
74
+ continue
75
+ item = self.path_item(child, f"Crash report: {child.name}")
76
+ if item:
77
+ yield item
@@ -0,0 +1,70 @@
1
+ """localepurge-style removal of unused locale & man-page translations.
2
+
3
+ Off by default (``purge_unused_locales``): it frees space but removes UI
4
+ translations and translated manuals for languages you don't use. We keep the
5
+ system's configured language(s), plus English and the C/POSIX locale.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from pathlib import Path
12
+ from typing import Iterable, Set
13
+
14
+ from cleanix.cleaners.base import Cleaner, SCOPE_SYSTEM
15
+ from cleanix.core.models import CleanableItem
16
+ from cleanix.core.platform import LINUX
17
+ from cleanix.core.utils import iter_children
18
+
19
+
20
+ class LocalePurgeCleaner(Cleaner):
21
+ id = "localepurge"
22
+ name = "Unused localizations"
23
+ description = "Locale & man-page translations for unused languages (opt-in)"
24
+ requires_root = True
25
+ platforms = (LINUX,)
26
+ scope = SCOPE_SYSTEM
27
+
28
+ def available(self):
29
+ if not self.config.purge_unused_locales:
30
+ return "disabled in config (purge_unused_locales=false)"
31
+ return None
32
+
33
+ def _keep_languages(self) -> Set[str]:
34
+ keep = {"en", "en_US", "en_GB", "C", "POSIX"}
35
+ for var in ("LANG", "LC_ALL", "LANGUAGE", "LC_MESSAGES"):
36
+ val = os.environ.get(var, "")
37
+ for part in val.replace(":", " ").split():
38
+ code = part.split(".")[0].split("_")[0]
39
+ if code:
40
+ keep.add(code)
41
+ keep.add(part.split(".")[0])
42
+ return keep
43
+
44
+ def _wanted(self, name: str, keep: Set[str]) -> bool:
45
+ base = name.split(".")[0]
46
+ return base in keep or base.split("_")[0] in keep
47
+
48
+ def find_items(self) -> Iterable[CleanableItem]:
49
+ keep = self._keep_languages()
50
+
51
+ locale_root = Path("/usr/share/locale")
52
+ if locale_root.is_dir():
53
+ for child in iter_children(locale_root):
54
+ if child.is_dir() and not self._wanted(child.name, keep):
55
+ item = self.path_item(child, f"Locale: {child.name}")
56
+ if item:
57
+ yield item
58
+
59
+ man_root = Path("/usr/share/man")
60
+ if man_root.is_dir():
61
+ for child in iter_children(man_root):
62
+ # man pages sit in man/<lang>/; man/man1 etc. are English.
63
+ if (
64
+ child.is_dir()
65
+ and not child.name.startswith("man")
66
+ and not self._wanted(child.name, keep)
67
+ ):
68
+ item = self.path_item(child, f"Man pages: {child.name}")
69
+ if item:
70
+ yield item
@@ -0,0 +1,80 @@
1
+ """Log cleaners: rotated files under /var/log, and the systemd journal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Iterable
7
+
8
+ from cleanix.cleaners.base import Cleaner, SCOPE_SYSTEM
9
+ from cleanix.core.models import CleanableItem
10
+ from cleanix.core.platform import LINUX
11
+ from cleanix.core.utils import older_than, path_size, which
12
+
13
+ # Rotated / compressed log suffixes that are safe to drop.
14
+ _ROTATED_SUFFIXES = (".gz", ".xz", ".bz2", ".old", ".1", ".2", ".3", ".4")
15
+
16
+
17
+ class RotatedLogCleaner(Cleaner):
18
+ id = "logs"
19
+ scope = SCOPE_SYSTEM
20
+ name = "Rotated logs (/var/log)"
21
+ description = "Old rotated/compressed log files"
22
+ requires_root = True
23
+
24
+ def find_items(self) -> Iterable[CleanableItem]:
25
+ root = Path("/var/log")
26
+ if not root.exists():
27
+ return
28
+ min_age = self.config.log_min_age_days
29
+ for path in root.rglob("*"):
30
+ if not path.is_file() or path.is_symlink():
31
+ continue
32
+ name = path.name
33
+ is_rotated = name.endswith(_ROTATED_SUFFIXES) or (
34
+ # e.g. syslog.1, messages-20240101
35
+ any(part.isdigit() for part in name.split(".")[-1:])
36
+ and "." in name
37
+ )
38
+ if not is_rotated:
39
+ continue
40
+ if not older_than(path, min_age):
41
+ continue
42
+ item = self.path_item(path, f"Log: {path}")
43
+ if item:
44
+ yield item
45
+
46
+
47
+ class JournalCleaner(Cleaner):
48
+ id = "journal"
49
+ scope = SCOPE_SYSTEM
50
+ name = "systemd journal"
51
+ description = "Vacuum journald history above the configured size cap"
52
+ requires_root = True
53
+ platforms = (LINUX,)
54
+
55
+ def available(self):
56
+ if not which("journalctl"):
57
+ return "journalctl not found"
58
+ return None
59
+
60
+ def find_items(self) -> Iterable[CleanableItem]:
61
+ # Estimate current on-disk journal size.
62
+ size = 0
63
+ for base in ("/var/log/journal", "/run/log/journal"):
64
+ p = Path(base)
65
+ if p.exists():
66
+ size += path_size(p)
67
+
68
+ cap_bytes = self.config.journal_max_size_mb * 1024 * 1024
69
+ reclaimable = max(size - cap_bytes, 0)
70
+ if reclaimable <= 0:
71
+ return
72
+
73
+ yield self.command_item(
74
+ [
75
+ "journalctl",
76
+ "--vacuum-size=%dM" % self.config.journal_max_size_mb,
77
+ ],
78
+ f"Vacuum journal to {self.config.journal_max_size_mb} MiB",
79
+ size=reclaimable,
80
+ )