- kurgan/hw/install.py (run elevated by setup.ps1): checks the base interpreter can run hw_service.py, creates %ProgramData%\Kurgan or resets its owner and access (Administrators own it; SYSTEM and Administrators full control, users read), moves the fan and RAM settings there, then creates or updates KurganHw through the service manager API (pywin32; sc.exe's quoting from Windows PowerShell 5.1 isn't reliable): LocalSystem, automatic start, restart after 5 s, 10 s and 60 s, the user's SID for the pipe. A running service is stopped first; then it's started and must reach "running". - kurgan/hw/migrate.py: "copy" (elevated) creates hw-settings.json from the user's cooling and lighting.memory, never overwriting an existing file; "strip" (as the user) removes them from settings.json once hw-settings.json exists, keeping a dated backup. An invalid file on either side stops it. - setup.ps1: creates the .venv if needed (the service runs from it), passes the base interpreter, the user's SID and settings path to the elevated part, which installs the service; then strips settings.json, registers and starts the app's task, and prints the service's status. - uninstall.ps1: also stops and deletes the service. - python -m kurgan.hw.client prints the service's status (setup runs it). - The pipe's "isn't running", "refused this user" and "closed the connection" errors no longer repeat the Windows error text. - Tests: migration (move, re-run, defaults, invalid files) and the install module's parts that don't need admin rights. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
114 lines
4.5 KiB
Python
114 lines
4.5 KiB
Python
"""Moving the fan and RAM lighting settings from the user's settings.json to hw-settings.json.
|
|
|
|
setup.ps1 runs both halves, once per install; each is safe to run again:
|
|
|
|
python -m kurgan.hw.migrate copy USER_SETTINGS elevated: create hw-settings.json from the user's
|
|
`cooling` and `lighting.memory`, unless it exists
|
|
python -m kurgan.hw.migrate strip as the user: once hw-settings.json exists, remove
|
|
them from settings.json, keeping a dated backup
|
|
|
|
An invalid file on either side stops the move (and setup) rather than lose a setting.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import copy as _copy
|
|
import json
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import time
|
|
|
|
from kurgan import paths
|
|
from kurgan.hw import settings as hw_settings
|
|
from kurgan.settings import SettingsError, validate, write_json_atomic
|
|
|
|
|
|
def _read_json(path: str) -> dict | None:
|
|
"""The file's contents, or None if it doesn't exist; SettingsError if it isn't valid JSON."""
|
|
try:
|
|
with open(path, encoding="utf-8") as stream:
|
|
return json.load(stream)
|
|
except FileNotFoundError:
|
|
return None
|
|
except ValueError as e:
|
|
raise SettingsError(f"{path}: {e}") from None
|
|
|
|
|
|
def hardware_sections(user: dict) -> dict:
|
|
"""The parts of a user settings.json that belong to the hardware service."""
|
|
out: dict = {}
|
|
if isinstance(user.get("cooling"), dict):
|
|
out["cooling"] = dict(user["cooling"])
|
|
lighting = user.get("lighting")
|
|
if isinstance(lighting, dict) and "memory" in lighting:
|
|
out["lighting"] = {"memory": lighting["memory"]}
|
|
return out
|
|
|
|
|
|
def copy(user_path: str, hw_path: str = paths.HW_SETTINGS_PATH) -> str:
|
|
"""Create hw-settings.json from the user's settings, unless it exists. Returns what it did."""
|
|
if os.path.exists(hw_path):
|
|
return f"{hw_path} already exists; left as it is"
|
|
raw = _read_json(user_path)
|
|
sections = {}
|
|
if raw is not None:
|
|
try:
|
|
sections = hardware_sections(validate(raw))
|
|
except SettingsError as e:
|
|
raise SettingsError(f"{user_path}: {e}") from None
|
|
try:
|
|
data = hw_settings.validate(sections)
|
|
except SettingsError as e:
|
|
raise SettingsError(f"{user_path}'s fan or RAM settings can't move: {e}") from None
|
|
write_json_atomic(hw_path, data)
|
|
moved = [name for name, present in (("cooling", "cooling" in sections),
|
|
("lighting.memory", "lighting" in sections)) if present]
|
|
return f"Created {hw_path}" + (f" with {' and '.join(moved)} from {user_path}" if moved else " with the defaults")
|
|
|
|
|
|
def strip(user_path: str = paths.SETTINGS_PATH, hw_path: str = paths.HW_SETTINGS_PATH, now: float | None = None) -> str:
|
|
"""Remove the hardware sections from the user's settings.json, once hw-settings.json exists."""
|
|
if not os.path.exists(hw_path):
|
|
return f"{hw_path} doesn't exist yet; settings.json left as it is"
|
|
raw = _read_json(user_path)
|
|
if raw is None or not hardware_sections(raw):
|
|
return f"Nothing to move out of {user_path}"
|
|
stripped = _copy.deepcopy(raw)
|
|
stripped.pop("cooling", None)
|
|
if isinstance(stripped.get("lighting"), dict):
|
|
stripped["lighting"].pop("memory", None)
|
|
try:
|
|
data = validate(stripped)
|
|
except SettingsError as e:
|
|
raise SettingsError(f"{user_path}: {e}") from None
|
|
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
|
|
backup = f"{user_path}.{stamp}.bak"
|
|
shutil.copy2(user_path, backup)
|
|
write_json_atomic(user_path, data)
|
|
return f"Removed the fan and RAM lighting settings from {user_path} (now in {hw_path}); backup: {backup}"
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
ap = argparse.ArgumentParser(prog="python -m kurgan.hw.migrate", description=__doc__,
|
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
sub = ap.add_subparsers(dest="action", required=True)
|
|
sub.add_parser("copy", help="create hw-settings.json (elevated)").add_argument("user_settings")
|
|
sub.add_parser("strip", help="tidy the user's settings.json (as the user)")
|
|
args = ap.parse_args(argv)
|
|
try:
|
|
if args.action == "copy":
|
|
hw_settings.ensure_data_dir()
|
|
print(copy(args.user_settings))
|
|
else:
|
|
print(strip())
|
|
except (OSError, SettingsError) as e:
|
|
print(f"error: {e}", file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|