#!/usr/bin/python3 import configparser import json import os import tempfile from dataclasses import dataclass, field # ── Game data model ───────────────────────────────────────────────────── @dataclass class Game: gameid: str = "" title: str = "" path: str = "" prefix: str = "" launch_arguments: str = "" game_arguments: str = "" protonfix: str = "" runner: str = "" playtime: int | str = 0 hidden: bool = False favorite: bool = False environment: list[str] = field(default_factory=list) # e.g. ["WINEDLLOVERRIDES=foo", "CUSTOM=val"] def to_dict(self): """Convert to a dict suitable for JSON storage.""" return { "gameid": self.gameid, "title": self.title, "path": self.path, "prefix": self.prefix, "launch_arguments": self.launch_arguments, "game_arguments": self.game_arguments, "protonfix": self.protonfix, "runner": self.runner, "playtime": self.playtime, "hidden": self.hidden, "favorite": self.favorite, "environment": self.environment, } @classmethod def from_dict(cls, data: dict): """Create a Game instance from a JSON-compatible dict.""" return cls( gameid=data.get("gameid", ""), title=data.get("title", ""), path=data.get("path", ""), prefix=data.get("prefix", ""), launch_arguments=data.get("launch_arguments", ""), game_arguments=data.get("game_arguments", ""), protonfix=data.get("protonfix", ""), runner=data.get("runner", ""), playtime=data.get("playtime", 0), hidden=data.get("hidden", False), favorite=data.get("favorite", False), environment=data.get("environment", []), ) # ── JSON I/O helpers (deprecated — kept for migration fallback) ───────── # These are no longer used by the new per-game storage but remain for # the one-shot migration from monolithic games.json. def load_games_json(path): """Load games from a JSON file. Returns a list of Game objects. Returns an empty list if the file does not exist or is invalid JSON. """ try: with open(path, encoding="utf-8") as f: raw = json.load(f) except (FileNotFoundError, json.JSONDecodeError): return [] return [Game.from_dict(d) for d in raw] # ── Per-game INI storage ──────────────────────────────────────────────── def _bool_to_ini(value: bool) -> str: """Convert a boolean to an INI-compatible string.""" return "true" if value else "false" def _ini_to_bool(value: str) -> bool: """Convert an INI string to a boolean.""" return value.strip().lower() in ("true", "1", "yes") GAME_INI_SECTION = "game" # Fields that require type coercion when reading from INI _GAME_INT_FIELDS = {"playtime"} _GAME_BOOL_FIELDS = {"hidden", "favorite"} class GameLibrary: """Manages per-game INI files in a directory. Each game is stored as ``{gameid}.ini`` under *games_dir*, with all fields in a ``[game]`` section. Writes are atomic (write to temp file, then rename) to prevent corruption on crash. Parameters ---------- games_dir : str, optional Directory containing per-game ``.ini`` files. Defaults to ``~/.config/fungus-launcher/games``. """ def __init__(self, games_dir: str | None = None): if games_dir is None: from fungus.path_manager import PathManager games_dir = PathManager.user_config("fungus-launcher/games") self.games_dir = games_dir os.makedirs(self.games_dir, exist_ok=True) # ── File helpers ─────────────────────────────────────────────────── def _ini_path(self, gameid: str) -> str: """Return the filesystem path for *gameid*.""" return os.path.join(self.games_dir, f"{gameid}.ini") def _write_ini(self, gameid: str, data: dict) -> None: """Write *data* to a ``{gameid}.ini`` file atomically. Writes to a temporary file in the same directory, then renames into place. This guarantees that a crash mid-write never leaves a partial or corrupt game file. """ ini_path = self._ini_path(gameid) tmp_fd, tmp_path = tempfile.mkstemp( suffix=".ini.tmp", dir=self.games_dir ) try: with os.fdopen(tmp_fd, "w", encoding="utf-8") as fh: config = configparser.ConfigParser() config[GAME_INI_SECTION] = data config.write(fh) os.replace(tmp_path, ini_path) # atomic on POSIX except BaseException: # Clean up temp file on any failure if os.path.exists(tmp_path): os.unlink(tmp_path) raise # ── Public API ───────────────────────────────────────────────────── def exists(self, gameid: str) -> bool: """Return ``True`` if a game file for *gameid* exists on disk.""" return os.path.isfile(self._ini_path(gameid)) def load(self, gameid: str) -> Game | None: """Load a single game by ID. Returns ``None`` if the file does not exist or is invalid. """ ini_path = self._ini_path(gameid) if not os.path.isfile(ini_path): return None try: config = configparser.ConfigParser() config.read(ini_path, encoding="utf-8") section = config[GAME_INI_SECTION] except (configparser.Error, KeyError): return None data: dict[str, str] = dict(section) # Parse per-game environment variables env_raw = data.get("environment", "").strip() if env_raw: env_list = [line for line in env_raw.splitlines() if line.strip()] else: env_list = [] return Game( gameid=data.get("gameid", ""), title=data.get("title", ""), path=data.get("path", ""), prefix=data.get("prefix", ""), launch_arguments=data.get("launch_arguments", ""), game_arguments=data.get("game_arguments", ""), protonfix=data.get("protonfix", ""), runner=data.get("runner", ""), playtime=int(data.get("playtime", 0)), hidden=_ini_to_bool(data.get("hidden", "false")), favorite=_ini_to_bool(data.get("favorite", "false")), environment=env_list, ) def load_all(self) -> list[Game]: """Enumerate all ``.ini`` files in the games directory and load them. Returns a list of ``Game`` objects. If the same ``gameid`` appears in multiple files, the first occurrence wins and a warning is logged. """ try: from fungus.logger import get_logger log = get_logger(__name__) except ImportError: log = None # type: ignore[assignment] games: list[Game] = [] seen: dict[str, str] = {} # gameid -> filename try: entries = sorted(os.listdir(self.games_dir)) except OSError: return [] for fname in entries: if not fname.endswith(".ini"): continue gameid_from_file = fname[:-4] # strip .ini game = self.load(gameid_from_file) if game is None: continue if game.gameid in seen: if log: log.warning( "Duplicate gameid '%s' in %s and %s — skipping %s", game.gameid, seen[game.gameid], fname, fname, ) continue seen[game.gameid] = fname games.append(game) return games def save(self, game: Game) -> None: """Persist a single ``Game`` to its ``.ini`` file atomically.""" data: dict[str, str] = { "gameid": game.gameid, "title": game.title, "path": game.path, "prefix": game.prefix, "launch_arguments": game.launch_arguments, "game_arguments": game.game_arguments, "protonfix": game.protonfix, "runner": game.runner, "playtime": str(game.playtime), "hidden": _bool_to_ini(game.hidden), "favorite": _bool_to_ini(game.favorite), } if game.environment: data["environment"] = "\n".join(game.environment) self._write_ini(game.gameid, data) def delete(self, gameid: str) -> bool: """Remove a game's ``.ini`` file. Returns ``True`` if the file was deleted, ``False`` if it didn't exist. """ ini_path = self._ini_path(gameid) if os.path.isfile(ini_path): os.unlink(ini_path) return True return False def update_field(self, gameid: str, field: str, value) -> bool: """Load one game, set a field, and save it back. Returns ``True`` if the game was found and updated, ``False`` if the gameid does not exist. """ game = self.load(gameid) if game is None: return False setattr(game, field, value) self.save(game) return True def add(self, game: Game) -> bool: """Add a new game to the library. Returns ``True`` if the game was added, ``False`` if a game with the same ``gameid`` already exists. """ if self.exists(game.gameid): return False self.save(game) return True def save_all(self, games: list[Game]) -> None: """Persist a list of games. Each game is written atomically. This is useful for batch operations (e.g. after a library scan). Games are written individually — no single monolithic file is used. """ for game in games: self.save(game) # ── Migration: monolithic games.json → per-game INI files ─────────────── @dataclass class MigrationResult: """Result of a migration operation.""" migrated: int = 0 skipped_duplicate: int = 0 skipped_error: int = 0 errors: list[str] = field(default_factory=list) def migrate_to_per_game( games_json_path: str, games_dir: str, *, dry_run: bool = False ) -> MigrationResult: """Migrate a monolithic ``games.json`` to per-game ``.ini`` files. Steps: 1. Back up ``games.json`` to the backup directory 2. Load all games from ``games.json`` 3. Deduplicate by ``gameid`` (keep first occurrence) 4. Write one ``.ini`` per game to ``games_dir/{gameid}.ini`` 5. Rename ``games.json`` → ``games.json.migrated`` Parameters ---------- games_json_path : str Path to the existing monolithic ``games.json``. games_dir : str Target directory for per-game ``.ini`` files. dry_run : bool, default False If ``True``, perform all steps except the final rename. Useful for testing. Returns ------- MigrationResult Summary of what was migrated, skipped, and any errors. """ result = MigrationResult() # Step 1: load games from JSON # (games.json is preserved as games.json.migrated — no separate backup needed) games = load_games_json(games_json_path) if not games: # Empty or missing file — nothing to migrate, but still rename if source exists if not dry_run and os.path.isfile(games_json_path): migrated_path = games_json_path + ".migrated" os.replace(games_json_path, migrated_path) return result # Step 3: deduplicate by gameid (keep first occurrence) seen: dict[str, int] = {} # gameid -> index in games list deduped: list[Game] = [] for i, game in enumerate(games): if game.gameid in seen: result.skipped_duplicate += 1 else: seen[game.gameid] = i deduped.append(game) # Step 4: write per-game INI files library = GameLibrary(games_dir) for game in deduped: try: library.save(game) result.migrated += 1 except Exception as exc: result.skipped_error += 1 result.errors.append(f"Failed to write {game.gameid}: {exc}") # Step 5: rename games.json → games.json.migrated (skip in dry-run) if not dry_run: migrated_path = games_json_path + ".migrated" os.replace(games_json_path, migrated_path) return result def needs_migration(games_json_path: str, games_dir: str) -> bool: """Return ``True`` if a migration from monolithic JSON is needed. Migration is needed when the old ``games.json`` exists but the new per-game directory has not yet been created. """ return os.path.isfile(games_json_path) and not os.path.isdir(games_dir)