"""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())