devstuff 2.24.0__py3-none-any.whl → 2.26.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.
- dev_setup/catalog.py +8 -0
- dev_setup/commands/install_cmd.py +20 -9
- dev_setup/commands/list_cmd.py +11 -7
- dev_setup/configure/__init__.py +6 -0
- dev_setup/configure/btop/__init__.py +2 -0
- dev_setup/configure/btop/capability.py +107 -0
- dev_setup/configure/btop/detect.py +370 -0
- dev_setup/configure/btop/model.py +306 -0
- dev_setup/configure/btop/render.py +242 -0
- dev_setup/configure/btop/validate.py +429 -0
- dev_setup/configure/btop/wizard.py +513 -0
- dev_setup/generic.py +3 -0
- dev_setup/managers.py +281 -0
- dev_setup/tools.yaml +17 -0
- {devstuff-2.24.0.dist-info → devstuff-2.26.0.dist-info}/METADATA +39 -1
- {devstuff-2.24.0.dist-info → devstuff-2.26.0.dist-info}/RECORD +18 -10
- {devstuff-2.24.0.dist-info → devstuff-2.26.0.dist-info}/WHEEL +0 -0
- {devstuff-2.24.0.dist-info → devstuff-2.26.0.dist-info}/entry_points.txt +0 -0
dev_setup/catalog.py
CHANGED
|
@@ -40,6 +40,7 @@ SUPPORTED_FIELDS = {
|
|
|
40
40
|
"sha256",
|
|
41
41
|
"install_script",
|
|
42
42
|
"remove_script",
|
|
43
|
+
"managed_by",
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
|
|
@@ -122,6 +123,13 @@ def validate_catalog(raw: Any, *, source: Path | str = "<catalog>") -> dict[str,
|
|
|
122
123
|
elif not isinstance(requires, list) or not all(isinstance(v, str) for v in requires):
|
|
123
124
|
raise CatalogError(f"{source}: tool {key!r} requires must be a list of strings")
|
|
124
125
|
|
|
126
|
+
managed_by = item.get("managed_by")
|
|
127
|
+
if managed_by is not None:
|
|
128
|
+
if not isinstance(managed_by, str) or not VALID_KEY.match(managed_by):
|
|
129
|
+
raise CatalogError(f"{source}: tool {key!r} managed_by must be a tool key")
|
|
130
|
+
if managed_by == key:
|
|
131
|
+
raise CatalogError(f"{source}: tool {key!r} cannot be managed_by itself")
|
|
132
|
+
|
|
125
133
|
validated[key] = item
|
|
126
134
|
|
|
127
135
|
return validated
|
|
@@ -7,7 +7,7 @@ import click
|
|
|
7
7
|
import questionary
|
|
8
8
|
from rich.markup import escape
|
|
9
9
|
|
|
10
|
-
from dev_setup import registry, ui
|
|
10
|
+
from dev_setup import managers, registry, ui
|
|
11
11
|
from dev_setup.base import Tool
|
|
12
12
|
from dev_setup.commands._plan import plan_for, plan_summary
|
|
13
13
|
|
|
@@ -163,10 +163,16 @@ def _install_interactive(*, yes: bool) -> None:
|
|
|
163
163
|
ui.print_banner()
|
|
164
164
|
tools = registry.all_tools()
|
|
165
165
|
|
|
166
|
-
# Probe installed status concurrently — each check shells out.
|
|
166
|
+
# Probe installed status concurrently — each check shells out. The manager
|
|
167
|
+
# note rides along so its probes share this pass rather than a second one.
|
|
168
|
+
def _probe_one(t: Tool) -> tuple[bool, managers.ManagerNote | None]:
|
|
169
|
+
inst = t.is_installed()
|
|
170
|
+
return inst, managers.note_for(t, inst)
|
|
171
|
+
|
|
167
172
|
with ui.spinner("Checking installed packages..."), ThreadPoolExecutor(max_workers=8) as pool:
|
|
168
|
-
|
|
169
|
-
|
|
173
|
+
probed = dict(zip((t.key for t in tools), pool.map(_probe_one, tools), strict=True))
|
|
174
|
+
installed = {k: v[0] for k, v in probed.items()}
|
|
175
|
+
notes = {k: v[1] for k, v in probed.items()}
|
|
170
176
|
|
|
171
177
|
by_cat: dict[str, list[Tool]] = {}
|
|
172
178
|
for t in tools:
|
|
@@ -186,11 +192,16 @@ def _install_interactive(*, yes: bool) -> None:
|
|
|
186
192
|
for t in entries:
|
|
187
193
|
is_inst = installed[t.key]
|
|
188
194
|
missing = [] if is_inst else registry.missing_requires(t)
|
|
195
|
+
note = notes[t.key]
|
|
196
|
+
suffix, disabled_override = (
|
|
197
|
+
managers.picker_hint(note, t) if note is not None else ("", None)
|
|
198
|
+
)
|
|
189
199
|
desc = t.description
|
|
190
|
-
|
|
191
|
-
|
|
200
|
+
room = max(10, desc_width - len(suffix))
|
|
201
|
+
if len(desc) > room:
|
|
202
|
+
desc = desc[: room - 1] + "…"
|
|
192
203
|
if is_inst:
|
|
193
|
-
disabled = "installed"
|
|
204
|
+
disabled = disabled_override or "installed"
|
|
194
205
|
elif missing:
|
|
195
206
|
disabled = f"requires {', '.join(missing)}"
|
|
196
207
|
else:
|
|
@@ -201,10 +212,10 @@ def _install_interactive(*, yes: bool) -> None:
|
|
|
201
212
|
title: str | list[tuple[str, str]] = (
|
|
202
213
|
[
|
|
203
214
|
("class:check", "● " if is_inst else " "),
|
|
204
|
-
("class:text", f"{t.key:<{key_width}}{desc}"),
|
|
215
|
+
("class:text", f"{t.key:<{key_width}}{desc}{suffix}"),
|
|
205
216
|
]
|
|
206
217
|
if disabled
|
|
207
|
-
else f" {t.key:<{key_width}}{desc}"
|
|
218
|
+
else f" {t.key:<{key_width}}{desc}{suffix}"
|
|
208
219
|
)
|
|
209
220
|
choices.append(questionary.Choice(
|
|
210
221
|
title=title,
|
dev_setup/commands/list_cmd.py
CHANGED
|
@@ -4,17 +4,17 @@ from concurrent.futures import ThreadPoolExecutor
|
|
|
4
4
|
|
|
5
5
|
import click
|
|
6
6
|
|
|
7
|
-
from dev_setup import registry, ui
|
|
7
|
+
from dev_setup import managers, registry, ui
|
|
8
8
|
from dev_setup.base import Tool
|
|
9
9
|
|
|
10
10
|
_MAX_WORKERS = 8
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
def _probe(tool: Tool) -> tuple[Tool, bool, str]:
|
|
13
|
+
def _probe(tool: Tool) -> tuple[Tool, bool, str, managers.ManagerNote | None]:
|
|
14
14
|
"""Gather subprocess-heavy status for one tool (runs in a worker thread)."""
|
|
15
15
|
is_inst = tool.is_installed()
|
|
16
16
|
version = tool.get_version() if is_inst else ""
|
|
17
|
-
return tool, is_inst, version
|
|
17
|
+
return tool, is_inst, version, managers.note_for(tool, is_inst)
|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
@click.command("list")
|
|
@@ -35,12 +35,12 @@ def list_cmd(show_filter: str, category: str) -> None:
|
|
|
35
35
|
probed = list(pool.map(_probe, tools))
|
|
36
36
|
|
|
37
37
|
by_cat: dict = {}
|
|
38
|
-
for tool, is_inst, version in probed:
|
|
38
|
+
for tool, is_inst, version, note in probed:
|
|
39
39
|
if show_filter == "installed" and not is_inst:
|
|
40
40
|
continue
|
|
41
41
|
if show_filter == "available" and is_inst:
|
|
42
42
|
continue
|
|
43
|
-
by_cat.setdefault(tool.category, []).append((tool, is_inst, version))
|
|
43
|
+
by_cat.setdefault(tool.category, []).append((tool, is_inst, version, note))
|
|
44
44
|
|
|
45
45
|
if not by_cat:
|
|
46
46
|
ui.warn("No packages match the given filters.")
|
|
@@ -52,7 +52,7 @@ def list_cmd(show_filter: str, category: str) -> None:
|
|
|
52
52
|
if not entries:
|
|
53
53
|
continue
|
|
54
54
|
|
|
55
|
-
n_inst = sum(1 for _, is_inst, _ in entries if is_inst)
|
|
55
|
+
n_inst = sum(1 for _, is_inst, _, _ in entries if is_inst)
|
|
56
56
|
tbl = ui.table(
|
|
57
57
|
title=f"[bold]{cat}[/] [{ui.GRAY}]{n_inst}/{len(entries)} installed[/]"
|
|
58
58
|
)
|
|
@@ -62,7 +62,7 @@ def list_cmd(show_filter: str, category: str) -> None:
|
|
|
62
62
|
tbl.add_column("Type", style=ui.CYAN, no_wrap=True)
|
|
63
63
|
tbl.add_column("Version", style=ui.GRAY, no_wrap=True, max_width=28, overflow="ellipsis")
|
|
64
64
|
|
|
65
|
-
for tool, is_inst, version in entries:
|
|
65
|
+
for tool, is_inst, version, note in entries:
|
|
66
66
|
icon = f"[{ui.GREEN}]●[/]" if is_inst else f"[{ui.GRAY}]○[/]"
|
|
67
67
|
desc = tool.description
|
|
68
68
|
if tool.help_cmd:
|
|
@@ -71,6 +71,10 @@ def list_cmd(show_filter: str, category: str) -> None:
|
|
|
71
71
|
missing = registry.missing_requires(tool)
|
|
72
72
|
if missing:
|
|
73
73
|
desc += f"\n[{ui.AMBER}] ⚠ requires: {', '.join(missing)}[/]"
|
|
74
|
+
if note is not None:
|
|
75
|
+
line = managers.list_line(note, tool)
|
|
76
|
+
if line:
|
|
77
|
+
desc += f"\n{line}"
|
|
74
78
|
tbl.add_row(icon, tool.key, desc, tool.install_type, version)
|
|
75
79
|
|
|
76
80
|
ui.console.print(tbl)
|
dev_setup/configure/__init__.py
CHANGED
|
@@ -57,6 +57,12 @@ CONFIGURATORS: dict[str, Configurator] = {
|
|
|
57
57
|
description="Theme, decorations, paging and the man-page/cat shell integration",
|
|
58
58
|
module="dev_setup.configure.bat.wizard",
|
|
59
59
|
),
|
|
60
|
+
"btop": Configurator(
|
|
61
|
+
key="btop",
|
|
62
|
+
label="btop",
|
|
63
|
+
description="Theme, boxes, graph glyphs, update rate and the process list in btop.conf",
|
|
64
|
+
module="dev_setup.configure.btop.wizard",
|
|
65
|
+
),
|
|
60
66
|
"commitizen": Configurator(
|
|
61
67
|
key="commitizen",
|
|
62
68
|
label="Commitizen",
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""The `cap_perfmon` offer — CPU package watts and Intel GPU stats need it.
|
|
2
|
+
|
|
3
|
+
Upstream's `make setcap` is `setcap cap_perfmon=+ep` on the binary, documented as
|
|
4
|
+
required for those readings and preferred over setuid. The Debian package ships
|
|
5
|
+
no postinst and no capability, and an apt upgrade replaces the binary — which
|
|
6
|
+
drops the capability — so the wizard offers it after a save and says that.
|
|
7
|
+
|
|
8
|
+
Three things bound what this module does:
|
|
9
|
+
|
|
10
|
+
- **It verifies the capability is set, nothing more.** `getcap` after `setcap`
|
|
11
|
+
is the whole check — containers and VMs often hide the power counters, so
|
|
12
|
+
whether watts then appear is not knowable here.
|
|
13
|
+
- **It refuses some binaries.** `setcap` on a binary others can replace — not
|
|
14
|
+
root-owned, or group/other-writable — is a privilege hole, not a fix; the
|
|
15
|
+
refusal names why and prints the command for the user to judge.
|
|
16
|
+
- **Sudo failures are failures**, surfaced through `generic._run` like every
|
|
17
|
+
other state-changing command; verification after the fact is a re-read, not a
|
|
18
|
+
trust of the exit code.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from dev_setup.generic import _run
|
|
30
|
+
|
|
31
|
+
CAP = "cap_perfmon"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def binary() -> str | None:
|
|
35
|
+
"""The resolved realpath of the btop on PATH."""
|
|
36
|
+
path = shutil.which("btop")
|
|
37
|
+
return str(Path(path).resolve()) if path else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def tool(name: str) -> str | None:
|
|
41
|
+
"""setcap/getcap live in sbin, which a non-root PATH may not have."""
|
|
42
|
+
found = shutil.which(name)
|
|
43
|
+
if found:
|
|
44
|
+
return found
|
|
45
|
+
for directory in ("/usr/sbin", "/sbin"):
|
|
46
|
+
candidate = Path(directory) / name
|
|
47
|
+
if candidate.is_file() and os.access(candidate, os.X_OK):
|
|
48
|
+
return str(candidate)
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def has_perfmon(path: str) -> bool | None:
|
|
53
|
+
"""Whether `cap_perfmon` is set on the binary. `None` = cannot tell."""
|
|
54
|
+
getcap = tool("getcap")
|
|
55
|
+
if getcap is None:
|
|
56
|
+
return None
|
|
57
|
+
try:
|
|
58
|
+
result = subprocess.run(
|
|
59
|
+
[getcap, path], capture_output=True, text=True,
|
|
60
|
+
encoding="utf-8", errors="replace", timeout=10, check=False,
|
|
61
|
+
)
|
|
62
|
+
except (OSError, subprocess.SubprocessError):
|
|
63
|
+
return None
|
|
64
|
+
if result.returncode != 0:
|
|
65
|
+
return None
|
|
66
|
+
# getcap prints e.g. `/usr/bin/btop cap_perfmon=ep` — or a combined set like
|
|
67
|
+
# `cap_perfmon,cap_net_raw=ep`, or `= cap_perfmon+ep` on older versions; and
|
|
68
|
+
# nothing when unset. Match the name, not `cap_perfmon=` glued to the flags.
|
|
69
|
+
for line in result.stdout.splitlines():
|
|
70
|
+
if line.startswith(path):
|
|
71
|
+
return bool(re.search(rf"\b{CAP}\b", line[len(path):]))
|
|
72
|
+
return False
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def refusal(path: str) -> str | None:
|
|
76
|
+
"""Why a grant must not run on this binary. `None` = no objection."""
|
|
77
|
+
if tool("setcap") is None:
|
|
78
|
+
return "setcap was not found (it lives in the libcap2-bin package, in sbin)"
|
|
79
|
+
try:
|
|
80
|
+
st = os.stat(path)
|
|
81
|
+
except OSError:
|
|
82
|
+
return f"cannot stat {path}"
|
|
83
|
+
if st.st_uid != 0:
|
|
84
|
+
return (
|
|
85
|
+
"the binary is not owned by root — a capability on a binary you can "
|
|
86
|
+
"replace is a privilege hole"
|
|
87
|
+
)
|
|
88
|
+
if st.st_mode & 0o022:
|
|
89
|
+
return "the binary is writable by group or others — a capability on it is a privilege hole"
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def grant(path: str) -> None:
|
|
94
|
+
"""`sudo setcap cap_perfmon=+ep <path>`, then verify with getcap."""
|
|
95
|
+
_run(["sudo", tool("setcap") or "setcap", f"{CAP}=+ep", path])
|
|
96
|
+
if has_perfmon(path) is not True:
|
|
97
|
+
raise RuntimeError("setcap ran, but getcap does not show cap_perfmon — not verified")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def revoke(path: str) -> None:
|
|
101
|
+
"""`sudo setcap -r <path>`, then verify the capability is gone."""
|
|
102
|
+
_run(["sudo", tool("setcap") or "setcap", "-r", path])
|
|
103
|
+
if has_perfmon(path) is not False:
|
|
104
|
+
raise RuntimeError("setcap -r ran, but getcap still shows cap_perfmon — not verified")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
__all__ = ["binary", "grant", "has_perfmon", "refusal", "revoke", "tool"]
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
"""Ask the installed `btop` about itself, and read any existing config.
|
|
2
|
+
|
|
3
|
+
Three things are asked of the machine rather than assumed:
|
|
4
|
+
|
|
5
|
+
- **Which keys this build knows.** `--default-config` (1.4.x) prints them; on
|
|
6
|
+
1.3.0 — no such flag — a first-run probe in a throwaway HOME produces the same
|
|
7
|
+
file. The set varies by version *and* build flags (the apt 1.4.6 build has GPU
|
|
8
|
+
keys the upstream static 1.4.7 does not), so a table would be wrong.
|
|
9
|
+
- **Which themes exist.** `Default`/`TTY` are builtin; `*.theme` stems are
|
|
10
|
+
scanned from the directories btop reads. A *path* is never a theme — measured:
|
|
11
|
+
a full path outside the scanned dirs silently renders Default.
|
|
12
|
+
- **Whether a btop is running.** It reads the config only at start, and one with
|
|
13
|
+
an in-app change overwrites external edits on exit.
|
|
14
|
+
|
|
15
|
+
`found.keys` is `None` when btop could not be asked — the difference between
|
|
16
|
+
"not installed" and "no keys" decides whether the wizard offers every setting or
|
|
17
|
+
only the ones this binary accepts.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import shutil
|
|
25
|
+
import subprocess
|
|
26
|
+
import tempfile
|
|
27
|
+
from collections.abc import Callable
|
|
28
|
+
from dataclasses import dataclass, field
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from dev_setup.configure.btop import render
|
|
32
|
+
from dev_setup.configure.btop.model import (
|
|
33
|
+
BOXES,
|
|
34
|
+
CONFIG_FILE,
|
|
35
|
+
GPU_BOXES,
|
|
36
|
+
PRESETS,
|
|
37
|
+
SETTINGS,
|
|
38
|
+
BtopConfig,
|
|
39
|
+
Setting,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
TIMEOUT = 15
|
|
43
|
+
_VERSION = re.compile(r"btop version:\s*([0-9][\d.]*)")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Btop:
|
|
48
|
+
installed: bool = False
|
|
49
|
+
binary: str = "" # resolved realpath of the btop on PATH
|
|
50
|
+
version: str = ""
|
|
51
|
+
path: Path = field(default_factory=lambda: config_dir() / CONFIG_FILE)
|
|
52
|
+
|
|
53
|
+
# From this binary's own defaults text; `keys` None means "could not ask".
|
|
54
|
+
header: str = ""
|
|
55
|
+
keys: frozenset[str] | None = None
|
|
56
|
+
defaults: dict[str, str] = field(default_factory=dict) # raw value text
|
|
57
|
+
themes: tuple[str, ...] = ()
|
|
58
|
+
|
|
59
|
+
existing_text: str = ""
|
|
60
|
+
existing: dict[str, object] = field(default_factory=dict)
|
|
61
|
+
existing_raw: dict[str, str] = field(default_factory=dict)
|
|
62
|
+
# (key, raw value, why) for values btop itself would reset to the default.
|
|
63
|
+
invalid_existing: list[tuple[str, str, str]] = field(default_factory=list)
|
|
64
|
+
|
|
65
|
+
running: list[int] = field(default_factory=list)
|
|
66
|
+
env_notes: list[str] = field(default_factory=list)
|
|
67
|
+
|
|
68
|
+
def has(self) -> bool:
|
|
69
|
+
return bool(self.existing_text.strip())
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _run(cmd: list[str]) -> subprocess.CompletedProcess[str] | None:
|
|
73
|
+
try:
|
|
74
|
+
return subprocess.run(
|
|
75
|
+
cmd, capture_output=True, text=True, encoding="utf-8",
|
|
76
|
+
errors="replace", timeout=TIMEOUT, check=False,
|
|
77
|
+
)
|
|
78
|
+
except (OSError, subprocess.SubprocessError):
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def binary() -> str | None:
|
|
83
|
+
path = shutil.which("btop")
|
|
84
|
+
return str(Path(path).resolve()) if path else None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def config_dir() -> Path:
|
|
88
|
+
xdg = os.environ.get("XDG_CONFIG_HOME") or ""
|
|
89
|
+
return (Path(xdg) if xdg else Path.home() / ".config") / "btop"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def config_file() -> Path:
|
|
93
|
+
return config_dir() / CONFIG_FILE
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def version(binary_path: str) -> str:
|
|
97
|
+
result = _run([binary_path, "--version"])
|
|
98
|
+
if result is None or result.returncode != 0:
|
|
99
|
+
return ""
|
|
100
|
+
# `btop version: \x1b[1m1.4.6\x1b[0m` on 1.4.x, `btop version: 1.3.0` on 1.3.0.
|
|
101
|
+
m = _VERSION.search(render.strip_ansi(result.stdout))
|
|
102
|
+
return m.group(1) if m else ""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _parse_defaults(text: str) -> tuple[str, frozenset[str], dict[str, str]]:
|
|
106
|
+
"""(header, key set, raw defaults) out of a defaults dump."""
|
|
107
|
+
header = text.splitlines()[0] if text.startswith("#?") else ""
|
|
108
|
+
keys: set[str] = set()
|
|
109
|
+
defaults: dict[str, str] = {}
|
|
110
|
+
for line in render.parse(text):
|
|
111
|
+
if line.key is not None:
|
|
112
|
+
keys.add(line.key)
|
|
113
|
+
defaults.setdefault(line.key, line.raw_value)
|
|
114
|
+
return header, frozenset(keys), defaults
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _first_run_config(binary_path: str) -> str:
|
|
118
|
+
"""1.3.0 has no `--default-config`, but its first run writes the same file —
|
|
119
|
+
so run it under a pty in a throwaway HOME and read what it wrote."""
|
|
120
|
+
from dev_setup.configure.btop.validate import run_pty
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
with tempfile.TemporaryDirectory(prefix="devstuff-btop-") as tmp:
|
|
124
|
+
home = Path(tmp)
|
|
125
|
+
run_pty(binary_path, home)
|
|
126
|
+
return (home / ".config" / "btop" / CONFIG_FILE).read_text(
|
|
127
|
+
encoding="utf-8", errors="replace"
|
|
128
|
+
)
|
|
129
|
+
except OSError:
|
|
130
|
+
return ""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def defaults_text(
|
|
134
|
+
binary_path: str, *, on_slow: Callable[[str], None] | None = None
|
|
135
|
+
) -> str:
|
|
136
|
+
result = _run([binary_path, "--default-config"])
|
|
137
|
+
if result is not None and result.returncode == 0 and result.stdout.startswith("#?"):
|
|
138
|
+
return result.stdout
|
|
139
|
+
if on_slow is not None:
|
|
140
|
+
on_slow(
|
|
141
|
+
"this btop has no --default-config — asking it for its defaults in "
|
|
142
|
+
"a hidden terminal (~3s)…"
|
|
143
|
+
)
|
|
144
|
+
return _first_run_config(binary_path)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def themes(found: Btop) -> tuple[str, ...]:
|
|
148
|
+
"""The builtins plus every `*.theme` stem in the directories btop reads —
|
|
149
|
+
binary-relative `../share/btop/themes` first, the distro fallbacks, then the
|
|
150
|
+
user's own. A full path is never a value: btop does not apply one."""
|
|
151
|
+
out = ["Default", "TTY"]
|
|
152
|
+
dirs: list[Path] = []
|
|
153
|
+
if found.binary:
|
|
154
|
+
dirs.append((Path(found.binary).parent / ".." / "share" / "btop" / "themes").resolve())
|
|
155
|
+
dirs += [
|
|
156
|
+
Path("/usr/local/share/btop/themes"),
|
|
157
|
+
Path("/usr/share/btop/themes"),
|
|
158
|
+
config_dir() / "themes",
|
|
159
|
+
]
|
|
160
|
+
for directory in dirs:
|
|
161
|
+
try:
|
|
162
|
+
stems = sorted(p.stem for p in directory.glob("*.theme"))
|
|
163
|
+
except OSError:
|
|
164
|
+
continue
|
|
165
|
+
for stem in stems:
|
|
166
|
+
if stem not in out:
|
|
167
|
+
out.append(stem)
|
|
168
|
+
return tuple(out)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def running(proc_root: Path = Path("/proc")) -> list[int]:
|
|
172
|
+
"""Pids of `btop` processes owned by this user."""
|
|
173
|
+
me = os.getuid()
|
|
174
|
+
pids: list[int] = []
|
|
175
|
+
try:
|
|
176
|
+
entries = list(proc_root.iterdir())
|
|
177
|
+
except OSError:
|
|
178
|
+
return pids
|
|
179
|
+
for entry in entries:
|
|
180
|
+
if not entry.name.isdigit():
|
|
181
|
+
continue
|
|
182
|
+
try:
|
|
183
|
+
if entry.stat().st_uid != me:
|
|
184
|
+
continue
|
|
185
|
+
if (entry / "comm").read_text().strip() == "btop":
|
|
186
|
+
pids.append(int(entry.name))
|
|
187
|
+
except OSError:
|
|
188
|
+
continue
|
|
189
|
+
return sorted(pids)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# ---------------------------------------------------------------------------
|
|
193
|
+
# Existing file → wizard state
|
|
194
|
+
# ---------------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _box_tokens(found: Btop) -> set[str]:
|
|
198
|
+
tokens = set(BOXES)
|
|
199
|
+
# gpuN is only real on a GPU build; "keys unknown" cannot promise it, so it
|
|
200
|
+
# is only accepted when `shown_gpus` is in the key set.
|
|
201
|
+
if found.keys is not None and "shown_gpus" in found.keys:
|
|
202
|
+
tokens.update(GPU_BOXES)
|
|
203
|
+
return tokens
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _coerce_existing(
|
|
207
|
+
setting: Setting, value: object, found: Btop
|
|
208
|
+
) -> tuple[object, str]:
|
|
209
|
+
"""(value to carry into the wizard, why-it-was-reset-or-empty).
|
|
210
|
+
|
|
211
|
+
Mirrors what btop itself does with a bad value: a rejected one becomes the
|
|
212
|
+
effective default and is reported; a silently-kept one (an enum string btop
|
|
213
|
+
does not validate, an unknown theme) is carried as-is so `verify` can flag it.
|
|
214
|
+
"""
|
|
215
|
+
kind = setting.kind
|
|
216
|
+
if kind == "bool":
|
|
217
|
+
if isinstance(value, bool):
|
|
218
|
+
return value, ""
|
|
219
|
+
return render.effective_default(setting, found), "not true/false — btop resets it"
|
|
220
|
+
if kind == "int":
|
|
221
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
222
|
+
if value < 0:
|
|
223
|
+
return render.effective_default(setting, found), "negative — btop resets it"
|
|
224
|
+
if setting.minimum is not None and value < setting.minimum:
|
|
225
|
+
return (
|
|
226
|
+
render.effective_default(setting, found),
|
|
227
|
+
f"below {setting.minimum} — btop resets it",
|
|
228
|
+
)
|
|
229
|
+
if setting.maximum is not None and value > setting.maximum:
|
|
230
|
+
return (
|
|
231
|
+
render.effective_default(setting, found),
|
|
232
|
+
f"above {setting.maximum} — btop resets it",
|
|
233
|
+
)
|
|
234
|
+
return value, ""
|
|
235
|
+
return render.effective_default(setting, found), "not an integer — btop resets it"
|
|
236
|
+
if kind == "boxes":
|
|
237
|
+
if not isinstance(value, str):
|
|
238
|
+
return render.effective_default(setting, found), "not a string — btop resets it"
|
|
239
|
+
if value == "":
|
|
240
|
+
# btop accepts it and shows "No boxes shown!" — kept so verify flags it.
|
|
241
|
+
return value, ""
|
|
242
|
+
bad = [t for t in value.split() if t not in _box_tokens(found)]
|
|
243
|
+
if bad:
|
|
244
|
+
return (
|
|
245
|
+
render.effective_default(setting, found),
|
|
246
|
+
f"unknown box {' '.join(bad)!r} — btop resets the whole list silently",
|
|
247
|
+
)
|
|
248
|
+
return value, ""
|
|
249
|
+
if kind == "enum":
|
|
250
|
+
if not isinstance(value, str):
|
|
251
|
+
return render.effective_default(setting, found), "not a string — btop resets it"
|
|
252
|
+
if value in setting.choices:
|
|
253
|
+
return value, ""
|
|
254
|
+
# Measured: a bad graph_symbol is rejected and reset, while
|
|
255
|
+
# proc_sorting/temp_scale are kept verbatim — so the former becomes the
|
|
256
|
+
# default and the latter is carried for `verify` to flag.
|
|
257
|
+
if setting.key == "graph_symbol":
|
|
258
|
+
return (
|
|
259
|
+
render.effective_default(setting, found),
|
|
260
|
+
"not a graph symbol — btop resets it",
|
|
261
|
+
)
|
|
262
|
+
return value, ""
|
|
263
|
+
# str / theme — kept as written; an unknown theme or a bad clock_format is for
|
|
264
|
+
# `verify` to flag, exactly as btop keeps them.
|
|
265
|
+
if isinstance(value, str):
|
|
266
|
+
return value, ""
|
|
267
|
+
return render.effective_default(setting, found), "not a string — btop resets it"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def from_existing(found: Btop) -> BtopConfig:
|
|
271
|
+
"""Read the config on disk back into wizard state.
|
|
272
|
+
|
|
273
|
+
Every modelled key maps onto a field; a value btop itself would reject is
|
|
274
|
+
turned into the effective default and recorded in `invalid_existing` for the
|
|
275
|
+
report — which is what btop does, measured, rather than an invention here.
|
|
276
|
+
Keys the wizard does not model are left in the file untouched by the splice.
|
|
277
|
+
"""
|
|
278
|
+
cfg = BtopConfig(preset="current", target=found.path)
|
|
279
|
+
found.invalid_existing.clear()
|
|
280
|
+
for key, setting in SETTINGS.items():
|
|
281
|
+
if key not in found.existing:
|
|
282
|
+
continue
|
|
283
|
+
value, why = _coerce_existing(setting, found.existing[key], found)
|
|
284
|
+
setattr(cfg, key, value)
|
|
285
|
+
if why:
|
|
286
|
+
found.invalid_existing.append(
|
|
287
|
+
(key, found.existing_raw.get(key, repr(found.existing[key])), why)
|
|
288
|
+
)
|
|
289
|
+
return cfg
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def apply_preset(cfg: BtopConfig, key: str, found: Btop) -> None:
|
|
293
|
+
if key == "current":
|
|
294
|
+
carried = from_existing(found)
|
|
295
|
+
carried.preset = key
|
|
296
|
+
_copy_into(cfg, carried)
|
|
297
|
+
return
|
|
298
|
+
fresh = BtopConfig(preset=key, target=cfg.target)
|
|
299
|
+
for name, value in PRESETS[key].values.items():
|
|
300
|
+
setattr(fresh, name, value)
|
|
301
|
+
_copy_into(cfg, fresh)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _copy_into(target: BtopConfig, source: BtopConfig) -> None:
|
|
305
|
+
for name in vars(source):
|
|
306
|
+
setattr(target, name, getattr(source, name))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def suggest(found: Btop) -> BtopConfig:
|
|
310
|
+
"""An existing config is the starting point; otherwise btop's defaults."""
|
|
311
|
+
if found.has():
|
|
312
|
+
return from_existing(found)
|
|
313
|
+
cfg = BtopConfig(target=found.path)
|
|
314
|
+
apply_preset(cfg, "defaults", found)
|
|
315
|
+
return cfg
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ---------------------------------------------------------------------------
|
|
319
|
+
# inspect()
|
|
320
|
+
# ---------------------------------------------------------------------------
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def inspect(*, on_slow: Callable[[str], None] | None = None) -> Btop:
|
|
324
|
+
"""Read the machine. `on_slow` is called once if the ~3s first-run probe is
|
|
325
|
+
about to run, so the caller can say why the wizard paused."""
|
|
326
|
+
found = Btop()
|
|
327
|
+
found.binary = binary() or ""
|
|
328
|
+
found.installed = bool(found.binary)
|
|
329
|
+
found.path = config_file()
|
|
330
|
+
|
|
331
|
+
if found.installed:
|
|
332
|
+
found.version = version(found.binary)
|
|
333
|
+
text = defaults_text(found.binary, on_slow=on_slow)
|
|
334
|
+
if text:
|
|
335
|
+
found.header, found.keys, found.defaults = _parse_defaults(text)
|
|
336
|
+
found.themes = themes(found)
|
|
337
|
+
found.running = running()
|
|
338
|
+
|
|
339
|
+
try:
|
|
340
|
+
found.existing_text = found.path.read_text(encoding="utf-8", errors="replace")
|
|
341
|
+
except OSError:
|
|
342
|
+
found.existing_text = ""
|
|
343
|
+
if found.existing_text:
|
|
344
|
+
found.existing = render.values(found.existing_text)
|
|
345
|
+
found.existing_raw = {
|
|
346
|
+
line.key: line.raw_value
|
|
347
|
+
for line in render.parse(found.existing_text)
|
|
348
|
+
if line.key is not None
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
xdg = os.environ.get("XDG_CONFIG_HOME") or ""
|
|
352
|
+
if xdg:
|
|
353
|
+
found.env_notes.append(f"XDG_CONFIG_HOME is set — btop reads {config_dir()}")
|
|
354
|
+
return found
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
__all__ = [
|
|
358
|
+
"Btop",
|
|
359
|
+
"apply_preset",
|
|
360
|
+
"binary",
|
|
361
|
+
"config_dir",
|
|
362
|
+
"config_file",
|
|
363
|
+
"defaults_text",
|
|
364
|
+
"from_existing",
|
|
365
|
+
"inspect",
|
|
366
|
+
"running",
|
|
367
|
+
"suggest",
|
|
368
|
+
"themes",
|
|
369
|
+
"version",
|
|
370
|
+
]
|