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.
- cleanix/__init__.py +4 -0
- cleanix/__main__.py +6 -0
- cleanix/cleaners/__init__.py +269 -0
- cleanix/cleaners/ai_cli.py +193 -0
- cleanix/cleaners/ai_tools.py +224 -0
- cleanix/cleaners/app_cruft.py +201 -0
- cleanix/cleaners/apple_litter.py +41 -0
- cleanix/cleaners/apps.py +89 -0
- cleanix/cleaners/apt.py +70 -0
- cleanix/cleaners/base.py +173 -0
- cleanix/cleaners/broken_symlinks.py +51 -0
- cleanix/cleaners/browsers.py +68 -0
- cleanix/cleaners/bsd.py +108 -0
- cleanix/cleaners/containers.py +82 -0
- cleanix/cleaners/coredumps.py +32 -0
- cleanix/cleaners/desktop_extras.py +42 -0
- cleanix/cleaners/dev_caches.py +57 -0
- cleanix/cleaners/distro_pkg.py +127 -0
- cleanix/cleaners/dnf.py +56 -0
- cleanix/cleaners/editor_litter.py +115 -0
- cleanix/cleaners/font_cache.py +29 -0
- cleanix/cleaners/ide.py +87 -0
- cleanix/cleaners/kernels.py +115 -0
- cleanix/cleaners/lang_caches.py +70 -0
- cleanix/cleaners/linux_extras.py +77 -0
- cleanix/cleaners/localizations.py +70 -0
- cleanix/cleaners/logs.py +80 -0
- cleanix/cleaners/macos.py +166 -0
- cleanix/cleaners/macos_extra.py +125 -0
- cleanix/cleaners/memory.py +110 -0
- cleanix/cleaners/more_pkg.py +168 -0
- cleanix/cleaners/npm_cache.py +36 -0
- cleanix/cleaners/packaging_extras.py +140 -0
- cleanix/cleaners/pacman.py +63 -0
- cleanix/cleaners/pip_cache.py +27 -0
- cleanix/cleaners/snapshots.py +126 -0
- cleanix/cleaners/sys_extras.py +109 -0
- cleanix/cleaners/temp_files.py +48 -0
- cleanix/cleaners/thumbnails.py +31 -0
- cleanix/cleaners/trash.py +47 -0
- cleanix/cleaners/user_cache.py +69 -0
- cleanix/cleaners/virtualization.py +76 -0
- cleanix/cli.py +810 -0
- cleanix/completion.py +131 -0
- cleanix/config.py +225 -0
- cleanix/core/__init__.py +1 -0
- cleanix/core/context.py +147 -0
- cleanix/core/engine.py +155 -0
- cleanix/core/history.py +55 -0
- cleanix/core/models.py +141 -0
- cleanix/core/platform.py +117 -0
- cleanix/core/quarantine.py +147 -0
- cleanix/core/registry.py +58 -0
- cleanix/core/report.py +130 -0
- cleanix/core/safety.py +166 -0
- cleanix/core/utils.py +244 -0
- cleanix/reset.py +328 -0
- cleanix/scheduler/__init__.py +1 -0
- cleanix/scheduler/systemd.py +160 -0
- cleanix_cli-1.0.1.dist-info/METADATA +436 -0
- cleanix_cli-1.0.1.dist-info/RECORD +64 -0
- cleanix_cli-1.0.1.dist-info/WHEEL +5 -0
- cleanix_cli-1.0.1.dist-info/entry_points.txt +2 -0
- cleanix_cli-1.0.1.dist-info/top_level.txt +1 -0
cleanix/core/history.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Clean-run history and lifetime statistics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Dict, List
|
|
9
|
+
|
|
10
|
+
from cleanix.core.context import invoking_user
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _history_file() -> Path:
|
|
14
|
+
return (
|
|
15
|
+
invoking_user().home / ".local" / "state" / "cleanix" / "history.jsonl"
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def record(freed: int, items: int, *, mode: str) -> None:
|
|
20
|
+
"""Append a completed clean run to the history log. ``mode`` is one of
|
|
21
|
+
'delete', 'quarantine'."""
|
|
22
|
+
path = _history_file()
|
|
23
|
+
try:
|
|
24
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
entry = {"time": time.time(), "freed": freed, "items": items, "mode": mode}
|
|
26
|
+
with path.open("a") as fh:
|
|
27
|
+
fh.write(json.dumps(entry) + "\n")
|
|
28
|
+
except OSError:
|
|
29
|
+
pass # history is best-effort; never fail a clean over it
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def load() -> List[Dict]:
|
|
33
|
+
path = _history_file()
|
|
34
|
+
if not path.exists():
|
|
35
|
+
return []
|
|
36
|
+
entries: List[Dict] = []
|
|
37
|
+
try:
|
|
38
|
+
for line in path.read_text().splitlines():
|
|
39
|
+
line = line.strip()
|
|
40
|
+
if line:
|
|
41
|
+
entries.append(json.loads(line))
|
|
42
|
+
except (OSError, ValueError):
|
|
43
|
+
return entries
|
|
44
|
+
return entries
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def stats() -> Dict:
|
|
48
|
+
entries = load()
|
|
49
|
+
return {
|
|
50
|
+
"runs": len(entries),
|
|
51
|
+
"total_freed": sum(e.get("freed", 0) for e in entries),
|
|
52
|
+
"total_items": sum(e.get("items", 0) for e in entries),
|
|
53
|
+
"last_time": entries[-1]["time"] if entries else 0,
|
|
54
|
+
"entries": entries,
|
|
55
|
+
}
|
cleanix/core/models.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Dataclasses shared across cleanix.
|
|
2
|
+
|
|
3
|
+
The scan phase produces :class:`CleanableItem` objects grouped into a
|
|
4
|
+
:class:`CleanerReport` per cleaner. The clean phase turns each item into a
|
|
5
|
+
:class:`CleanOutcome`. Nothing here performs I/O — that keeps the data model
|
|
6
|
+
easy to serialize (for JSON reports and scheduled runs) and easy to test.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from enum import Enum
|
|
13
|
+
from typing import List, Optional, Sequence
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ItemKind(str, Enum):
|
|
17
|
+
"""How an item is removed."""
|
|
18
|
+
|
|
19
|
+
PATH = "path" # a file or directory to delete
|
|
20
|
+
COMMAND = "command" # an external command to run (e.g. `apt-get clean`)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class CleanableItem:
|
|
25
|
+
"""One removable thing discovered during a scan.
|
|
26
|
+
|
|
27
|
+
Either ``path`` (for ``PATH`` kind) or ``command`` (for ``COMMAND`` kind)
|
|
28
|
+
must be set. ``size`` is the number of bytes that would be reclaimed; for
|
|
29
|
+
command-based items it is a best-effort estimate and may be 0.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
cleaner_id: str
|
|
33
|
+
description: str
|
|
34
|
+
size: int = 0
|
|
35
|
+
kind: ItemKind = ItemKind.PATH
|
|
36
|
+
path: Optional[str] = None
|
|
37
|
+
command: Optional[Sequence[str]] = None
|
|
38
|
+
requires_root: bool = False
|
|
39
|
+
# Report-only items are surfaced with their size but are NEVER deleted by
|
|
40
|
+
# cleanix. Used for backups/snapshots/device data — things a user should
|
|
41
|
+
# review and remove deliberately. ``hint`` explains how to remove manually.
|
|
42
|
+
report_only: bool = False
|
|
43
|
+
hint: Optional[str] = None
|
|
44
|
+
|
|
45
|
+
def __post_init__(self) -> None:
|
|
46
|
+
if self.kind is ItemKind.PATH and not self.path:
|
|
47
|
+
raise ValueError("PATH item requires a path")
|
|
48
|
+
if self.kind is ItemKind.COMMAND and not self.command:
|
|
49
|
+
raise ValueError("COMMAND item requires a command")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class CleanerReport:
|
|
54
|
+
"""The result of scanning with a single cleaner."""
|
|
55
|
+
|
|
56
|
+
cleaner_id: str
|
|
57
|
+
name: str
|
|
58
|
+
description: str
|
|
59
|
+
items: List[CleanableItem] = field(default_factory=list)
|
|
60
|
+
skipped_reason: Optional[str] = None # set when the cleaner could not run
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def total_size(self) -> int:
|
|
64
|
+
return sum(i.size for i in self.items)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def count(self) -> int:
|
|
68
|
+
return len(self.items)
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def ran(self) -> bool:
|
|
72
|
+
return self.skipped_reason is None
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def report_only(self) -> bool:
|
|
76
|
+
"""True if this cleaner only surfaces (never deletes) its items."""
|
|
77
|
+
return bool(self.items) and all(i.report_only for i in self.items)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class ScanResult:
|
|
82
|
+
"""Aggregated scan across all selected cleaners."""
|
|
83
|
+
|
|
84
|
+
reports: List[CleanerReport] = field(default_factory=list)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def total_size(self) -> int:
|
|
88
|
+
return sum(r.total_size for r in self.reports)
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def total_items(self) -> int:
|
|
92
|
+
return sum(r.count for r in self.reports)
|
|
93
|
+
|
|
94
|
+
def all_items(self) -> List[CleanableItem]:
|
|
95
|
+
return [item for r in self.reports for item in r.items]
|
|
96
|
+
|
|
97
|
+
def cleanable_items(self) -> List[CleanableItem]:
|
|
98
|
+
"""Items eligible for deletion (excludes report-only)."""
|
|
99
|
+
return [i for i in self.all_items() if not i.report_only]
|
|
100
|
+
|
|
101
|
+
def report_only_items(self) -> List[CleanableItem]:
|
|
102
|
+
return [i for i in self.all_items() if i.report_only]
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def cleanable_size(self) -> int:
|
|
106
|
+
return sum(i.size for i in self.cleanable_items())
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def report_only_size(self) -> int:
|
|
110
|
+
return sum(i.size for i in self.report_only_items())
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class CleanOutcome:
|
|
115
|
+
"""The result of attempting to remove one item."""
|
|
116
|
+
|
|
117
|
+
item: CleanableItem
|
|
118
|
+
removed: bool
|
|
119
|
+
freed: int = 0
|
|
120
|
+
error: Optional[str] = None
|
|
121
|
+
dry_run: bool = False
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass
|
|
125
|
+
class CleanResult:
|
|
126
|
+
"""Aggregated result of a clean run."""
|
|
127
|
+
|
|
128
|
+
outcomes: List[CleanOutcome] = field(default_factory=list)
|
|
129
|
+
dry_run: bool = False
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def freed(self) -> int:
|
|
133
|
+
return sum(o.freed for o in self.outcomes)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def removed_count(self) -> int:
|
|
137
|
+
return sum(1 for o in self.outcomes if o.removed)
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def errors(self) -> List[CleanOutcome]:
|
|
141
|
+
return [o for o in self.outcomes if o.error]
|
cleanix/core/platform.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Operating-system / distribution detection.
|
|
2
|
+
|
|
3
|
+
Cleanix targets every *nix flavour, so cleaners declare which platforms they
|
|
4
|
+
apply to and the engine only runs the relevant ones. Detection is cheap and
|
|
5
|
+
cached. Distro detection parses ``/etc/os-release`` (freedesktop standard,
|
|
6
|
+
present on virtually all modern Linux distros).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import platform as _platform
|
|
12
|
+
from functools import lru_cache
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Dict, Iterable, Set
|
|
15
|
+
|
|
16
|
+
# Canonical platform tokens used by cleaners.
|
|
17
|
+
LINUX = "linux"
|
|
18
|
+
MACOS = "macos"
|
|
19
|
+
FREEBSD = "freebsd"
|
|
20
|
+
OPENBSD = "openbsd"
|
|
21
|
+
NETBSD = "netbsd"
|
|
22
|
+
DRAGONFLY = "dragonfly"
|
|
23
|
+
SUNOS = "sunos" # Solaris / illumos
|
|
24
|
+
UNKNOWN = "unknown"
|
|
25
|
+
|
|
26
|
+
ALL = "*" # sentinel: cleaner applies to every platform
|
|
27
|
+
|
|
28
|
+
BSD: Set[str] = {FREEBSD, OPENBSD, NETBSD, DRAGONFLY}
|
|
29
|
+
|
|
30
|
+
# Platforms that follow the freedesktop/XDG layout (~/.cache, ~/.local/share,
|
|
31
|
+
# freedesktop Trash, etc.). macOS uses ~/Library instead and is excluded.
|
|
32
|
+
XDG_PLATFORMS = (LINUX, FREEBSD, OPENBSD, NETBSD, DRAGONFLY)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@lru_cache(maxsize=1)
|
|
36
|
+
def current_os() -> str:
|
|
37
|
+
system = _platform.system().lower()
|
|
38
|
+
if system == "linux":
|
|
39
|
+
return LINUX
|
|
40
|
+
if system == "darwin":
|
|
41
|
+
return MACOS
|
|
42
|
+
if "freebsd" in system:
|
|
43
|
+
return FREEBSD
|
|
44
|
+
if "openbsd" in system:
|
|
45
|
+
return OPENBSD
|
|
46
|
+
if "netbsd" in system:
|
|
47
|
+
return NETBSD
|
|
48
|
+
if "dragonfly" in system:
|
|
49
|
+
return DRAGONFLY
|
|
50
|
+
if system == "sunos":
|
|
51
|
+
return SUNOS
|
|
52
|
+
return UNKNOWN
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@lru_cache(maxsize=1)
|
|
56
|
+
def os_release() -> Dict[str, str]:
|
|
57
|
+
"""Parse /etc/os-release into a dict (empty on non-Linux or if absent)."""
|
|
58
|
+
data: Dict[str, str] = {}
|
|
59
|
+
for candidate in ("/etc/os-release", "/usr/lib/os-release"):
|
|
60
|
+
p = Path(candidate)
|
|
61
|
+
if not p.exists():
|
|
62
|
+
continue
|
|
63
|
+
try:
|
|
64
|
+
for line in p.read_text().splitlines():
|
|
65
|
+
line = line.strip()
|
|
66
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
67
|
+
continue
|
|
68
|
+
key, _, value = line.partition("=")
|
|
69
|
+
data[key.strip()] = value.strip().strip('"').strip("'")
|
|
70
|
+
except OSError:
|
|
71
|
+
continue
|
|
72
|
+
break
|
|
73
|
+
return data
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def current_distro() -> str:
|
|
77
|
+
"""Distro id, e.g. ``fedora``, ``debian``, ``ubuntu``, ``arch`` (or "")."""
|
|
78
|
+
return os_release().get("ID", "").lower()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def distro_like() -> Set[str]:
|
|
82
|
+
"""The ``ID_LIKE`` family set, e.g. {'debian'} for Ubuntu."""
|
|
83
|
+
return set(os_release().get("ID_LIKE", "").lower().split())
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def distro_family() -> Set[str]:
|
|
87
|
+
"""Distro id plus its ID_LIKE ancestry, for family checks."""
|
|
88
|
+
fam = {current_distro()} | distro_like()
|
|
89
|
+
fam.discard("")
|
|
90
|
+
return fam
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def is_bsd() -> bool:
|
|
94
|
+
return current_os() in BSD
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def is_linux() -> bool:
|
|
98
|
+
return current_os() == LINUX
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def is_macos() -> bool:
|
|
102
|
+
return current_os() == MACOS
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def supports(platforms: Iterable[str]) -> bool:
|
|
106
|
+
"""True if a cleaner declaring ``platforms`` applies to this machine."""
|
|
107
|
+
plats = set(platforms)
|
|
108
|
+
return ALL in plats or current_os() in plats
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def os_label() -> str:
|
|
112
|
+
"""Human label, e.g. ``fedora (linux)`` or ``macos``."""
|
|
113
|
+
distro = current_distro()
|
|
114
|
+
if distro:
|
|
115
|
+
pretty = os_release().get("PRETTY_NAME") or distro
|
|
116
|
+
return f"{pretty}"
|
|
117
|
+
return current_os()
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Reversible cleaning: move junk to a quarantine instead of deleting it.
|
|
2
|
+
|
|
3
|
+
``cleanix clean --quarantine`` moves items into a per-run quarantine directory
|
|
4
|
+
and writes a manifest. ``cleanix restore`` moves them back; ``cleanix quarantine
|
|
5
|
+
empty`` reclaims the space for good. This makes cleaning undoable — a safety net
|
|
6
|
+
most cleaners don't offer.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Dict, List, Optional
|
|
17
|
+
|
|
18
|
+
from cleanix.core.context import invoking_user
|
|
19
|
+
from cleanix.core.utils import path_size
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def quarantine_root() -> Path:
|
|
23
|
+
return invoking_user().home / ".local" / "state" / "cleanix" / "quarantine"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Quarantine:
|
|
27
|
+
"""A single quarantine run (a batch of moved items)."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, run_id: str):
|
|
30
|
+
self.run_id = run_id
|
|
31
|
+
self.dir = quarantine_root() / run_id
|
|
32
|
+
self.files_dir = self.dir / "files"
|
|
33
|
+
self.items: List[Dict] = []
|
|
34
|
+
|
|
35
|
+
def store(self, path: os.PathLike | str) -> None:
|
|
36
|
+
"""Move ``path`` into this quarantine run, recording its origin."""
|
|
37
|
+
src = Path(os.path.abspath(str(path)))
|
|
38
|
+
size = path_size(src)
|
|
39
|
+
self.files_dir.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
idx = len(self.items)
|
|
41
|
+
dest = self.files_dir / f"{idx}__{src.name}"
|
|
42
|
+
shutil.move(str(src), str(dest))
|
|
43
|
+
self.items.append(
|
|
44
|
+
{"original": str(src), "stored": str(dest), "size": size}
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def save(self) -> None:
|
|
48
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
(self.dir / "manifest.json").write_text(
|
|
50
|
+
json.dumps(
|
|
51
|
+
{"run_id": self.run_id, "created": time.time(), "items": self.items},
|
|
52
|
+
indent=2,
|
|
53
|
+
)
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def size(self) -> int:
|
|
58
|
+
return sum(i["size"] for i in self.items)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def new_run() -> Quarantine:
|
|
62
|
+
run_id = f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}"
|
|
63
|
+
return Quarantine(run_id)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _read_manifest(run_dir: Path) -> Optional[Dict]:
|
|
67
|
+
mf = run_dir / "manifest.json"
|
|
68
|
+
if not mf.exists():
|
|
69
|
+
return None
|
|
70
|
+
try:
|
|
71
|
+
return json.loads(mf.read_text())
|
|
72
|
+
except (OSError, ValueError):
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def list_runs() -> List[Dict]:
|
|
77
|
+
root = quarantine_root()
|
|
78
|
+
runs: List[Dict] = []
|
|
79
|
+
if not root.is_dir():
|
|
80
|
+
return runs
|
|
81
|
+
for run_dir in sorted(root.iterdir()):
|
|
82
|
+
data = _read_manifest(run_dir)
|
|
83
|
+
if not data:
|
|
84
|
+
continue
|
|
85
|
+
runs.append(
|
|
86
|
+
{
|
|
87
|
+
"run_id": data.get("run_id", run_dir.name),
|
|
88
|
+
"created": data.get("created", 0),
|
|
89
|
+
"count": len(data.get("items", [])),
|
|
90
|
+
"size": sum(i.get("size", 0) for i in data.get("items", [])),
|
|
91
|
+
}
|
|
92
|
+
)
|
|
93
|
+
return runs
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def latest_run() -> Optional[str]:
|
|
97
|
+
runs = list_runs()
|
|
98
|
+
return runs[-1]["run_id"] if runs else None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def restore(run_id: str) -> Dict:
|
|
102
|
+
"""Move a run's items back to their original locations."""
|
|
103
|
+
run_dir = quarantine_root() / run_id
|
|
104
|
+
data = _read_manifest(run_dir)
|
|
105
|
+
if not data:
|
|
106
|
+
raise FileNotFoundError(f"no quarantine run '{run_id}'")
|
|
107
|
+
|
|
108
|
+
restored, failed = [], []
|
|
109
|
+
for item in data.get("items", []):
|
|
110
|
+
original = Path(item["original"])
|
|
111
|
+
stored = Path(item["stored"])
|
|
112
|
+
if not stored.exists():
|
|
113
|
+
failed.append((item["original"], "missing from quarantine"))
|
|
114
|
+
continue
|
|
115
|
+
if original.exists():
|
|
116
|
+
failed.append((item["original"], "destination already exists"))
|
|
117
|
+
continue
|
|
118
|
+
try:
|
|
119
|
+
original.parent.mkdir(parents=True, exist_ok=True)
|
|
120
|
+
shutil.move(str(stored), str(original))
|
|
121
|
+
restored.append(item["original"])
|
|
122
|
+
except OSError as exc:
|
|
123
|
+
failed.append((item["original"], str(exc)))
|
|
124
|
+
|
|
125
|
+
# If everything came back, drop the (now empty) run.
|
|
126
|
+
if not failed:
|
|
127
|
+
shutil.rmtree(run_dir, ignore_errors=True)
|
|
128
|
+
return {"restored": restored, "failed": failed}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def purge(run_id: str) -> int:
|
|
132
|
+
run_dir = quarantine_root() / run_id
|
|
133
|
+
data = _read_manifest(run_dir)
|
|
134
|
+
size = sum(i.get("size", 0) for i in data.get("items", [])) if data else 0
|
|
135
|
+
shutil.rmtree(run_dir, ignore_errors=True)
|
|
136
|
+
return size
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def purge_all() -> int:
|
|
140
|
+
total = 0
|
|
141
|
+
for run in list_runs():
|
|
142
|
+
total += purge(run["run_id"])
|
|
143
|
+
return total
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def total_size() -> int:
|
|
147
|
+
return sum(r["size"] for r in list_runs())
|
cleanix/core/registry.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Cleaner discovery and selection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Dict, List, Optional, Sequence
|
|
6
|
+
|
|
7
|
+
from cleanix.cleaners import ALL_CLEANERS
|
|
8
|
+
from cleanix.cleaners.base import Cleaner
|
|
9
|
+
from cleanix.config import Config
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def build_cleaners(
|
|
13
|
+
config: Config,
|
|
14
|
+
only: Optional[Sequence[str]] = None,
|
|
15
|
+
exclude: Optional[Sequence[str]] = None,
|
|
16
|
+
) -> List[Cleaner]:
|
|
17
|
+
"""Instantiate the selected cleaners in registry order.
|
|
18
|
+
|
|
19
|
+
``only`` restricts to the given ids (case-insensitive). ``exclude`` and the
|
|
20
|
+
config's ``disabled_cleaners`` remove ids. ``only`` wins over disables so a
|
|
21
|
+
user can force a specific cleaner even if it is disabled by default.
|
|
22
|
+
"""
|
|
23
|
+
only_set = {c.lower() for c in only} if only else None
|
|
24
|
+
exclude_set = {c.lower() for c in (exclude or [])}
|
|
25
|
+
disabled = {c.lower() for c in config.disabled_cleaners}
|
|
26
|
+
|
|
27
|
+
selected: List[Cleaner] = []
|
|
28
|
+
for cls in ALL_CLEANERS:
|
|
29
|
+
cid = cls.id.lower()
|
|
30
|
+
instance = cls(config)
|
|
31
|
+
if only_set is not None:
|
|
32
|
+
# Explicit selection wins even over platform/disable filters.
|
|
33
|
+
if cid not in only_set:
|
|
34
|
+
continue
|
|
35
|
+
else:
|
|
36
|
+
if cid in exclude_set or cid in disabled:
|
|
37
|
+
continue
|
|
38
|
+
# Skip cleaners that don't apply to this operating system.
|
|
39
|
+
if not instance.supported():
|
|
40
|
+
continue
|
|
41
|
+
# Skip opt-in-only cleaners unless explicitly selected.
|
|
42
|
+
if not instance.default_enabled:
|
|
43
|
+
continue
|
|
44
|
+
selected.append(instance)
|
|
45
|
+
return selected
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def known_ids() -> List[str]:
|
|
49
|
+
return [c.id for c in ALL_CLEANERS]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def describe_all(config: Config) -> Dict[str, Cleaner]:
|
|
53
|
+
return {c.id: c(config) for c in ALL_CLEANERS}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def unknown_ids(ids: Sequence[str]) -> List[str]:
|
|
57
|
+
known = {i.lower() for i in known_ids()}
|
|
58
|
+
return [i for i in ids if i.lower() not in known]
|
cleanix/core/report.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Rendering scan/clean results as rich tables or JSON."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, Dict
|
|
7
|
+
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.table import Table
|
|
10
|
+
|
|
11
|
+
from cleanix.core.models import CleanResult, ScanResult
|
|
12
|
+
from cleanix.core.utils import human_size
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def render_scan_table(
|
|
16
|
+
result: ScanResult, console: Console, *, sort: str = "none", top: int = 0
|
|
17
|
+
) -> None:
|
|
18
|
+
table = Table(title="Cleanix — scan results", show_lines=False)
|
|
19
|
+
table.add_column("Cleaner", style="cyan", no_wrap=True)
|
|
20
|
+
table.add_column("Items", justify="right")
|
|
21
|
+
table.add_column("Reclaimable", justify="right", style="green")
|
|
22
|
+
table.add_column("Notes", style="dim")
|
|
23
|
+
|
|
24
|
+
reports = list(result.reports)
|
|
25
|
+
if sort == "size":
|
|
26
|
+
reports.sort(key=lambda r: r.total_size, reverse=True)
|
|
27
|
+
elif sort == "name":
|
|
28
|
+
reports.sort(key=lambda r: r.name.lower())
|
|
29
|
+
if top and top > 0:
|
|
30
|
+
# Show only the N with something to clean; keep the rest out of the way.
|
|
31
|
+
nonempty = [r for r in reports if r.count]
|
|
32
|
+
reports = (nonempty if sort != "none" else
|
|
33
|
+
sorted(nonempty, key=lambda r: r.total_size, reverse=True))[:top]
|
|
34
|
+
|
|
35
|
+
for report in reports:
|
|
36
|
+
if not report.ran:
|
|
37
|
+
table.add_row(report.name, "-", "-", report.skipped_reason or "skipped")
|
|
38
|
+
continue
|
|
39
|
+
if report.count == 0:
|
|
40
|
+
table.add_row(report.name, "0", "-", "clean")
|
|
41
|
+
continue
|
|
42
|
+
note = report.description
|
|
43
|
+
size_cell = human_size(report.total_size)
|
|
44
|
+
if report.report_only:
|
|
45
|
+
note = "[yellow]report only — review manually[/yellow]"
|
|
46
|
+
size_cell = f"[yellow]{size_cell}[/yellow]"
|
|
47
|
+
table.add_row(report.name, str(report.count), size_cell, note)
|
|
48
|
+
|
|
49
|
+
table.add_section()
|
|
50
|
+
table.add_row(
|
|
51
|
+
"[bold]TOTAL (cleanable)[/bold]",
|
|
52
|
+
f"[bold]{len(result.cleanable_items())}[/bold]",
|
|
53
|
+
f"[bold]{human_size(result.cleanable_size)}[/bold]",
|
|
54
|
+
"",
|
|
55
|
+
)
|
|
56
|
+
if result.report_only_items():
|
|
57
|
+
table.add_row(
|
|
58
|
+
"[yellow]report-only[/yellow]",
|
|
59
|
+
f"[yellow]{len(result.report_only_items())}[/yellow]",
|
|
60
|
+
f"[yellow]{human_size(result.report_only_size)}[/yellow]",
|
|
61
|
+
"[dim]not deleted by cleanix[/dim]",
|
|
62
|
+
)
|
|
63
|
+
console.print(table)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def render_report_only(result: ScanResult, console: Console) -> None:
|
|
67
|
+
"""List report-only findings with manual-removal hints."""
|
|
68
|
+
items = result.report_only_items()
|
|
69
|
+
if not items:
|
|
70
|
+
return
|
|
71
|
+
table = Table(
|
|
72
|
+
title="Report-only — review and remove manually (never auto-deleted)",
|
|
73
|
+
title_style="yellow",
|
|
74
|
+
)
|
|
75
|
+
table.add_column("Size", justify="right", style="yellow")
|
|
76
|
+
table.add_column("What", style="cyan")
|
|
77
|
+
table.add_column("How to remove", style="dim")
|
|
78
|
+
for i in sorted(items, key=lambda x: x.size, reverse=True):
|
|
79
|
+
table.add_row(human_size(i.size), i.description, i.hint or "")
|
|
80
|
+
console.print(table)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def render_clean_summary(result: CleanResult, console: Console) -> None:
|
|
84
|
+
verb = "Would free" if result.dry_run else "Freed"
|
|
85
|
+
style = "yellow" if result.dry_run else "green"
|
|
86
|
+
console.print(
|
|
87
|
+
f"[{style}]{verb} {human_size(result.freed)} "
|
|
88
|
+
f"across {result.removed_count if not result.dry_run else len(result.outcomes)} "
|
|
89
|
+
f"item(s).[/{style}]"
|
|
90
|
+
)
|
|
91
|
+
for outcome in result.errors:
|
|
92
|
+
console.print(
|
|
93
|
+
f" [red]![/red] {outcome.item.description}: {outcome.error}"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def scan_to_dict(result: ScanResult) -> Dict[str, Any]:
|
|
98
|
+
return {
|
|
99
|
+
"total_items": result.total_items,
|
|
100
|
+
"total_bytes": result.total_size,
|
|
101
|
+
"total_human": human_size(result.total_size),
|
|
102
|
+
"cleaners": [
|
|
103
|
+
{
|
|
104
|
+
"id": r.cleaner_id,
|
|
105
|
+
"name": r.name,
|
|
106
|
+
"ran": r.ran,
|
|
107
|
+
"skipped_reason": r.skipped_reason,
|
|
108
|
+
"count": r.count,
|
|
109
|
+
"bytes": r.total_size,
|
|
110
|
+
"human": human_size(r.total_size),
|
|
111
|
+
"items": [
|
|
112
|
+
{
|
|
113
|
+
"description": i.description,
|
|
114
|
+
"bytes": i.size,
|
|
115
|
+
"path": i.path,
|
|
116
|
+
"command": list(i.command) if i.command else None,
|
|
117
|
+
"requires_root": i.requires_root,
|
|
118
|
+
"report_only": i.report_only,
|
|
119
|
+
"hint": i.hint,
|
|
120
|
+
}
|
|
121
|
+
for i in r.items
|
|
122
|
+
],
|
|
123
|
+
}
|
|
124
|
+
for r in result.reports
|
|
125
|
+
],
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def scan_to_json(result: ScanResult) -> str:
|
|
130
|
+
return json.dumps(scan_to_dict(result), indent=2)
|