bekas 0.1.0__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.
- bekas/__init__.py +11 -0
- bekas/clean.py +191 -0
- bekas/cli.py +450 -0
- bekas/config.py +201 -0
- bekas/database.py +231 -0
- bekas/formatters.py +137 -0
- bekas/models.py +242 -0
- bekas/plugin.py +152 -0
- bekas/plugins/docker_containers.py +110 -0
- bekas/plugins/docker_images.py +277 -0
- bekas/plugins/dotfiles_backups.py +132 -0
- bekas/plugins/downloads.py +117 -0
- bekas/plugins/git_branches.py +192 -0
- bekas/plugins/node_modules.py +259 -0
- bekas/plugins/python_cache.py +147 -0
- bekas/plugins/python_venvs.py +203 -0
- bekas/plugins/rust_target.py +172 -0
- bekas/plugins/screenshots.py +136 -0
- bekas/plugins/system_tmp.py +99 -0
- bekas/quarantine.py +126 -0
- bekas/runner.py +117 -0
- bekas/safety.py +191 -0
- bekas/signing.py +66 -0
- bekas/tui.py +119 -0
- bekas-0.1.0.dist-info/METADATA +303 -0
- bekas-0.1.0.dist-info/RECORD +29 -0
- bekas-0.1.0.dist-info/WHEEL +4 -0
- bekas-0.1.0.dist-info/entry_points.txt +15 -0
- bekas-0.1.0.dist-info/licenses/LICENSE +21 -0
bekas/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""bekas — One audit. Every kind of forgotten thing. Nothing deleted you cared about.
|
|
2
|
+
|
|
3
|
+
bekas is a CLI utility that audits your local machine for forgotten artifacts
|
|
4
|
+
(Docker images, Python virtual environments, node_modules, old downloads, etc.)
|
|
5
|
+
and helps you safely reclaim disk space.
|
|
6
|
+
|
|
7
|
+
Attributes:
|
|
8
|
+
__version__: Package version string.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
bekas/clean.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Clean runner — applies a plan, optionally with dry-run."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from bekas.config import profile_for, quarantine_dir
|
|
10
|
+
from bekas.database import log_run
|
|
11
|
+
from bekas.models import AuditReport, Candidate, Context, Plan, RemovalResult, RunResult
|
|
12
|
+
from bekas.plugin import Plugin
|
|
13
|
+
from bekas.quarantine import move_to_quarantine, purge_old_quarantine
|
|
14
|
+
from bekas.safety import is_excluded
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _find_plugin(plugins: list[Plugin], name: str) -> Plugin | None:
|
|
18
|
+
"""Find a plugin by its exact name.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
plugins: List of loaded plugins.
|
|
22
|
+
name: Plugin name to match against ``Plugin.name``.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
The matching plugin, or None if not found.
|
|
26
|
+
"""
|
|
27
|
+
for p in plugins:
|
|
28
|
+
if p.name == name:
|
|
29
|
+
return p
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _group_by_category(candidates: list[Candidate]) -> dict[str, list[Candidate]]:
|
|
34
|
+
"""Group candidates by their top-level category prefix.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
candidates: Candidates to group.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
Mapping from category prefix (before the first '.') to candidates.
|
|
41
|
+
"""
|
|
42
|
+
groups: dict[str, list[Candidate]] = {}
|
|
43
|
+
for c in candidates:
|
|
44
|
+
cat = c.category.split(".")[0]
|
|
45
|
+
groups.setdefault(cat, []).append(c)
|
|
46
|
+
return groups
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def apply_plan(
|
|
50
|
+
plan: Plan,
|
|
51
|
+
plugins: list[Plugin],
|
|
52
|
+
ctx: Context,
|
|
53
|
+
audit: AuditReport | None = None,
|
|
54
|
+
yes_all: bool = False,
|
|
55
|
+
quarantine_enabled: bool = False,
|
|
56
|
+
profile_name: str | None = None,
|
|
57
|
+
) -> RunResult:
|
|
58
|
+
"""Apply a cleanup plan and return the run result.
|
|
59
|
+
|
|
60
|
+
Iterates over plan candidates grouped by category, optionally
|
|
61
|
+
prompting for confirmation, then delegates removal to the
|
|
62
|
+
matching plugin or falls back to generic deletion.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
plan: The plan to apply.
|
|
66
|
+
plugins: Available plugins for category-specific removal.
|
|
67
|
+
ctx: Execution context (controls dry-run and verbosity).
|
|
68
|
+
audit: Optional originating audit report (reserved for future use).
|
|
69
|
+
yes_all: If True, skip interactive per-category confirmation.
|
|
70
|
+
quarantine_enabled: If True, quarantine instead of deleting when supported.
|
|
71
|
+
profile_name: Optional profile name to load settings from.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
RunResult summarizing the operation.
|
|
75
|
+
"""
|
|
76
|
+
_ = audit # reserved for future use
|
|
77
|
+
profile = profile_for(profile_name)
|
|
78
|
+
quarantine_enabled = quarantine_enabled or profile.get("quarantine_enabled", False)
|
|
79
|
+
retention = profile.get("quarantine_retention_days", 30)
|
|
80
|
+
|
|
81
|
+
# Purge old quarantine first
|
|
82
|
+
purge_old_quarantine(retention)
|
|
83
|
+
|
|
84
|
+
groups = _group_by_category(plan.candidates)
|
|
85
|
+
per_candidate: list[tuple[Candidate, RemovalResult]] = []
|
|
86
|
+
total_freed = 0
|
|
87
|
+
run_id = f"run_{uuid.uuid4().hex[:8]}"
|
|
88
|
+
|
|
89
|
+
for cat, items in groups.items():
|
|
90
|
+
size = sum(c.size_bytes for c in items)
|
|
91
|
+
if not yes_all and not ctx.dry_run:
|
|
92
|
+
# Interactive prompt per category
|
|
93
|
+
resp = input(f"About to delete {len(items)} {cat} items ({_human_size(size)}). Confirm? [y/N] ")
|
|
94
|
+
if resp.strip().lower() != "y":
|
|
95
|
+
continue
|
|
96
|
+
|
|
97
|
+
for c in items:
|
|
98
|
+
if is_excluded(c.path_or_handle):
|
|
99
|
+
continue
|
|
100
|
+
plugin = _find_plugin(plugins, c.category)
|
|
101
|
+
removal_result: RemovalResult
|
|
102
|
+
if plugin is None:
|
|
103
|
+
# Fall back to generic deletion if no plugin matched category exactly
|
|
104
|
+
removal_result = _generic_remove(c, ctx, quarantine_enabled, run_id)
|
|
105
|
+
if removal_result.success:
|
|
106
|
+
total_freed += removal_result.bytes_freed
|
|
107
|
+
else:
|
|
108
|
+
if ctx.dry_run:
|
|
109
|
+
removal_result = RemovalResult(success=True, bytes_freed=0, log="dry-run")
|
|
110
|
+
else:
|
|
111
|
+
if quarantine_enabled and plugin.supports_quarantine():
|
|
112
|
+
removal_result = plugin.quarantine(c, ctx, str(quarantine_dir()), run_id=run_id)
|
|
113
|
+
# Quarantine counts as reclamation regardless of undo_token presence
|
|
114
|
+
if removal_result.success:
|
|
115
|
+
total_freed += removal_result.bytes_freed
|
|
116
|
+
else:
|
|
117
|
+
removal_result = plugin.remove(c, ctx)
|
|
118
|
+
if removal_result.success:
|
|
119
|
+
total_freed += removal_result.bytes_freed
|
|
120
|
+
per_candidate.append((c, removal_result))
|
|
121
|
+
|
|
122
|
+
run_result = RunResult(
|
|
123
|
+
run_id=run_id,
|
|
124
|
+
timestamp=datetime.now(UTC),
|
|
125
|
+
audit_id=plan.audit_id,
|
|
126
|
+
per_candidate=per_candidate,
|
|
127
|
+
total_bytes_freed=total_freed,
|
|
128
|
+
)
|
|
129
|
+
if not ctx.dry_run:
|
|
130
|
+
log_run(run_result)
|
|
131
|
+
return run_result
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _generic_remove(candidate: Candidate, ctx: Context, quarantine_enabled: bool, run_id: str) -> RemovalResult:
|
|
135
|
+
"""Perform generic removal for a candidate without a matching plugin.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
candidate: Candidate to remove.
|
|
139
|
+
ctx: Execution context (dry_run is respected).
|
|
140
|
+
quarantine_enabled: If True, move to quarantine instead of deleting.
|
|
141
|
+
run_id: Run identifier for quarantine tracking.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
Result of the removal or quarantine operation.
|
|
145
|
+
"""
|
|
146
|
+
p = Path(candidate.path_or_handle)
|
|
147
|
+
if not p.exists():
|
|
148
|
+
return RemovalResult(success=False, bytes_freed=0, log="Path does not exist")
|
|
149
|
+
|
|
150
|
+
if ctx.dry_run:
|
|
151
|
+
return RemovalResult(success=True, bytes_freed=0, log="dry-run")
|
|
152
|
+
|
|
153
|
+
if quarantine_enabled:
|
|
154
|
+
try:
|
|
155
|
+
dest = move_to_quarantine(run_id, p, candidate.category, candidate.size_bytes, candidate.metadata)
|
|
156
|
+
return RemovalResult(
|
|
157
|
+
success=True,
|
|
158
|
+
bytes_freed=candidate.size_bytes,
|
|
159
|
+
undo_token=str(dest),
|
|
160
|
+
log="quarantined",
|
|
161
|
+
)
|
|
162
|
+
except Exception as exc:
|
|
163
|
+
return RemovalResult(success=False, bytes_freed=0, log=str(exc))
|
|
164
|
+
|
|
165
|
+
import shutil
|
|
166
|
+
|
|
167
|
+
try:
|
|
168
|
+
if p.is_dir():
|
|
169
|
+
shutil.rmtree(p)
|
|
170
|
+
else:
|
|
171
|
+
p.unlink()
|
|
172
|
+
return RemovalResult(success=True, bytes_freed=candidate.size_bytes, log="deleted")
|
|
173
|
+
except Exception as exc:
|
|
174
|
+
return RemovalResult(success=False, bytes_freed=0, log=str(exc))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _human_size(size_bytes: int) -> str:
|
|
178
|
+
"""Convert a byte size into a human-readable string.
|
|
179
|
+
|
|
180
|
+
Args:
|
|
181
|
+
size_bytes: Size in bytes.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
Human-readable size (e.g., "1.5 MB").
|
|
185
|
+
"""
|
|
186
|
+
size = float(size_bytes)
|
|
187
|
+
for unit in ["B", "KB", "MB", "GB", "TB"]:
|
|
188
|
+
if abs(size) < 1024.0:
|
|
189
|
+
return f"{size:.1f} {unit}"
|
|
190
|
+
size /= 1024.0
|
|
191
|
+
return f"{size:.1f} PB"
|
bekas/cli.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
"""CLI entry point for bekas."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
|
|
10
|
+
from bekas.clean import apply_plan
|
|
11
|
+
from bekas.config import (
|
|
12
|
+
config_path,
|
|
13
|
+
ensure_config,
|
|
14
|
+
is_plugin_enabled,
|
|
15
|
+
load_config,
|
|
16
|
+
profile_for,
|
|
17
|
+
)
|
|
18
|
+
from bekas.database import get_run, list_quarantine, list_runs
|
|
19
|
+
from bekas.formatters import format_human, format_json
|
|
20
|
+
from bekas.models import AuditReport, Confidence, Context, Plan
|
|
21
|
+
from bekas.plugin import Plugin, discover_plugins
|
|
22
|
+
from bekas.quarantine import purge_old_quarantine, restore_from_quarantine
|
|
23
|
+
from bekas.runner import run_audit
|
|
24
|
+
from bekas.signing import sign_plan, verify_plan
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _get_plugins() -> list[Plugin]:
|
|
28
|
+
"""Discover and return all installed plugins.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
List of plugin instances.
|
|
32
|
+
"""
|
|
33
|
+
return discover_plugins()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _audit_to_plan(report: AuditReport, safe_only: bool = False, include_review: bool = False) -> Plan:
|
|
37
|
+
"""Convert an AuditReport into a Plan based on confidence filters.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
report: Audit report to derive the plan from.
|
|
41
|
+
safe_only: If True, only include SAFE-tier candidates.
|
|
42
|
+
include_review: If True, explicitly include REVIEW-tier candidates
|
|
43
|
+
(ignored when safe_only is True).
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
Plan containing the filtered candidates.
|
|
47
|
+
"""
|
|
48
|
+
allowed = {Confidence.SAFE}
|
|
49
|
+
if not safe_only:
|
|
50
|
+
if include_review:
|
|
51
|
+
allowed.add(Confidence.REVIEW)
|
|
52
|
+
else:
|
|
53
|
+
allowed = {Confidence.SAFE, Confidence.REVIEW}
|
|
54
|
+
candidates = [c for pr in report.plugins for c in pr.candidates if c.confidence in allowed]
|
|
55
|
+
return Plan(audit_id=report.audit_id, candidates=candidates)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@click.group(invoke_without_command=True)
|
|
59
|
+
@click.option("--profile", default=None, help="Configuration profile to use.")
|
|
60
|
+
@click.option("--json", "json_output", is_flag=True, help="Output JSON.")
|
|
61
|
+
@click.option("--verbose", "-v", is_flag=True, help="Verbose output.")
|
|
62
|
+
@click.pass_context
|
|
63
|
+
def cli(ctx: click.Context, profile: str | None, json_output: bool, verbose: bool) -> None:
|
|
64
|
+
"""bekas — finds leftover stuff on your machine and helps reclaim disk space safely."""
|
|
65
|
+
ctx.ensure_object(dict)
|
|
66
|
+
ctx.obj["profile"] = profile
|
|
67
|
+
ctx.obj["json"] = json_output
|
|
68
|
+
ctx.obj["verbose"] = verbose
|
|
69
|
+
|
|
70
|
+
if ctx.invoked_subcommand is None:
|
|
71
|
+
# First-run welcome
|
|
72
|
+
click.echo("Welcome to bekas.")
|
|
73
|
+
click.echo("")
|
|
74
|
+
click.echo(
|
|
75
|
+
"bekas finds leftover stuff on your machine — Docker images you forgot, "
|
|
76
|
+
"Python venvs from old projects, old downloads, etc. — and helps you "
|
|
77
|
+
"reclaim disk space safely."
|
|
78
|
+
)
|
|
79
|
+
click.echo("")
|
|
80
|
+
if sys.stdin.isatty():
|
|
81
|
+
resp = click.prompt("You haven't run an audit yet. Try one now?", default="Y")
|
|
82
|
+
if resp.strip().lower() in ("y", "yes"):
|
|
83
|
+
ctx.invoke(audit_cmd)
|
|
84
|
+
else:
|
|
85
|
+
click.echo("\nNext steps:")
|
|
86
|
+
click.echo(" bekas audit Run an audit")
|
|
87
|
+
click.echo(" bekas plan See what would be removed")
|
|
88
|
+
click.echo(" bekas clean Auto-clean safe items")
|
|
89
|
+
else:
|
|
90
|
+
click.echo("Run 'bekas audit' to get started.")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@cli.command("audit")
|
|
94
|
+
@click.option("--plugin", "plugins_filter", default=None, help="Comma-separated plugin names.")
|
|
95
|
+
@click.option("--serial", is_flag=True, help="Run plugins serially.")
|
|
96
|
+
@click.pass_context
|
|
97
|
+
def audit_cmd(ctx: click.Context, plugins_filter: str | None, serial: bool) -> None:
|
|
98
|
+
"""Run a read-only audit."""
|
|
99
|
+
profile_name = ctx.obj.get("profile")
|
|
100
|
+
all_plugins = _get_plugins()
|
|
101
|
+
|
|
102
|
+
if plugins_filter:
|
|
103
|
+
names = {n.strip() for n in plugins_filter.split(",")}
|
|
104
|
+
all_plugins = [p for p in all_plugins if p.name in names]
|
|
105
|
+
|
|
106
|
+
click.echo("Running audit (this may take 30–90 seconds)...")
|
|
107
|
+
report = run_audit(all_plugins, profile_name=profile_name, serial=serial)
|
|
108
|
+
|
|
109
|
+
if ctx.obj.get("json"):
|
|
110
|
+
click.echo(format_json(report))
|
|
111
|
+
else:
|
|
112
|
+
click.echo(format_human(report))
|
|
113
|
+
|
|
114
|
+
# Save report in context for chaining if needed
|
|
115
|
+
ctx.obj["last_audit"] = report
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@cli.command("plan")
|
|
119
|
+
@click.option("--safe-only", is_flag=True, help="Only include safe-tier items.")
|
|
120
|
+
@click.option("--include-review", is_flag=True, help="Include review-tier items.")
|
|
121
|
+
@click.option("--json", "json_output", is_flag=True, help="Output JSON.")
|
|
122
|
+
@click.option("--save", type=click.Path(), default=None, help="Save signed plan to a file.")
|
|
123
|
+
@click.pass_context
|
|
124
|
+
def plan_cmd(ctx: click.Context, safe_only: bool, include_review: bool, json_output: bool, save: str | None) -> None:
|
|
125
|
+
"""Preview what clean would do."""
|
|
126
|
+
profile_name = ctx.obj.get("profile")
|
|
127
|
+
all_plugins = _get_plugins()
|
|
128
|
+
report = run_audit(all_plugins, profile_name=profile_name)
|
|
129
|
+
plan = _audit_to_plan(report, safe_only=safe_only, include_review=include_review)
|
|
130
|
+
|
|
131
|
+
if save:
|
|
132
|
+
plan_data = plan.model_dump(mode="json")
|
|
133
|
+
plan_data["_signature"] = sign_plan(plan_data)
|
|
134
|
+
with open(save, "w") as f:
|
|
135
|
+
json.dump(plan_data, f, indent=2)
|
|
136
|
+
click.echo(f"Signed plan saved to {save}")
|
|
137
|
+
return
|
|
138
|
+
|
|
139
|
+
use_json = json_output or ctx.obj.get("json")
|
|
140
|
+
if use_json:
|
|
141
|
+
click.echo(format_json(plan))
|
|
142
|
+
else:
|
|
143
|
+
click.echo(format_human(plan))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@cli.command("clean")
|
|
147
|
+
@click.option("--apply", is_flag=True, help="Actually delete (default is dry-run).")
|
|
148
|
+
@click.option("--safe-only", is_flag=True, help="Only clean safe-tier items.")
|
|
149
|
+
@click.option("--review", "include_review", is_flag=True, help="Include review-tier items interactively.")
|
|
150
|
+
@click.option("--yes-all", is_flag=True, help="Skip per-category prompts.")
|
|
151
|
+
@click.option("--non-interactive", is_flag=True, help="Non-interactive mode (requires --accept-categories).")
|
|
152
|
+
@click.option("--accept-categories", default=None, help="Comma-separated categories for non-interactive mode.")
|
|
153
|
+
@click.option("--plan-file", type=click.Path(exists=True), default=None, help="Apply a saved JSON plan file.")
|
|
154
|
+
@click.pass_context
|
|
155
|
+
def clean_cmd(
|
|
156
|
+
ctx: click.Context,
|
|
157
|
+
apply: bool,
|
|
158
|
+
safe_only: bool,
|
|
159
|
+
include_review: bool,
|
|
160
|
+
yes_all: bool,
|
|
161
|
+
non_interactive: bool,
|
|
162
|
+
accept_categories: str | None,
|
|
163
|
+
plan_file: str | None,
|
|
164
|
+
) -> None:
|
|
165
|
+
"""Remove approved candidates. Dry-run by default."""
|
|
166
|
+
profile_name = ctx.obj.get("profile")
|
|
167
|
+
profile = profile_for(profile_name)
|
|
168
|
+
|
|
169
|
+
if plan_file:
|
|
170
|
+
with open(plan_file) as f:
|
|
171
|
+
plan_data = json.load(f)
|
|
172
|
+
signature = plan_data.pop("_signature", None)
|
|
173
|
+
if signature and not verify_plan(plan_data, signature):
|
|
174
|
+
click.echo("Error: plan file signature is invalid or was tampered with.")
|
|
175
|
+
sys.exit(1)
|
|
176
|
+
plan = Plan(**plan_data)
|
|
177
|
+
report = None
|
|
178
|
+
else:
|
|
179
|
+
all_plugins = _get_plugins()
|
|
180
|
+
report = run_audit(all_plugins, profile_name=profile_name)
|
|
181
|
+
plan = _audit_to_plan(report, safe_only=safe_only, include_review=include_review)
|
|
182
|
+
|
|
183
|
+
if not plan.candidates:
|
|
184
|
+
click.echo("Nothing to clean.")
|
|
185
|
+
return
|
|
186
|
+
|
|
187
|
+
if not apply:
|
|
188
|
+
click.echo("Dry run mode (default).")
|
|
189
|
+
click.echo("Re-run with --apply to actually delete.")
|
|
190
|
+
click.echo("")
|
|
191
|
+
click.echo(format_human(plan))
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
if non_interactive and not accept_categories:
|
|
195
|
+
click.echo("Error: --non-interactive requires --accept-categories.")
|
|
196
|
+
sys.exit(1)
|
|
197
|
+
|
|
198
|
+
# If non-interactive, we still filter to accepted categories
|
|
199
|
+
if non_interactive and accept_categories:
|
|
200
|
+
accepted = {c.strip() for c in accept_categories.split(",")}
|
|
201
|
+
plan.candidates = [c for c in plan.candidates if c.category.split(".")[0] in accepted]
|
|
202
|
+
|
|
203
|
+
ctx_obj = Context(dry_run=False, config=profile, verbose=ctx.obj.get("verbose", False))
|
|
204
|
+
quarantine_enabled = profile.get("quarantine_enabled", True)
|
|
205
|
+
|
|
206
|
+
result = apply_plan(
|
|
207
|
+
plan,
|
|
208
|
+
all_plugins if not plan_file else _get_plugins(),
|
|
209
|
+
ctx_obj,
|
|
210
|
+
audit=report,
|
|
211
|
+
yes_all=yes_all or non_interactive,
|
|
212
|
+
quarantine_enabled=quarantine_enabled,
|
|
213
|
+
profile_name=profile_name,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
if ctx.obj.get("json"):
|
|
217
|
+
click.echo(format_json(result))
|
|
218
|
+
else:
|
|
219
|
+
click.echo(format_human(result))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@cli.command("inspect")
|
|
223
|
+
@click.argument("candidate_id")
|
|
224
|
+
@click.pass_context
|
|
225
|
+
def inspect_cmd(ctx: click.Context, candidate_id: str) -> None:
|
|
226
|
+
"""Show full reasoning for a single candidate."""
|
|
227
|
+
all_plugins = _get_plugins()
|
|
228
|
+
report = run_audit(all_plugins, profile_name=ctx.obj.get("profile"))
|
|
229
|
+
for pr in report.plugins:
|
|
230
|
+
for c in pr.candidates:
|
|
231
|
+
if c.id == candidate_id:
|
|
232
|
+
click.echo(f"Candidate: {c.id}")
|
|
233
|
+
click.echo(f"Category: {c.category}")
|
|
234
|
+
click.echo(f"Size: {_human_size(c.size_bytes)}")
|
|
235
|
+
click.echo(f"Confidence: {c.confidence.value}")
|
|
236
|
+
click.echo(f"Reason: {c.reason}")
|
|
237
|
+
click.echo(f"Path: {c.path_or_handle}")
|
|
238
|
+
if c.metadata:
|
|
239
|
+
click.echo("Metadata:")
|
|
240
|
+
for k, v in c.metadata.items():
|
|
241
|
+
click.echo(f" {k}: {v}")
|
|
242
|
+
return
|
|
243
|
+
click.echo(f"Candidate {candidate_id} not found in latest audit.")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@cli.command("history")
|
|
247
|
+
@click.argument("run_id", required=False)
|
|
248
|
+
@click.pass_context
|
|
249
|
+
def history_cmd(ctx: click.Context, run_id: str | None) -> None:
|
|
250
|
+
"""List past actions or show details of a specific run."""
|
|
251
|
+
if run_id:
|
|
252
|
+
run = get_run(run_id)
|
|
253
|
+
if not run:
|
|
254
|
+
click.echo(f"Run {run_id} not found.")
|
|
255
|
+
return
|
|
256
|
+
click.echo(f"Run {run['run_id']} at {run['timestamp']}")
|
|
257
|
+
click.echo(f"Audit ID: {run['audit_id']}")
|
|
258
|
+
click.echo(f"Total freed: {_human_size(run['total_bytes_freed'])}")
|
|
259
|
+
# Could pretty-print plan_json / results_json here
|
|
260
|
+
else:
|
|
261
|
+
runs = list_runs()
|
|
262
|
+
if not runs:
|
|
263
|
+
click.echo("No history yet.")
|
|
264
|
+
return
|
|
265
|
+
click.echo(f"{'Run ID':12s} {'Time':20s} {'Audit ID':12s} {'Freed':>12s}")
|
|
266
|
+
for r in runs:
|
|
267
|
+
click.echo(
|
|
268
|
+
f"{r['run_id']:12s} {r['timestamp']:20s} {r['audit_id']:12s} {_human_size(r['total_bytes_freed']):>12s}"
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@cli.command("undo")
|
|
273
|
+
@click.argument("run_id", required=False)
|
|
274
|
+
@click.pass_context
|
|
275
|
+
def undo_cmd(ctx: click.Context, run_id: str | None) -> None:
|
|
276
|
+
"""Undo the last apply or a specific run."""
|
|
277
|
+
from bekas.database import get_run
|
|
278
|
+
from bekas.quarantine import restore_from_quarantine
|
|
279
|
+
|
|
280
|
+
if not run_id:
|
|
281
|
+
runs = list_runs()
|
|
282
|
+
if not runs:
|
|
283
|
+
click.echo("No runs to undo.")
|
|
284
|
+
return
|
|
285
|
+
run_id = runs[0]["run_id"]
|
|
286
|
+
|
|
287
|
+
run = get_run(run_id)
|
|
288
|
+
if not run:
|
|
289
|
+
click.echo(f"Run {run_id} not found.")
|
|
290
|
+
return
|
|
291
|
+
|
|
292
|
+
click.echo(f"Undo run {run_id}...")
|
|
293
|
+
|
|
294
|
+
# Parse per-candidate results and restore anything that was quarantined
|
|
295
|
+
import json
|
|
296
|
+
|
|
297
|
+
restored = 0
|
|
298
|
+
failed = 0
|
|
299
|
+
try:
|
|
300
|
+
results = json.loads(run["results_json"])
|
|
301
|
+
except Exception:
|
|
302
|
+
click.echo("Could not parse run results.")
|
|
303
|
+
return
|
|
304
|
+
|
|
305
|
+
for entry in results:
|
|
306
|
+
undo_token = entry.get("undo_token")
|
|
307
|
+
if not undo_token:
|
|
308
|
+
continue
|
|
309
|
+
try:
|
|
310
|
+
restore_from_quarantine(undo_token)
|
|
311
|
+
restored += 1
|
|
312
|
+
except Exception as exc:
|
|
313
|
+
click.echo(f" Failed to restore {undo_token}: {exc}")
|
|
314
|
+
failed += 1
|
|
315
|
+
|
|
316
|
+
if restored == 0 and failed == 0:
|
|
317
|
+
click.echo("No quarantined items to restore for this run.")
|
|
318
|
+
else:
|
|
319
|
+
click.echo(f"Restored {restored} item(s). Failed: {failed}.")
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@cli.group("quarantine")
|
|
323
|
+
def quarantine_group() -> None:
|
|
324
|
+
"""Manage quarantined items."""
|
|
325
|
+
pass
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
@quarantine_group.command("list")
|
|
329
|
+
def quarantine_list() -> None:
|
|
330
|
+
"""List quarantined items."""
|
|
331
|
+
items = list_quarantine()
|
|
332
|
+
if not items:
|
|
333
|
+
click.echo("Quarantine is empty.")
|
|
334
|
+
return
|
|
335
|
+
click.echo(f"{'ID':14s} {'Category':20s} {'Original':40s} {'Size':>12s}")
|
|
336
|
+
for item in items:
|
|
337
|
+
click.echo(
|
|
338
|
+
f"{item['quarantine_id']:14s} {item['category']:20s} "
|
|
339
|
+
f"{item['original_path']:40s} {_human_size(item['size_bytes']):>12s}"
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@quarantine_group.command("restore")
|
|
344
|
+
@click.argument("quarantine_id")
|
|
345
|
+
def quarantine_restore(quarantine_id: str) -> None:
|
|
346
|
+
"""Restore a quarantined item to its original location."""
|
|
347
|
+
try:
|
|
348
|
+
dest = restore_from_quarantine(quarantine_id)
|
|
349
|
+
click.echo(f"Restored to {dest}")
|
|
350
|
+
except Exception as exc:
|
|
351
|
+
click.echo(f"Restore failed: {exc}")
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
@quarantine_group.command("purge")
|
|
355
|
+
def quarantine_purge() -> None:
|
|
356
|
+
"""Empty quarantine immediately."""
|
|
357
|
+
removed, freed = purge_old_quarantine(retention_days=0)
|
|
358
|
+
click.echo(f"Purged {removed} items, freeing {_human_size(freed)}.")
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
@cli.group("plugins")
|
|
362
|
+
def plugins_group() -> None:
|
|
363
|
+
"""Manage plugins."""
|
|
364
|
+
pass
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
@plugins_group.command("list")
|
|
368
|
+
@click.pass_context
|
|
369
|
+
def plugins_list(ctx: click.Context) -> None:
|
|
370
|
+
"""List installed plugins and their availability."""
|
|
371
|
+
profile_name = ctx.obj.get("profile")
|
|
372
|
+
profile = profile_for(profile_name)
|
|
373
|
+
patterns = profile.get("enabled_plugins", ["*"])
|
|
374
|
+
all_plugins = _get_plugins()
|
|
375
|
+
click.echo(f"{'Plugin':30s} {'Available':10s} {'Enabled':10s}")
|
|
376
|
+
for p in all_plugins:
|
|
377
|
+
avail = "yes" if p.is_available(Context(dry_run=True, config=profile)) else "no"
|
|
378
|
+
enabled = "yes" if is_plugin_enabled(patterns, p.name) else "no"
|
|
379
|
+
click.echo(f"{p.name:30s} {avail:10s} {enabled:10s}")
|
|
380
|
+
click.echo(f" {p.description}")
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
@plugins_group.command("enable")
|
|
384
|
+
@click.argument("plugin_name")
|
|
385
|
+
def plugins_enable(plugin_name: str) -> None:
|
|
386
|
+
"""Enable a plugin in config (not implemented in v0.1)."""
|
|
387
|
+
click.echo(f"Enable {plugin_name}: edit {config_path()} to add to enabled_plugins.")
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
@plugins_group.command("disable")
|
|
391
|
+
@click.argument("plugin_name")
|
|
392
|
+
def plugins_disable(plugin_name: str) -> None:
|
|
393
|
+
"""Disable a plugin in config (not implemented in v0.1)."""
|
|
394
|
+
click.echo(f"Disable {plugin_name}: edit {config_path()} to remove from enabled_plugins.")
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
@cli.command("config")
|
|
398
|
+
@click.pass_context
|
|
399
|
+
def config_cmd(ctx: click.Context) -> None:
|
|
400
|
+
"""Print current effective configuration."""
|
|
401
|
+
cfg = load_config()
|
|
402
|
+
profile = profile_for(ctx.obj.get("profile"))
|
|
403
|
+
click.echo(f"Config file: {config_path()}")
|
|
404
|
+
click.echo("")
|
|
405
|
+
click.echo("Active profile:")
|
|
406
|
+
for k, v in profile.items():
|
|
407
|
+
click.echo(f" {k}: {v}")
|
|
408
|
+
click.echo("")
|
|
409
|
+
click.echo("Full config:")
|
|
410
|
+
click.echo(json.dumps(cfg, indent=2))
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
@cli.command("tui")
|
|
414
|
+
def tui_cmd() -> None:
|
|
415
|
+
"""Launch interactive TUI (Textual)."""
|
|
416
|
+
try:
|
|
417
|
+
from bekas.tui import TuiApp
|
|
418
|
+
|
|
419
|
+
app = TuiApp()
|
|
420
|
+
app.run()
|
|
421
|
+
except Exception as exc:
|
|
422
|
+
click.echo(f"TUI not available: {exc}")
|
|
423
|
+
sys.exit(1)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _human_size(size_bytes: int) -> str:
|
|
427
|
+
"""Convert a byte size into a human-readable string.
|
|
428
|
+
|
|
429
|
+
Args:
|
|
430
|
+
size_bytes: Size in bytes.
|
|
431
|
+
|
|
432
|
+
Returns:
|
|
433
|
+
Human-readable size (e.g., "1.5 MB").
|
|
434
|
+
"""
|
|
435
|
+
size = float(size_bytes)
|
|
436
|
+
for unit in ["B", "KB", "MB", "GB", "TB"]:
|
|
437
|
+
if abs(size) < 1024.0:
|
|
438
|
+
return f"{size:.1f} {unit}"
|
|
439
|
+
size /= 1024.0
|
|
440
|
+
return f"{size:.1f} PB"
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def main() -> None:
|
|
444
|
+
"""Application entry point. Ensures config exists and starts the CLI."""
|
|
445
|
+
ensure_config()
|
|
446
|
+
cli()
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
if __name__ == "__main__":
|
|
450
|
+
main()
|