testsAndMisc/python_pkg/vscode_optimizer/_hardware.py
Krzysztof kuhy Rudnicki 377a352d48
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
vscode_optimizer: split _optimize.py 498 -> 100 + 5 modules
The last python file over the 250-line cap. Now that it sits at 100% line
and branch coverage, split along its natural seams:

  _types.py     48  the three dataclasses, so nothing imports a sibling
                    merely to name a type (which would have made a cycle)
  _render.py    69  the ANSI palette and the printers
  _config_io.py 104 variant discovery, JSONC parsing, reads and writes
  _hardware.py  106 _run and the four probes
  _plan.py      156 the pure hardware -> proposed-changes functions
  _optimize.py  100 the CLI entry: _apply_variant and main

Definitions were moved by line range rather than retyped. A throwaway
ast.dump identity check against HEAD confirms all 26 top-level definitions
are unchanged - formatting-blind, logic-sensitive.

The first attempt raised NameError: name '_BO' is not defined at runtime;
_BO was used by main() but missing from the _render import list. Rather than
fix that one failure alone, an AST scan over all six modules for names used
but not bound confirmed nothing else was missing.

Test imports now name the owning module; no re-export barrels. One patch
target genuinely moved - the guard-rail test patches _config_io.Path, since
that is the namespace resolving the name when _discover_variants is called
directly rather than through main().

Verified: same 98 tests pass with every module at 100% line and branch;
python3 -m python_pkg.vscode_optimizer --dry-run reproduces the same
18-change plan and writes nothing; repo-wide pytest 1846 passed at 100%;
over-cap files 36 -> 35.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-17 13:15:50 +02:00

107 lines
3.0 KiB
Python

"""Probe the machine's CPU, RAM, GPU, and root disk.
Every probe shells out and degrades to a default rather than raising, so a
missing tool narrows the report instead of failing the run.
"""
from __future__ import annotations
from pathlib import Path
import re
import subprocess
from python_pkg.vscode_optimizer._types import _Hw
_MIB_1024 = 1024
_LSCPU = {
"Model name": "cpu_model",
"CPU(s)": "cpu_logical_cores",
"Core(s) per socket": "cpu_physical_cores",
"CPU max MHz": "cpu_max_mhz",
}
_VENDOR_KW = {"nvidia": "NVIDIA", "amd": "AMD", "ati": "AMD", "intel": "Intel"}
def _run(args: list[str]) -> str:
"""Run *args* and return stdout, or ``""`` on failure."""
try:
proc = subprocess.run(
args,
capture_output=True,
text=True,
timeout=10,
check=False,
)
except (subprocess.TimeoutExpired, FileNotFoundError):
return ""
return proc.stdout.strip()
def _detect_cpu(hw: _Hw) -> None:
for line in _run(["lscpu"]).splitlines():
key, _, val = line.partition(":")
attr = _LSCPU.get(key.strip())
if attr == "cpu_model":
hw.cpu_model = val.strip()
elif attr == "cpu_max_mhz":
hw.cpu_max_mhz = float(val)
elif attr is not None:
setattr(hw, attr, int(val))
def _detect_ram(hw: _Hw) -> None:
try:
meminfo = Path("/proc/meminfo").read_text(encoding="utf-8")
except OSError:
return
m = re.search(r"MemTotal:\s+(\d+)\s+kB", meminfo)
if m:
hw.ram_total_mb = int(m.group(1)) // _MIB_1024
def _detect_gpu(hw: _Hw) -> None:
for line in _run(["lspci"]).splitlines():
low = line.lower()
if "vga" not in low and "3d" not in low:
continue
hw.gpu_model = line.rsplit(":", maxsplit=1)[-1].strip()
for kw, vendor in _VENDOR_KW.items():
if kw in low:
hw.gpu_vendor = vendor
break
if hw.gpu_vendor == "NVIDIA":
vram = _run(
[
"nvidia-smi",
"--query-gpu=memory.total",
"--format=csv,noheader,nounits",
]
)
if vram:
hw.gpu_vram_mb = int(vram.split("\n")[0].strip())
break
def _detect_disk(hw: _Hw) -> None:
root_dev = _run(["findmnt", "-n", "-o", "SOURCE", "/"])
if not root_dev:
return
base = re.sub(r"p?\d+$", "", Path(root_dev).name)
rotational = Path(f"/sys/block/{base}/queue/rotational")
if not rotational.exists():
return
if rotational.read_text(encoding="utf-8").strip() == "1":
hw.disk_type = "hdd"
elif "nvme" in base:
hw.disk_type = "nvme"
else:
hw.disk_type = "ssd"
def _detect_hardware() -> _Hw:
"""Probe CPU, RAM, GPU, and root disk type."""
hw = _Hw()
for fn in (_detect_cpu, _detect_ram, _detect_gpu, _detect_disk):
fn(hw)
return hw