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/completion.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Shell-completion script generation for bash, zsh and fish.
|
|
2
|
+
|
|
3
|
+
Scripts are generated with the live subcommand list, cleaner ids and config keys
|
|
4
|
+
baked in, so completion always matches this build.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from cleanix.config import field_names
|
|
10
|
+
from cleanix.core.registry import known_ids
|
|
11
|
+
|
|
12
|
+
SUBCOMMANDS = [
|
|
13
|
+
"list", "scan", "clean", "info", "stats", "restore", "quarantine",
|
|
14
|
+
"config", "schedule", "factory-reset", "completion",
|
|
15
|
+
]
|
|
16
|
+
SCAN_CLEAN_OPTS = [
|
|
17
|
+
"--only", "--exclude", "--json", "--output", "--quiet", "--summary",
|
|
18
|
+
"--sort", "--top", "--all-users", "--current-user", "--min-uid",
|
|
19
|
+
"--execute", "--yes", "--quarantine",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _ids() -> str:
|
|
24
|
+
return " ".join(known_ids())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _keys() -> str:
|
|
28
|
+
return " ".join(field_names())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def bash_script() -> str:
|
|
32
|
+
return f"""# cleanix bash completion — source this file or install to
|
|
33
|
+
# /etc/bash_completion.d/cleanix
|
|
34
|
+
_cleanix() {{
|
|
35
|
+
local cur prev words cword
|
|
36
|
+
cur="${{COMP_WORDS[COMP_CWORD]}}"
|
|
37
|
+
prev="${{COMP_WORDS[COMP_CWORD-1]}}"
|
|
38
|
+
local sub="{' '.join(SUBCOMMANDS)}"
|
|
39
|
+
local cleaners="{_ids()}"
|
|
40
|
+
local cfgkeys="{_keys()}"
|
|
41
|
+
|
|
42
|
+
if [ "$COMP_CWORD" -eq 1 ]; then
|
|
43
|
+
COMPREPLY=( $(compgen -W "$sub" -- "$cur") ); return
|
|
44
|
+
fi
|
|
45
|
+
case "$prev" in
|
|
46
|
+
--only|--exclude)
|
|
47
|
+
COMPREPLY=( $(compgen -W "$cleaners" -- "$cur") ); return;;
|
|
48
|
+
--sort) COMPREPLY=( $(compgen -W "none size name" -- "$cur") ); return;;
|
|
49
|
+
esac
|
|
50
|
+
case "${{COMP_WORDS[1]}}" in
|
|
51
|
+
scan|clean)
|
|
52
|
+
COMPREPLY=( $(compgen -W "{' '.join(SCAN_CLEAN_OPTS)}" -- "$cur") );;
|
|
53
|
+
config)
|
|
54
|
+
if [ "$COMP_CWORD" -eq 2 ]; then
|
|
55
|
+
COMPREPLY=( $(compgen -W "list get set unset path" -- "$cur") )
|
|
56
|
+
else
|
|
57
|
+
COMPREPLY=( $(compgen -W "$cfgkeys" -- "$cur") )
|
|
58
|
+
fi;;
|
|
59
|
+
quarantine)
|
|
60
|
+
COMPREPLY=( $(compgen -W "list empty" -- "$cur") );;
|
|
61
|
+
schedule)
|
|
62
|
+
COMPREPLY=( $(compgen -W "install uninstall status --frequency" -- "$cur") );;
|
|
63
|
+
factory-reset)
|
|
64
|
+
COMPREPLY=( $(compgen -W "--scope --execute" -- "$cur") );;
|
|
65
|
+
completion)
|
|
66
|
+
COMPREPLY=( $(compgen -W "bash zsh fish" -- "$cur") );;
|
|
67
|
+
list) COMPREPLY=( $(compgen -W "--all" -- "$cur") );;
|
|
68
|
+
esac
|
|
69
|
+
}}
|
|
70
|
+
complete -F _cleanix cleanix
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def zsh_script() -> str:
|
|
75
|
+
return f"""#compdef cleanix
|
|
76
|
+
# cleanix zsh completion — install to a dir on your $fpath as _cleanix
|
|
77
|
+
_cleanix() {{
|
|
78
|
+
local -a subs cleaners cfgkeys
|
|
79
|
+
subs=({' '.join(SUBCOMMANDS)})
|
|
80
|
+
cleaners=({_ids()})
|
|
81
|
+
cfgkeys=({_keys()})
|
|
82
|
+
if (( CURRENT == 2 )); then
|
|
83
|
+
_describe 'command' subs; return
|
|
84
|
+
fi
|
|
85
|
+
case "$words[2]" in
|
|
86
|
+
scan|clean)
|
|
87
|
+
case "$words[CURRENT-1]" in
|
|
88
|
+
--only|--exclude) _values 'cleaner' $cleaners; return;;
|
|
89
|
+
--sort) _values 'sort' none size name; return;;
|
|
90
|
+
esac
|
|
91
|
+
_values 'option' {' '.join(SCAN_CLEAN_OPTS)};;
|
|
92
|
+
config)
|
|
93
|
+
if (( CURRENT == 3 )); then _values 'action' list get set unset path
|
|
94
|
+
else _values 'key' $cfgkeys; fi;;
|
|
95
|
+
quarantine) _values 'action' list empty;;
|
|
96
|
+
schedule) _values 'action' install uninstall status;;
|
|
97
|
+
completion) _values 'shell' bash zsh fish;;
|
|
98
|
+
esac
|
|
99
|
+
}}
|
|
100
|
+
compdef _cleanix cleanix
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def fish_script() -> str:
|
|
105
|
+
lines = [
|
|
106
|
+
"# cleanix fish completion — install to "
|
|
107
|
+
"~/.config/fish/completions/cleanix.fish",
|
|
108
|
+
"complete -c cleanix -f",
|
|
109
|
+
]
|
|
110
|
+
subs = " ".join(SUBCOMMANDS)
|
|
111
|
+
lines.append(
|
|
112
|
+
f'complete -c cleanix -n "__fish_use_subcommand" -a "{subs}"'
|
|
113
|
+
)
|
|
114
|
+
for opt in ("--only", "--exclude"):
|
|
115
|
+
lines.append(
|
|
116
|
+
f'complete -c cleanix -n "__fish_seen_subcommand_from scan clean" '
|
|
117
|
+
f'-l {opt.lstrip("-")} -a "{_ids()}"'
|
|
118
|
+
)
|
|
119
|
+
lines.append(
|
|
120
|
+
'complete -c cleanix -n "__fish_seen_subcommand_from config" '
|
|
121
|
+
f'-a "list get set unset path {_keys()}"'
|
|
122
|
+
)
|
|
123
|
+
lines.append(
|
|
124
|
+
'complete -c cleanix -n "__fish_seen_subcommand_from completion" '
|
|
125
|
+
'-a "bash zsh fish"'
|
|
126
|
+
)
|
|
127
|
+
return "\n".join(lines) + "\n"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def generate(shell: str) -> str:
|
|
131
|
+
return {"bash": bash_script, "zsh": zsh_script, "fish": fish_script}[shell]()
|
cleanix/config.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""Configuration: sane defaults plus optional YAML overrides.
|
|
2
|
+
|
|
3
|
+
Defaults are defined in code so cleanix works with zero configuration. Users
|
|
4
|
+
may drop a YAML file at ``~/.config/cleanix/config.yaml`` to override any field;
|
|
5
|
+
see ``config/default.yaml`` for the shape.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from dataclasses import dataclass, field, fields
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import List
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _config_path() -> Path:
|
|
17
|
+
base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
|
|
18
|
+
return Path(base) / "cleanix" / "config.yaml"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Config:
|
|
23
|
+
"""Tunable behavior shared by every cleaner."""
|
|
24
|
+
|
|
25
|
+
# Cleaners the user has explicitly disabled (by id).
|
|
26
|
+
disabled_cleaners: List[str] = field(default_factory=list)
|
|
27
|
+
|
|
28
|
+
# Only remove temp files older than this many days.
|
|
29
|
+
temp_min_age_days: float = 3.0
|
|
30
|
+
|
|
31
|
+
# Only remove rotated logs older than this many days.
|
|
32
|
+
log_min_age_days: float = 7.0
|
|
33
|
+
|
|
34
|
+
# Keep at most this much journald history (systemd `--vacuum-size`).
|
|
35
|
+
journal_max_size_mb: int = 200
|
|
36
|
+
|
|
37
|
+
# Only remove coredumps older than this many days.
|
|
38
|
+
coredump_min_age_days: float = 3.0
|
|
39
|
+
|
|
40
|
+
# Leave loose cache files alone if modified within this many minutes
|
|
41
|
+
# (an "in use" guard against actively-written scratch files).
|
|
42
|
+
cache_min_age_minutes: float = 10.0
|
|
43
|
+
|
|
44
|
+
# Extra directories to treat as user caches to clear.
|
|
45
|
+
extra_cache_dirs: List[str] = field(default_factory=list)
|
|
46
|
+
|
|
47
|
+
# Browsers to include when clearing browser caches.
|
|
48
|
+
browsers: List[str] = field(
|
|
49
|
+
default_factory=lambda: ["firefox", "chrome", "chromium"]
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Directories scanned for dangling (broken) symlinks — a classic sign of
|
|
53
|
+
# software that was removed without cleaning up after itself.
|
|
54
|
+
symlink_scan_dirs: List[str] = field(
|
|
55
|
+
default_factory=lambda: [
|
|
56
|
+
"~/.local/bin", "~/bin", "~/.local/share/applications",
|
|
57
|
+
"/usr/local/bin", "/usr/local/sbin", "/usr/local/share/applications",
|
|
58
|
+
]
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
# When pruning container systems, also remove unused *volumes*. Off by
|
|
62
|
+
# default because volumes can hold real data.
|
|
63
|
+
docker_prune_volumes: bool = False
|
|
64
|
+
|
|
65
|
+
# Offer removal of package-update leftovers (.rpmnew/.pacnew/.dpkg-old ...).
|
|
66
|
+
remove_config_leftovers: bool = True
|
|
67
|
+
|
|
68
|
+
# Remove ``.DS_Store`` / AppleDouble (``._*``) litter from the home tree.
|
|
69
|
+
remove_apple_litter: bool = True
|
|
70
|
+
|
|
71
|
+
# AI CLI tools keep rolling config/file backups; keep this many newest and
|
|
72
|
+
# offer the older surplus for removal ("keep max N backups").
|
|
73
|
+
keep_backups: int = 2
|
|
74
|
+
|
|
75
|
+
# AI CLI session transcripts / file-history / logs older than this many days
|
|
76
|
+
# are considered stale and offered for removal (chat history is user data,
|
|
77
|
+
# so this is age-gated and conservative).
|
|
78
|
+
ai_history_max_age_days: float = 30.0
|
|
79
|
+
|
|
80
|
+
# Old-kernel removal: keep the newest N installed kernels (plus the running
|
|
81
|
+
# one is always kept by the package manager). Set remove_old_kernels=false
|
|
82
|
+
# to skip entirely.
|
|
83
|
+
remove_old_kernels: bool = True
|
|
84
|
+
keep_kernels: int = 2
|
|
85
|
+
|
|
86
|
+
# Include language "offline repository" caches whose removal forces large
|
|
87
|
+
# re-downloads and can break offline builds (Maven ~/.m2, Ivy, sbt,
|
|
88
|
+
# Coursier, NuGet, RubyGems). Off by default.
|
|
89
|
+
include_offline_repos: bool = False
|
|
90
|
+
|
|
91
|
+
# Remove editor backup/tilde litter (``*~``, ``*.orig``, ``*.bak``,
|
|
92
|
+
# ``*.rej``). Off by default — these can be intentional.
|
|
93
|
+
remove_backup_files: bool = False
|
|
94
|
+
|
|
95
|
+
# Purge locale/man-page translations for languages you don't use
|
|
96
|
+
# (localepurge-style). Off by default — frees space but affects i18n.
|
|
97
|
+
purge_unused_locales: bool = False
|
|
98
|
+
|
|
99
|
+
# Extra paths/globs that must NEVER be deleted, on top of the built-in
|
|
100
|
+
# protected paths (e.g. "~/Projects/**", "/data").
|
|
101
|
+
protected_globs: List[str] = field(default_factory=list)
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def load(cls, path: str | os.PathLike | None = None) -> "Config":
|
|
105
|
+
"""Load config, layering a YAML file over the defaults if present."""
|
|
106
|
+
cfg = cls()
|
|
107
|
+
cfg_path = Path(path) if path else _config_path()
|
|
108
|
+
if not cfg_path.exists():
|
|
109
|
+
return cfg
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
import yaml # imported lazily so the dep is optional at runtime
|
|
113
|
+
except ImportError:
|
|
114
|
+
return cfg
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
data = yaml.safe_load(cfg_path.read_text()) or {}
|
|
118
|
+
except (OSError, yaml.YAMLError):
|
|
119
|
+
return cfg
|
|
120
|
+
|
|
121
|
+
known = {f.name for f in fields(cls)}
|
|
122
|
+
for key, value in data.items():
|
|
123
|
+
if key in known and value is not None:
|
|
124
|
+
setattr(cfg, key, value)
|
|
125
|
+
return cfg
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# One-line help shown by ``cleanix config list``.
|
|
129
|
+
FIELD_HELP = {
|
|
130
|
+
"disabled_cleaners": "Cleaner ids to disable entirely",
|
|
131
|
+
"temp_min_age_days": "Only remove temp files older than N days",
|
|
132
|
+
"log_min_age_days": "Only remove rotated logs older than N days",
|
|
133
|
+
"journal_max_size_mb": "Cap journald history to N MiB when vacuuming",
|
|
134
|
+
"coredump_min_age_days": "Only remove coredumps older than N days",
|
|
135
|
+
"cache_min_age_minutes": "Leave loose cache files touched within N minutes",
|
|
136
|
+
"extra_cache_dirs": "Additional cache directories to clear",
|
|
137
|
+
"browsers": "Browsers whose caches to clear",
|
|
138
|
+
"symlink_scan_dirs": "Directories scanned for broken symlinks",
|
|
139
|
+
"docker_prune_volumes": "Also prune unused Docker/Podman volumes",
|
|
140
|
+
"remove_config_leftovers": "Offer .rpmnew/.pacnew/.dpkg-old residue",
|
|
141
|
+
"remove_apple_litter": "Remove .DS_Store / AppleDouble litter",
|
|
142
|
+
"keep_backups": "AI CLI rolling backups to keep (newest N)",
|
|
143
|
+
"ai_history_max_age_days": "AI transcripts/history older than N days are stale",
|
|
144
|
+
"remove_old_kernels": "Offer removal of superseded kernels",
|
|
145
|
+
"keep_kernels": "Number of newest kernels to keep",
|
|
146
|
+
"include_offline_repos": "Include Maven/Ivy/NuGet/etc. offline caches",
|
|
147
|
+
"remove_backup_files": "Remove *~/*.bak/*.orig/*.rej editor backups",
|
|
148
|
+
"purge_unused_locales": "Remove locale/man-page translations you don't use",
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _field_types() -> dict:
|
|
153
|
+
"""Map each config key to the Python type of its default value."""
|
|
154
|
+
defaults = Config()
|
|
155
|
+
return {f.name: type(getattr(defaults, f.name)) for f in fields(Config)}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def field_names() -> List[str]:
|
|
159
|
+
return [f.name for f in fields(Config)]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def coerce_value(key: str, raw: str):
|
|
163
|
+
"""Convert a CLI string into the correct type for config key ``key``."""
|
|
164
|
+
types = _field_types()
|
|
165
|
+
if key not in types:
|
|
166
|
+
raise KeyError(key)
|
|
167
|
+
t = types[key]
|
|
168
|
+
if t is bool:
|
|
169
|
+
low = raw.strip().lower()
|
|
170
|
+
if low in ("1", "true", "yes", "on", "y", "t"):
|
|
171
|
+
return True
|
|
172
|
+
if low in ("0", "false", "no", "off", "n", "f"):
|
|
173
|
+
return False
|
|
174
|
+
raise ValueError(f"expected a boolean for {key}, got {raw!r}")
|
|
175
|
+
if t is int:
|
|
176
|
+
return int(raw)
|
|
177
|
+
if t is float:
|
|
178
|
+
return float(raw)
|
|
179
|
+
if t is list:
|
|
180
|
+
return [p.strip() for p in raw.split(",") if p.strip()]
|
|
181
|
+
return raw
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def read_user_overrides(path: str | os.PathLike | None = None) -> dict:
|
|
185
|
+
"""Return the raw override dict from the user's YAML (or {} if none)."""
|
|
186
|
+
cfg_path = Path(path) if path else _config_path()
|
|
187
|
+
if not cfg_path.exists():
|
|
188
|
+
return {}
|
|
189
|
+
try:
|
|
190
|
+
import yaml
|
|
191
|
+
|
|
192
|
+
return yaml.safe_load(cfg_path.read_text()) or {}
|
|
193
|
+
except Exception: # noqa: BLE001
|
|
194
|
+
return {}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def write_user_override(key: str, value, path: str | os.PathLike | None = None) -> Path:
|
|
198
|
+
"""Set ``key`` in the user's YAML config, creating it if needed."""
|
|
199
|
+
import yaml
|
|
200
|
+
|
|
201
|
+
if key not in _field_types():
|
|
202
|
+
raise KeyError(key)
|
|
203
|
+
cfg_path = Path(path) if path else _config_path()
|
|
204
|
+
cfg_path.parent.mkdir(parents=True, exist_ok=True)
|
|
205
|
+
data = read_user_overrides(cfg_path)
|
|
206
|
+
data[key] = value
|
|
207
|
+
cfg_path.write_text(yaml.safe_dump(data, default_flow_style=False, sort_keys=True))
|
|
208
|
+
return cfg_path
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def remove_user_override(key: str, path: str | os.PathLike | None = None) -> bool:
|
|
212
|
+
"""Remove ``key`` from the user's YAML (revert to default). True if removed."""
|
|
213
|
+
import yaml
|
|
214
|
+
|
|
215
|
+
cfg_path = Path(path) if path else _config_path()
|
|
216
|
+
data = read_user_overrides(cfg_path)
|
|
217
|
+
if key not in data:
|
|
218
|
+
return False
|
|
219
|
+
del data[key]
|
|
220
|
+
cfg_path.write_text(yaml.safe_dump(data, default_flow_style=False, sort_keys=True))
|
|
221
|
+
return True
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def config_file_path() -> Path:
|
|
225
|
+
return _config_path()
|
cleanix/core/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core engine, models, and safety primitives for cleanix."""
|
cleanix/core/context.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Multi-user scanning context.
|
|
2
|
+
|
|
3
|
+
Per-user cleaners operate relative to "the home directory". When cleanix runs
|
|
4
|
+
unprivileged that's just the invoking user. When it runs as root it should sweep
|
|
5
|
+
*every* real user's home. This module resolves the set of target users and lets
|
|
6
|
+
the engine bind a "current user" while a cleaner runs, so cleaners can stay
|
|
7
|
+
written against a single home and automatically apply to each user.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import contextlib
|
|
13
|
+
import contextvars
|
|
14
|
+
import os
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from functools import lru_cache
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import List, Optional
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
import pwd # POSIX only (Linux, macOS, BSD)
|
|
22
|
+
except ImportError: # pragma: no cover - non-POSIX
|
|
23
|
+
pwd = None # type: ignore
|
|
24
|
+
|
|
25
|
+
from cleanix.core.platform import MACOS, current_os
|
|
26
|
+
|
|
27
|
+
# Homes that are never real user homes even if they appear in passwd.
|
|
28
|
+
_BOGUS_HOMES = {"/", "", "/nonexistent", "/dev/null", "/var/empty", "/run/nologin"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class TargetUser:
|
|
33
|
+
name: str
|
|
34
|
+
home: Path
|
|
35
|
+
uid: int
|
|
36
|
+
gid: int
|
|
37
|
+
is_invoker: bool # the user who launched cleanix (honors their XDG env)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def is_effective_root() -> bool:
|
|
41
|
+
return hasattr(os, "geteuid") and os.geteuid() == 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _default_min_uid() -> int:
|
|
45
|
+
# Human accounts start at 501 on macOS, 1000 on Linux/BSD.
|
|
46
|
+
return 500 if current_os() == MACOS else 1000
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@lru_cache(maxsize=1)
|
|
50
|
+
def invoking_user() -> TargetUser:
|
|
51
|
+
"""The real user who launched cleanix (honoring ``sudo``)."""
|
|
52
|
+
sudo_user = os.environ.get("SUDO_USER")
|
|
53
|
+
if pwd is not None:
|
|
54
|
+
try:
|
|
55
|
+
if sudo_user and is_effective_root():
|
|
56
|
+
pw = pwd.getpwnam(sudo_user)
|
|
57
|
+
else:
|
|
58
|
+
pw = pwd.getpwuid(os.geteuid())
|
|
59
|
+
return TargetUser(pw.pw_name, Path(pw.pw_dir), pw.pw_uid, pw.pw_gid, True)
|
|
60
|
+
except (KeyError, OSError):
|
|
61
|
+
pass
|
|
62
|
+
home = Path(os.path.expanduser("~"))
|
|
63
|
+
uid = os.geteuid() if hasattr(os, "geteuid") else 0
|
|
64
|
+
return TargetUser(os.environ.get("USER", "user"), home, uid, uid, True)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _all_users(min_uid: int) -> List[TargetUser]:
|
|
68
|
+
invoker = invoking_user()
|
|
69
|
+
if pwd is None:
|
|
70
|
+
return [invoker]
|
|
71
|
+
|
|
72
|
+
seen_homes = set()
|
|
73
|
+
users: List[TargetUser] = []
|
|
74
|
+
for pw in pwd.getpwall():
|
|
75
|
+
# Root plus real human accounts (uid >= min_uid); skip service accounts.
|
|
76
|
+
if pw.pw_uid != 0 and pw.pw_uid < min_uid:
|
|
77
|
+
continue
|
|
78
|
+
home = Path(pw.pw_dir)
|
|
79
|
+
if str(home) in _BOGUS_HOMES or not home.is_dir():
|
|
80
|
+
continue
|
|
81
|
+
if str(home) in seen_homes:
|
|
82
|
+
continue
|
|
83
|
+
seen_homes.add(str(home))
|
|
84
|
+
users.append(
|
|
85
|
+
TargetUser(
|
|
86
|
+
pw.pw_name, home, pw.pw_uid, pw.pw_gid,
|
|
87
|
+
is_invoker=(pw.pw_name == invoker.name),
|
|
88
|
+
)
|
|
89
|
+
)
|
|
90
|
+
if not users:
|
|
91
|
+
users = [invoker]
|
|
92
|
+
return users
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# --- configuration / caching -------------------------------------------------
|
|
96
|
+
_all_users_flag: Optional[bool] = None
|
|
97
|
+
_min_uid_override: Optional[int] = None
|
|
98
|
+
_cached_targets: Optional[List[TargetUser]] = None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def configure(all_users: Optional[bool] = None, min_uid: Optional[int] = None) -> None:
|
|
102
|
+
"""Set scanning scope. ``all_users=None`` means "all users iff root"."""
|
|
103
|
+
global _all_users_flag, _min_uid_override, _cached_targets
|
|
104
|
+
_all_users_flag = all_users
|
|
105
|
+
_min_uid_override = min_uid
|
|
106
|
+
_cached_targets = None # invalidate
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def get_target_users() -> List[TargetUser]:
|
|
110
|
+
"""The users whose homes should be scanned, per current configuration."""
|
|
111
|
+
global _cached_targets
|
|
112
|
+
if _cached_targets is not None:
|
|
113
|
+
return _cached_targets
|
|
114
|
+
|
|
115
|
+
want_all = _all_users_flag
|
|
116
|
+
if want_all is None:
|
|
117
|
+
want_all = is_effective_root()
|
|
118
|
+
|
|
119
|
+
if want_all:
|
|
120
|
+
min_uid = _min_uid_override if _min_uid_override is not None else _default_min_uid()
|
|
121
|
+
_cached_targets = _all_users(min_uid)
|
|
122
|
+
else:
|
|
123
|
+
_cached_targets = [invoking_user()]
|
|
124
|
+
return _cached_targets
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def scanning_all_users() -> bool:
|
|
128
|
+
return len(get_target_users()) > 1
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# --- current-user binding ----------------------------------------------------
|
|
132
|
+
_current: contextvars.ContextVar[Optional[TargetUser]] = contextvars.ContextVar(
|
|
133
|
+
"cleanix_current_user", default=None
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def current_user() -> TargetUser:
|
|
138
|
+
return _current.get() or invoking_user()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@contextlib.contextmanager
|
|
142
|
+
def use_user(user: TargetUser):
|
|
143
|
+
token = _current.set(user)
|
|
144
|
+
try:
|
|
145
|
+
yield user
|
|
146
|
+
finally:
|
|
147
|
+
_current.reset(token)
|
cleanix/core/engine.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""The engine: run scans and execute (or simulate) cleans.
|
|
2
|
+
|
|
3
|
+
All deletion goes through here so that the safety guard, dry-run behavior, and
|
|
4
|
+
root checks are enforced in one auditable place.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Callable, List, Optional, Sequence
|
|
11
|
+
|
|
12
|
+
from cleanix.cleaners.base import Cleaner
|
|
13
|
+
from cleanix.core import safety
|
|
14
|
+
from cleanix.core.models import (
|
|
15
|
+
CleanableItem,
|
|
16
|
+
CleanerReport,
|
|
17
|
+
CleanOutcome,
|
|
18
|
+
CleanResult,
|
|
19
|
+
ItemKind,
|
|
20
|
+
ScanResult,
|
|
21
|
+
)
|
|
22
|
+
from cleanix.core.utils import is_root, path_size, run_command
|
|
23
|
+
|
|
24
|
+
ProgressCB = Optional[Callable[[str], None]]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Engine:
|
|
28
|
+
def __init__(self, cleaners: Sequence[Cleaner]):
|
|
29
|
+
self.cleaners = list(cleaners)
|
|
30
|
+
|
|
31
|
+
# -- scanning ------------------------------------------------------------
|
|
32
|
+
def scan(self, progress: ProgressCB = None, parallel: bool = True) -> ScanResult:
|
|
33
|
+
"""Scan all cleaners. Cleaners are I/O-bound (directory walks, external
|
|
34
|
+
commands), so running them on a thread pool is a large speed-up."""
|
|
35
|
+
n = len(self.cleaners)
|
|
36
|
+
if not parallel or n <= 1:
|
|
37
|
+
reports: List[CleanerReport] = []
|
|
38
|
+
for cleaner in self.cleaners:
|
|
39
|
+
reports.append(cleaner.scan())
|
|
40
|
+
if progress:
|
|
41
|
+
progress(cleaner.name)
|
|
42
|
+
return ScanResult(reports=reports)
|
|
43
|
+
|
|
44
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
45
|
+
|
|
46
|
+
results: List[Optional[CleanerReport]] = [None] * n
|
|
47
|
+
workers = min(16, n)
|
|
48
|
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
|
49
|
+
futures = {pool.submit(c.scan): i for i, c in enumerate(self.cleaners)}
|
|
50
|
+
for fut in as_completed(futures):
|
|
51
|
+
idx = futures[fut]
|
|
52
|
+
results[idx] = fut.result()
|
|
53
|
+
if progress:
|
|
54
|
+
progress(self.cleaners[idx].name)
|
|
55
|
+
return ScanResult(reports=[r for r in results if r is not None])
|
|
56
|
+
|
|
57
|
+
# -- cleaning ------------------------------------------------------------
|
|
58
|
+
def clean(
|
|
59
|
+
self,
|
|
60
|
+
items: Sequence[CleanableItem],
|
|
61
|
+
*,
|
|
62
|
+
dry_run: bool = True,
|
|
63
|
+
allow_root_items: Optional[bool] = None,
|
|
64
|
+
progress: ProgressCB = None,
|
|
65
|
+
quarantine=None,
|
|
66
|
+
) -> CleanResult:
|
|
67
|
+
"""Remove (or simulate removing) the given items.
|
|
68
|
+
|
|
69
|
+
Root-requiring items are skipped with an error unless the process is
|
|
70
|
+
root (or ``allow_root_items`` is forced True). If ``quarantine`` is a
|
|
71
|
+
Quarantine store, path items are *moved* there (reversible) instead of
|
|
72
|
+
being deleted.
|
|
73
|
+
"""
|
|
74
|
+
if allow_root_items is None:
|
|
75
|
+
allow_root_items = is_root()
|
|
76
|
+
|
|
77
|
+
result = CleanResult(dry_run=dry_run)
|
|
78
|
+
for item in items:
|
|
79
|
+
if progress:
|
|
80
|
+
progress(item.description)
|
|
81
|
+
result.outcomes.append(
|
|
82
|
+
self._clean_one(
|
|
83
|
+
item, dry_run=dry_run, allow_root=allow_root_items,
|
|
84
|
+
quarantine=quarantine,
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
return result
|
|
88
|
+
|
|
89
|
+
def _clean_one(
|
|
90
|
+
self, item: CleanableItem, *, dry_run: bool, allow_root: bool, quarantine=None
|
|
91
|
+
) -> CleanOutcome:
|
|
92
|
+
# Report-only items are never deleted, even if one slips into a clean set.
|
|
93
|
+
if item.report_only:
|
|
94
|
+
return CleanOutcome(
|
|
95
|
+
item=item, removed=False, freed=0, dry_run=dry_run,
|
|
96
|
+
error="report only (remove manually)",
|
|
97
|
+
)
|
|
98
|
+
if item.requires_root and not allow_root:
|
|
99
|
+
return CleanOutcome(
|
|
100
|
+
item=item,
|
|
101
|
+
removed=False,
|
|
102
|
+
error="requires root (re-run with sudo)",
|
|
103
|
+
dry_run=dry_run,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
if item.kind is ItemKind.PATH:
|
|
107
|
+
return self._clean_path(item, dry_run=dry_run, quarantine=quarantine)
|
|
108
|
+
return self._clean_command(item, dry_run=dry_run)
|
|
109
|
+
|
|
110
|
+
def _clean_path(
|
|
111
|
+
self, item: CleanableItem, *, dry_run: bool, quarantine=None
|
|
112
|
+
) -> CleanOutcome:
|
|
113
|
+
path = item.path or ""
|
|
114
|
+
if not safety.is_safe_to_delete(path):
|
|
115
|
+
return CleanOutcome(
|
|
116
|
+
item=item,
|
|
117
|
+
removed=False,
|
|
118
|
+
error="blocked by safety guard (protected path)",
|
|
119
|
+
dry_run=dry_run,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
p = Path(path)
|
|
123
|
+
freed = item.size or path_size(p)
|
|
124
|
+
if dry_run:
|
|
125
|
+
return CleanOutcome(item=item, removed=False, freed=freed, dry_run=True)
|
|
126
|
+
|
|
127
|
+
# Reversible mode: move to quarantine instead of deleting.
|
|
128
|
+
if quarantine is not None:
|
|
129
|
+
try:
|
|
130
|
+
quarantine.store(p)
|
|
131
|
+
except Exception as exc: # noqa: BLE001
|
|
132
|
+
return CleanOutcome(item=item, removed=False, error=f"quarantine: {exc}")
|
|
133
|
+
return CleanOutcome(item=item, removed=True, freed=freed)
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
safety.safe_rmtree(p)
|
|
137
|
+
except safety.UnsafePathError as exc:
|
|
138
|
+
return CleanOutcome(item=item, removed=False, error=str(exc))
|
|
139
|
+
except OSError as exc:
|
|
140
|
+
return CleanOutcome(item=item, removed=False, error=str(exc))
|
|
141
|
+
return CleanOutcome(item=item, removed=True, freed=freed)
|
|
142
|
+
|
|
143
|
+
def _clean_command(self, item: CleanableItem, *, dry_run: bool) -> CleanOutcome:
|
|
144
|
+
if dry_run:
|
|
145
|
+
return CleanOutcome(
|
|
146
|
+
item=item, removed=False, freed=item.size, dry_run=True
|
|
147
|
+
)
|
|
148
|
+
code, _out, err = run_command(list(item.command or []))
|
|
149
|
+
if code != 0:
|
|
150
|
+
return CleanOutcome(
|
|
151
|
+
item=item,
|
|
152
|
+
removed=False,
|
|
153
|
+
error=(err.strip() or f"exit code {code}"),
|
|
154
|
+
)
|
|
155
|
+
return CleanOutcome(item=item, removed=True, freed=item.size)
|