1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
|
#!/usr/bin/python3
import configparser
import json
import os
import tempfile
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
# ── 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
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,
}
@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),
)
# ── 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)
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")),
)
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.
"""
if TYPE_CHECKING:
from fungus.logger import get_logger
log = get_logger(__name__)
else:
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),
}
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)
|