devstuff 2.25.0__py3-none-any.whl → 2.27.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/commands/install_cmd.py +15 -1
- dev_setup/commands/list_cmd.py +6 -2
- dev_setup/commands/remove_cmd.py +6 -2
- dev_setup/commands/update_cmd.py +4 -1
- 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 +302 -24
- dev_setup/tools.yaml +170 -93
- dev_setup/ui.py +18 -2
- {devstuff-2.25.0.dist-info → devstuff-2.27.0.dist-info}/METADATA +37 -1
- {devstuff-2.25.0.dist-info → devstuff-2.27.0.dist-info}/RECORD +19 -12
- {devstuff-2.25.0.dist-info → devstuff-2.27.0.dist-info}/WHEEL +1 -1
- {devstuff-2.25.0.dist-info → devstuff-2.27.0.dist-info}/entry_points.txt +0 -0
|
@@ -7,7 +7,7 @@ import click
|
|
|
7
7
|
import questionary
|
|
8
8
|
from rich.markup import escape
|
|
9
9
|
|
|
10
|
-
from dev_setup import managers, registry, ui
|
|
10
|
+
from dev_setup import generic, 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
|
|
|
@@ -112,6 +112,13 @@ def _install_one(
|
|
|
112
112
|
status, detail = _install_one(dep, yes=yes) if dep else ("fail", "")
|
|
113
113
|
if status == "fail":
|
|
114
114
|
return "fail", f"required tool {dep_key} failed"
|
|
115
|
+
# A required tool's install can already provide this tool
|
|
116
|
+
# (ansible-vault is bundled with ansible) — re-check before doing
|
|
117
|
+
# the work a second time.
|
|
118
|
+
if tool.is_installed():
|
|
119
|
+
version = tool.get_version()
|
|
120
|
+
ui.success(f"{tool.name} is already installed: {version}")
|
|
121
|
+
return "skip", f"already installed{': ' + version if version else ''}"
|
|
115
122
|
else:
|
|
116
123
|
ui.error(f"Cannot install {tool.name} — missing: {', '.join(missing)}")
|
|
117
124
|
return "fail", "declined required tools"
|
|
@@ -128,7 +135,12 @@ def _install_one(
|
|
|
128
135
|
ui.success(msg)
|
|
129
136
|
except Exception as exc:
|
|
130
137
|
ui.error(f"Failed to install {tool.name}: {escape(str(exc))}")
|
|
138
|
+
ui.dim(f" full output: {generic.run_log_path()}")
|
|
131
139
|
return "fail", str(exc).splitlines()[-1][:120]
|
|
140
|
+
finally:
|
|
141
|
+
# An installer — even a failed one — may have changed the machine (added
|
|
142
|
+
# an apt repo, dropped a binary); the next tool's probes must re-read it.
|
|
143
|
+
generic.forget_probes()
|
|
132
144
|
|
|
133
145
|
# A freshly installed tool with a setup wizard is the moment to mention it.
|
|
134
146
|
from dev_setup.commands.configure_cmd import offer_after_install
|
|
@@ -196,6 +208,8 @@ def _install_interactive(*, yes: bool) -> None:
|
|
|
196
208
|
suffix, disabled_override = (
|
|
197
209
|
managers.picker_hint(note, t) if note is not None else ("", None)
|
|
198
210
|
)
|
|
211
|
+
if not is_inst:
|
|
212
|
+
suffix += " · sudo" if generic.needs_sudo(t) else " · user"
|
|
199
213
|
desc = t.description
|
|
200
214
|
room = max(10, desc_width - len(suffix))
|
|
201
215
|
if len(desc) > room:
|
dev_setup/commands/list_cmd.py
CHANGED
|
@@ -4,7 +4,7 @@ from concurrent.futures import ThreadPoolExecutor
|
|
|
4
4
|
|
|
5
5
|
import click
|
|
6
6
|
|
|
7
|
-
from dev_setup import managers, registry, ui
|
|
7
|
+
from dev_setup import generic, managers, registry, ui
|
|
8
8
|
from dev_setup.base import Tool
|
|
9
9
|
|
|
10
10
|
_MAX_WORKERS = 8
|
|
@@ -75,7 +75,11 @@ def list_cmd(show_filter: str, category: str) -> None:
|
|
|
75
75
|
line = managers.list_line(note, tool)
|
|
76
76
|
if line:
|
|
77
77
|
desc += f"\n{line}"
|
|
78
|
-
|
|
78
|
+
sudo_tag = "sudo" if generic.needs_sudo(tool) else "user"
|
|
79
|
+
tbl.add_row(
|
|
80
|
+
icon, tool.key, desc,
|
|
81
|
+
f"{tool.install_type} [{ui.GRAY}]· {sudo_tag}[/]", version,
|
|
82
|
+
)
|
|
79
83
|
|
|
80
84
|
ui.console.print(tbl)
|
|
81
85
|
ui.console.print()
|
dev_setup/commands/remove_cmd.py
CHANGED
|
@@ -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 generic, registry, ui
|
|
11
11
|
from dev_setup.base import Tool
|
|
12
12
|
from dev_setup.commands._plan import plan_for, plan_summary
|
|
13
13
|
|
|
@@ -87,7 +87,10 @@ def _remove_one(
|
|
|
87
87
|
return "ok", "removed"
|
|
88
88
|
except Exception as exc:
|
|
89
89
|
ui.error(f"Failed to remove {tool.name}: {escape(str(exc))}")
|
|
90
|
+
ui.dim(f" full output: {generic.run_log_path()}")
|
|
90
91
|
return "fail", str(exc).splitlines()[-1][:120]
|
|
92
|
+
finally:
|
|
93
|
+
generic.forget_probes()
|
|
91
94
|
|
|
92
95
|
|
|
93
96
|
def _confirm_plan(tool: Tool) -> bool:
|
|
@@ -127,9 +130,10 @@ def _remove_interactive(*, yes: bool) -> None:
|
|
|
127
130
|
for t in sorted(installed, key=lambda t: t.key):
|
|
128
131
|
deps = registry.dependents(t.key)
|
|
129
132
|
annotation = f" ⚠ required by: {', '.join(deps)}" if deps else ""
|
|
133
|
+
sudo_tag = " · sudo" if generic.needs_sudo(t, "remove") else " · user"
|
|
130
134
|
# Plain-string title: a token list would render verbatim and never pick
|
|
131
135
|
# up the `highlighted` style, leaving the cursor invisible.
|
|
132
|
-
title = f"{t.key:<{key_width}}{t.description}{annotation}"
|
|
136
|
+
title = f"{t.key:<{key_width}}{t.description}{annotation}{sudo_tag}"
|
|
133
137
|
choices.append(questionary.Choice(title=title, value=t.key, checked=False))
|
|
134
138
|
|
|
135
139
|
selected = ui.checkbox(
|
dev_setup/commands/update_cmd.py
CHANGED
|
@@ -6,7 +6,7 @@ import click
|
|
|
6
6
|
import questionary
|
|
7
7
|
from rich.markup import escape
|
|
8
8
|
|
|
9
|
-
from dev_setup import registry, ui
|
|
9
|
+
from dev_setup import generic, registry, ui
|
|
10
10
|
from dev_setup.base import Tool
|
|
11
11
|
from dev_setup.commands._plan import plan_for, plan_summary
|
|
12
12
|
from dev_setup.updates import collect_candidates
|
|
@@ -113,7 +113,10 @@ def _update_one(
|
|
|
113
113
|
return "ok", "updated"
|
|
114
114
|
except Exception as exc:
|
|
115
115
|
ui.error(f"Failed to update {tool.name}: {escape(str(exc))}")
|
|
116
|
+
ui.dim(f" full output: {generic.run_log_path()}")
|
|
116
117
|
return "fail", str(exc).splitlines()[-1][:120]
|
|
118
|
+
finally:
|
|
119
|
+
generic.forget_probes()
|
|
117
120
|
|
|
118
121
|
|
|
119
122
|
def _confirm_plan(tool: Tool, version: str | None) -> bool:
|
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
|
+
]
|