diff options
| author | fox <fox@fakecake.org> | 2026-07-05 18:08:29 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-07-05 18:08:29 +0300 |
| commit | f8205cbfa571e5e4c2e57654580b46bec1b88c48 (patch) | |
| tree | a8b1fa74461775708493a37687a4b0dc5c05faad | |
| parent | f52874fb82125ca82286414a461eed655120fb88 (diff) | |
| parent | 11e51c73c992a573f681cc20b5bb80494b73a5af (diff) | |
| download | fungus-launcher-f8205cbfa571e5e4c2e57654580b46bec1b88c48.tar.gz fungus-launcher-f8205cbfa571e5e4c2e57654580b46bec1b88c48.tar.xz | |
Merge branch 'dev' into 'master'
deprecate and remove envar.txt and store global envs in config, add per-game env vars See merge request git/fungus-launcher!45
| -rw-r--r-- | fungus/__init__.py | 3 | ||||
| -rw-r--r-- | fungus/add_game_dialog.py | 88 | ||||
| -rw-r--r-- | fungus/config_manager.py | 20 | ||||
| -rw-r--r-- | fungus/constants.py | 1 | ||||
| -rw-r--r-- | fungus/game_launcher.py | 101 | ||||
| -rw-r--r-- | fungus/game_model.py | 14 | ||||
| -rw-r--r-- | fungus/main_window.py | 3 | ||||
| -rw-r--r-- | fungus/settings_dialog.py | 52 | ||||
| -rw-r--r-- | fungus/utils.py | 39 | ||||
| -rw-r--r-- | tests/test_run_manager.py | 119 |
10 files changed, 335 insertions, 105 deletions
diff --git a/fungus/__init__.py b/fungus/__init__.py index 9ae5253..6916c18 100644 --- a/fungus/__init__.py +++ b/fungus/__init__.py @@ -15,7 +15,6 @@ __all__ = [ "app_dir", "config_file_path", "desktop_dir", - "envar_dir", "format_title", "fungus_launcher_dir", "fungus_png", @@ -54,7 +53,6 @@ def __getattr__(name): app_dir, config_file_path, desktop_dir, - envar_dir, fungus_launcher_dir, fungus_png, fungus_run, @@ -66,7 +64,6 @@ def __getattr__(name): "app_dir": app_dir, "config_file_path": config_file_path, "desktop_dir": desktop_dir, - "envar_dir": envar_dir, "fungus_launcher_dir": fungus_launcher_dir, "fungus_png": fungus_png, "fungus_run": fungus_run, diff --git a/fungus/add_game_dialog.py b/fungus/add_game_dialog.py index 2db1d9c..25e12bf 100644 --- a/fungus/add_game_dialog.py +++ b/fungus/add_game_dialog.py @@ -284,6 +284,29 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): self.button_ok.connect("clicked", lambda widget: self.response(Gtk.ResponseType.OK)) self.button_ok.set_size_request(150, -1) + # ── Environment tab widgets ─────────────────────────────────── + self.liststore_environment = Gtk.ListStore(str) + self.liststore_environment.append([""]) + + self.treeview_environment = Gtk.TreeView(model=self.liststore_environment) + self.treeview_environment.set_has_tooltip(True) + self.treeview_environment.connect("query-tooltip", self._on_env_query_tooltip) + self.treeview_environment.connect("key-press-event", self.on_env_key_press) + renderer_env = Gtk.CellRendererText() + renderer_env.set_property("editable", True) + renderer_env.set_property("ellipsize", 3) + renderer_env.connect("edited", self.on_env_cell_edited) + column_env = Gtk.TreeViewColumn("", renderer_env, text=0) + self.treeview_environment.set_headers_visible(False) + self.treeview_environment.append_column(column_env) + + scrolled_env = Gtk.ScrolledWindow() + scrolled_env.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) + scrolled_env.set_min_content_height(130) + scrolled_env.add(self.treeview_environment) + + self._environment_vars: list[str] = [] + self.load_config() self.default_prefix = prefixes_dir @@ -310,6 +333,25 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): self.notebook.append_page(self.grid_page1, self.tab_box1) + # ── Page 3: Environment ─────────────────────────────────────── + page3 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) + page3.set_hexpand(True) + self.tab_box3 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) + tab_label3 = Gtk.Label(label="Environment") + tab_label3.set_width_chars(12) + tab_label3.set_xalign(0.5) + self.tab_box3.pack_start(tab_label3, True, True, 0) + self.tab_box3.set_hexpand(True) + + env_frame = Gtk.Frame() + env_frame.set_shadow_type(Gtk.ShadowType.IN) + env_frame.set_border_width(5) + env_frame.add(scrolled_env) + + page3.pack_start(env_frame, True, True, 0) + + self.notebook.append_page(page3, self.tab_box3) + page2 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.tab_box2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) tab_label2 = Gtk.Label(label="Tools") @@ -402,6 +444,7 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): self.tab_box1.show_all() self.tab_box2.show_all() + self.tab_box3.show_all() self.show_all() def populate_combobox_with_runners(self): @@ -889,3 +932,48 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): return False return True + + # ── Environment tab handlers ───────────────────────────────────── + + def populate_environment_from_game(self, game): + """Pre-populate the environment liststore from a Game object.""" + self.liststore_environment.clear() + for env_var in game.environment: + self.liststore_environment.append([env_var]) + self.liststore_environment.append([""]) + + def _collect_environment_vars(self) -> list[str]: + """Collect non-empty rows from the environment liststore.""" + return [row[0] for row in self.liststore_environment if row[0].strip()] + + def on_env_cell_edited(self, widget, path, text): + """Update the liststore cell on edit and normalize empty rows.""" + self.liststore_environment[path][0] = text + self._adjust_env_rows() + + def _adjust_env_rows(self): + """Remove empty rows and ensure a trailing empty row.""" + filled_rows = [row[0] for row in self.liststore_environment if row[0].strip() != ""] + self.liststore_environment.clear() + for value in filled_rows: + self.liststore_environment.append([value]) + self.liststore_environment.append([""]) + + def _on_env_query_tooltip(self, widget, x, y, keyboard_mode, tooltip): + """Tooltip handler for the environment variable treeview.""" + return self.on_list_query_tooltip(widget, x, y, keyboard_mode, tooltip, self.liststore_environment) + + def on_env_key_press(self, widget, event): + """Allow deleting environment variable rows via the Delete key (but not the last empty row).""" + if event.keyval == Gdk.KEY_Delete: + selection = widget.get_selection() + model, treeiter = selection.get_selected() + if not treeiter: + return False + path = model.get_path(treeiter) + index = path.get_indices()[0] + if index == len(model) - 1: + return True + model.remove(treeiter) + return True + return False diff --git a/fungus/config_manager.py b/fungus/config_manager.py index 683718b..58ac4d9 100644 --- a/fungus/config_manager.py +++ b/fungus/config_manager.py @@ -43,6 +43,26 @@ class ConfigManager: """Store *value* for *key* (converted to string).""" self._config.set(_CONFIG_SECTION, key, str(value)) + # ── Global environment variables ────────────────────────────────── + + def get_envars(self) -> list[str]: + """Return global environment variables as a list of KEY=VALUE strings.""" + raw = self._config.get(_CONFIG_SECTION, "environment", fallback="").strip() + if not raw: + return [] + return [line for line in raw.splitlines() if line.strip()] + + def set_envars(self, envvars: list[str]) -> None: + """Store global environment variables as a multiline string.""" + if envvars: + self._config.set(_CONFIG_SECTION, "environment", "\n".join(envvars)) + else: + # Remove the key if empty to keep INI clean + try: + self._config.remove_option(_CONFIG_SECTION, "environment") + except KeyError: + pass + def save(self) -> None: """Persist the current state to disk.""" _config_path.parent.mkdir(parents=True, exist_ok=True) diff --git a/fungus/constants.py b/fungus/constants.py index 90dc34e..554c616 100644 --- a/fungus/constants.py +++ b/fungus/constants.py @@ -23,7 +23,6 @@ def get_desktop_dir(): fungus_launcher_dir = PathManager.user_config('fungus-launcher') icons_dir = PathManager.user_config('fungus-launcher/icons') config_file_path = PathManager.user_config('fungus-launcher/config.ini') -envar_dir = PathManager.user_config('fungus-launcher/envar.txt') share_dir = PathManager.user_data() app_dir = PathManager.user_data('applications') diff --git a/fungus/game_launcher.py b/fungus/game_launcher.py index 685b516..16b3a22 100644 --- a/fungus/game_launcher.py +++ b/fungus/game_launcher.py @@ -21,7 +21,7 @@ from typing import ClassVar import psutil # type: ignore -from fungus.constants import envar_dir, share_dir, umu_run +from fungus.constants import share_dir, umu_run from fungus.game_model import Game, GameLibrary from fungus.path_manager import PathManager from fungus.config_manager import ConfigManager @@ -135,6 +135,21 @@ class GameLauncher: self._watchdog_thread = Thread(target=self._watchdog_loop, daemon=True) self._watchdog_thread.start() + # ── Sleep inhibition ──────────────────────────────────────────── + + def _build_inhibit_prefix(self, gameid: str) -> list[str]: + """Return [systemd-inhibit, …] if available, else [].""" + systemd_inhibit = PathManager.find_binary("systemd-inhibit") + if not systemd_inhibit: + log.debug("systemd-inhibit not found; sleep inhibition unavailable") + return [] + return [ + systemd_inhibit, + "--what=sleep:idle", + f"--why={gameid} is running", + "--mode=block", + ] + # ── Pure helpers ────────────────────────────────────────────────── @staticmethod @@ -147,31 +162,20 @@ class GameLauncher: # ── Environment / config ────────────────────────────────────────── - def load_env_from_file(self, filename: str = envar_dir) -> dict[str, str]: - """Read key=value pairs from *filename* and merge them into os.environ. + def load_global_env(self) -> dict[str, str]: + """Read global environment variables from config.ini. - Returns a dict of the loaded variables. Silently returns an - empty dict when the file does not exist. + Returns a dict suitable for merging into sandbox_env. """ - env_from_file: dict[str, str] = {} - - try: - with open(filename, encoding="utf-8") as f: - for raw_line in f: - line = raw_line.strip() - if not line or "=" not in line: - continue - - key, value = line.split("=", 1) - key, value = key.strip(), value.strip() - - os.environ[key] = value - env_from_file[key] = value - - except FileNotFoundError: - pass - - return env_from_file + env: dict[str, str] = {} + cfg = ConfigManager() + for raw_line in cfg.get_envars(): + line = raw_line.strip() + if not line or "=" not in line: + continue + key, value = line.split("=", 1) + env[key.strip()] = value.strip() + return env def load_config(self) -> None: """Load discrete-GPU and game-directories from config.""" @@ -214,11 +218,26 @@ class GameLauncher: # ── Sandbox command builder ─────────────────────────────────────── + def _build_per_game_env(self) -> dict[str, str]: + """Parse the game's environment list into a dict. + + Returns an empty dict when the game has no per-game env vars. + """ + env: dict[str, str] = {} + for raw_line in self.game.environment or []: + line = raw_line.strip() + if not line or "=" not in line: + continue + key, value = line.split("=", 1) + env[key.strip()] = value.strip() + return env + def build_bwrap_command( self, game: Game | None = None, game_dirs: list[str] | None = None, - env_from_file: dict[str, str] | None = None, + global_env: dict[str, str] | None = None, + per_game_env: dict[str, str] | None = None, ) -> tuple[list[str], dict[str, str], list[str]]: """Construct the bwrap sandbox and inner command. @@ -228,8 +247,10 @@ class GameLauncher: game = self.game if game_dirs is None: game_dirs = [] - if env_from_file is None: - env_from_file = {} + if global_env is None: + global_env = {} + if per_game_env is None: + per_game_env = {} bwrap_args: list[str] = [] sandbox_env: dict[str, str] = {} @@ -247,12 +268,16 @@ class GameLauncher: ]) # ── Environment variables from env file (base layer) ──────── - if env_from_file: - sandbox_env.update(env_from_file) + if global_env: + sandbox_env.update(global_env) + + # ── Per-game environment (override layer) ────────────────── + sandbox_env.update(per_game_env) - # ── Environment variables to pass through (override layer) ── + # ── Environment variables to pass through (highest layer) ── for key in self.SANDBOX_ENV_KEYS: - sandbox_env[key] = os.environ.get(key, "") + if key not in sandbox_env: + sandbox_env[key] = os.environ.get(key, "") # ── UMU-Launcher environment variables ────────────────────── sandbox_env["GAMEID"] = game.protonfix or game.gameid or "" @@ -361,9 +386,6 @@ class GameLauncher: self.start_time = time.time() os.environ["UMU_RUNTIME_UPDATE"] = "0" - # TODO make this customizable per-game - os.environ["WINEDLLOVERRIDES"] = "winmm=n,b;xgameruntime=n,b" - if logging.root.level <= logging.DEBUG: os.environ["UMU_LOG"] = "debug" os.environ["PROTON_LOG"] = "1" @@ -396,8 +418,11 @@ class GameLauncher: self._on_proton_path_missing(proton_dir) return LaunchHandle(None, 0) - # ── Load env file ─────────────────────────────────────────── - self.env_from_file = self.load_env_from_file(envar_dir) + # ── Load global env ───────────────────────────────────────── + self.global_env = self.load_global_env() + + # ── Build per-game environment ────────────────────────────── + per_game_env = self._build_per_game_env() # ── Build sandbox ─────────────────────────────────────────── valid_dirs: list[str] = [] @@ -417,7 +442,7 @@ class GameLauncher: self._on_sandbox_warning(exec_path, valid_dirs) bwrap_cmd, sandbox_env, inner_cmd = self.build_bwrap_command( - self.game, valid_dirs, self.env_from_file, + self.game, valid_dirs, self.global_env, per_game_env, ) log.info(f"final bwrap command: {bwrap_cmd}") @@ -427,7 +452,7 @@ class GameLauncher: run_env = os.environ.copy() run_env.update(sandbox_env) - full_cmd = bwrap_cmd + inner_cmd + full_cmd = self._build_inhibit_prefix(self.game.gameid) + bwrap_cmd + inner_cmd try: # we invoke popen() setting work directory as a dirname() of our executable diff --git a/fungus/game_model.py b/fungus/game_model.py index 2f114bc..3528cd5 100644 --- a/fungus/game_model.py +++ b/fungus/game_model.py @@ -21,6 +21,7 @@ class Game: 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.""" @@ -36,6 +37,7 @@ class Game: "playtime": self.playtime, "hidden": self.hidden, "favorite": self.favorite, + "environment": self.environment, } @classmethod @@ -53,6 +55,7 @@ class Game: playtime=data.get("playtime", 0), hidden=data.get("hidden", False), favorite=data.get("favorite", False), + environment=data.get("environment", []), ) @@ -170,6 +173,14 @@ class GameLibrary: 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", ""), @@ -182,6 +193,7 @@ class GameLibrary: 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]: @@ -242,6 +254,8 @@ class GameLibrary: "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: diff --git a/fungus/main_window.py b/fungus/main_window.py index b17b119..75cb76b 100644 --- a/fungus/main_window.py +++ b/fungus/main_window.py @@ -720,6 +720,7 @@ class Main(Gtk.ApplicationWindow): edit_game_dialog.set_title("Edit %s" % game.title) edit_game_dialog.entry_protonfix.set_text(game.protonfix) edit_game_dialog.grid_launcher.set_visible(False) + edit_game_dialog.populate_environment_from_game(game) image = self.set_image_shortcut_icon(game.title, edit_game_dialog.icons_path, edit_game_dialog.icon_temp) edit_game_dialog.button_shortcut_icon.set_image(image) @@ -890,6 +891,7 @@ class Main(Gtk.ApplicationWindow): title_formatted, title, path, prefix, launch_arguments, game_arguments, protonfix, runner, playtime, hidden, favorite, + add_game_dialog._collect_environment_vars(), ) icon_temp = os.path.expanduser(add_game_dialog.icon_temp) @@ -928,6 +930,7 @@ class Main(Gtk.ApplicationWindow): game.game_arguments = edit_game_dialog.entry_game_arguments.get_text() game.protonfix = edit_game_dialog.entry_protonfix.get_text() game.runner = edit_game_dialog.combobox_runner.get_active_text() + game.environment = edit_game_dialog._collect_environment_vars() title_formatted = format_title(game.title) diff --git a/fungus/settings_dialog.py b/fungus/settings_dialog.py index 9d37465..5f2e8f9 100644 --- a/fungus/settings_dialog.py +++ b/fungus/settings_dialog.py @@ -11,7 +11,6 @@ from gi.repository import Gtk, Gdk, Pango # type: ignore from fungus.constants import ( fungus_version, - envar_dir, fungus_png, fungus_proton_manager, @@ -61,7 +60,7 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): self.treeview_game_dirs = Gtk.TreeView(model=self.liststore_game_dirs) self.treeview_game_dirs.set_has_tooltip(True) - self.treeview_game_dirs.connect("query-tooltip", self.on_query_tooltip) + self.treeview_game_dirs.connect("query-tooltip", self._on_gamedirs_query_tooltip) self.treeview_game_dirs.connect("button-press-event", self.on_gamedirs_button_press) renderer_game_dirs = Gtk.CellRendererText() @@ -209,7 +208,7 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): treeview = Gtk.TreeView(model=self.liststore) treeview.set_has_tooltip(True) - treeview.connect("query-tooltip", self.on_query_tooltip) + treeview.connect("query-tooltip", self._on_env_query_tooltip) treeview.connect("key-press-event", self.on_envar_key_press) renderer = Gtk.CellRendererText() @@ -449,25 +448,13 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): total /= 1024.0 return f"{total:.1f} TB" - def on_query_tooltip(self, widget, x, y, keyboard_mode, tooltip): - """Show a tooltip with the cell value when hovering over a treeview row.""" - result = widget.get_path_at_pos(x, y) - if result is not None: - path, *_ = result - liststore = self.liststore - try: - tree_iter = liststore.get_iter(path) - except ValueError: - liststore = self.liststore_game_dirs - try: - tree_iter = liststore.get_iter(path) - except ValueError: - return False - value = liststore.get_value(tree_iter, 0) - if value.strip(): - tooltip.set_text(value) - return True - return False + def _on_env_query_tooltip(self, widget, x, y, keyboard_mode, tooltip): + """Tooltip handler for the environment variable treeview.""" + return self.on_list_query_tooltip(widget, x, y, keyboard_mode, tooltip, self.liststore) + + def _on_gamedirs_query_tooltip(self, widget, x, y, keyboard_mode, tooltip): + """Tooltip handler for the game directories treeview.""" + return self.on_list_query_tooltip(widget, x, y, keyboard_mode, tooltip, self.liststore_game_dirs) def on_cell_edited(self, widget, path, text, column_index): """Update the liststore cell and normalize empty rows.""" @@ -538,12 +525,12 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): return self.combobox_runner.get_active_text() def update_envar_file(self): - """Write all non-empty environment variable rows to the envar file.""" + """Write all non-empty environment variable rows to config.ini.""" if hasattr(self, "liststore"): values = [row[0] for row in self.liststore if row[0].strip() != ""] - with open(envar_dir, "w", encoding="utf-8") as f: - for val in values: - f.write(val + "\n") + cfg = ConfigManager() + cfg.set_envars(values) + cfg.save() def on_button_proton_manager_clicked(self, widget): """Launch the Proton Manager dialog as a blocking child window.""" @@ -818,7 +805,7 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): for path in paths: self.liststore_game_dirs.append([path]) - self.load_liststore_from_file(envar_dir) + self._load_liststore_from_config() # Load UMU-Launcher version info installed = get_installed_umu_version() @@ -834,15 +821,12 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): else: self.label_steam_runtime_last.set_text("Last checked: -") - def load_liststore_from_file(self, filename=envar_dir): - """Read environment variable lines from *filename* and populate the liststore.""" + def _load_liststore_from_config(self): + """Read global environment variable lines from config.ini and populate the liststore.""" self.liststore.clear() - try: - with open(filename, encoding="utf-8") as f: - lines = [line.strip() for line in f.readlines() if line.strip()] - except FileNotFoundError: - lines = [] + cfg = ConfigManager() + lines = cfg.get_envars() for line in lines: self.liststore.append([line]) diff --git a/fungus/utils.py b/fungus/utils.py index e9ae9dc..923628e 100644 --- a/fungus/utils.py +++ b/fungus/utils.py @@ -122,10 +122,14 @@ def pick_folder(title: str, transient_for, current_folder: str | None = None) -> class EntryTooltipMixin: - """Mixin providing a standard ``query-tooltip`` handler for GTK Entry widgets. + """Mixin providing standard ``query-tooltip`` handlers for GTK widgets. - Displays the entry's current text when non-empty, otherwise falls back - to the entry's ``tooltip-text`` property. + ``on_entry_query_tooltip`` — displays the entry's current text when + non-empty, otherwise falls back to the entry's ``tooltip-text`` property. + + ``on_list_query_tooltip`` — shows a tooltip with the cell value when + hovering over a TreeView row. Accepts a single *liststore* to resolve + the cell from. """ def on_entry_query_tooltip(self, widget, x, y, keyboard_mode, tooltip): @@ -135,3 +139,32 @@ class EntryTooltipMixin: else: tooltip.set_text(widget.get_tooltip_text()) return True + + def on_list_query_tooltip(self, widget, x, y, keyboard_mode, tooltip, liststore): + """Show a tooltip with the cell value when hovering over a treeview row. + + Parameters + ---------- + widget : Gtk.TreeView + The treeview that emitted the signal. + x, y : int + The cursor position inside *widget*. + keyboard_mode : bool + Whether the tooltip was triggered by the keyboard. + tooltip : Gtk.Tooltip + The tooltip widget to populate. + liststore : Gtk.ListStore + The liststore to resolve the cell from. + """ + result = widget.get_path_at_pos(x, y) + if result is not None: + path, *_ = result + try: + tree_iter = liststore.get_iter(path) + except ValueError: + return False + value = liststore.get_value(tree_iter, 0) + if value.strip(): + tooltip.set_text(value) + return True + return False diff --git a/tests/test_run_manager.py b/tests/test_run_manager.py index f324b06..8face5b 100644 --- a/tests/test_run_manager.py +++ b/tests/test_run_manager.py @@ -229,41 +229,97 @@ class TestResolveCommandPath: # --------------------------------------------------------------------------- -# Test load_env_from_file +# Test load_global_env # --------------------------------------------------------------------------- -class TestLoadEnvFromFile: - def test_loads_valid_env_file(self, fungus_run, env_file): - result = fungus_run.load_env_from_file(str(env_file)) - assert result == {"FOO": "bar", "BAZ": "qux"} +class TestLoadGlobalEnv: + def test_loads_envars_from_config(self, fungus_run): + """load_global_env should return env vars stored in ConfigManager.""" + result = fungus_run.load_global_env() + assert result == {} # No envars configured in fixture - def test_returns_empty_dict_for_missing_file(self, fungus_run, tmp_path): - result = fungus_run.load_env_file = fungus_run.load_env_from_file - result(tmp_path / "nonexistent.txt") - assert result(tmp_path / "nonexistent.txt") == {} + def test_ignores_empty_lines(self, tmp_path, fungus_run): + """Empty lines in the environment should be skipped.""" + from fungus.config_manager import ConfigManager - def test_ignores_empty_lines_and_comments(self, tmp_path, fungus_run): - env_path = tmp_path / "env.txt" - env_path.write_text( - "FOO=bar\n\n# comment\nBAZ=qux\n\n", - encoding="utf-8", - ) - result = fungus_run.load_env_from_file(str(env_path)) + mock_cfg = MagicMock() + mock_cfg.get_envars.return_value = ["FOO=bar", "", "BAZ=qux", ""] + with patch.object(ConfigManager, "__new__", return_value=mock_cfg): + result = fungus_run.load_global_env() assert result == {"FOO": "bar", "BAZ": "qux"} def test_splits_on_first_equals_only(self, tmp_path, fungus_run): """Values containing '=' should be preserved.""" - env_path = tmp_path / "env.txt" - env_path.write_text("KEY=value=with=equals\n", encoding="utf-8") - result = fungus_run.load_env_from_file(str(env_path)) + from fungus.config_manager import ConfigManager + + mock_cfg = MagicMock() + mock_cfg.get_envars.return_value = ["KEY=value=with=equals"] + with patch.object(ConfigManager, "__new__", return_value=mock_cfg): + result = fungus_run.load_global_env() + assert result == {"KEY": "value=with=equals"} + + def test_ignores_malformed_lines(self, tmp_path, fungus_run): + """Lines without '=' should be silently skipped.""" + from fungus.config_manager import ConfigManager + + mock_cfg = MagicMock() + mock_cfg.get_envars.return_value = ["FOO=bar", "malformed", "BAZ=qux"] + with patch.object(ConfigManager, "__new__", return_value=mock_cfg): + result = fungus_run.load_global_env() + assert result == {"FOO": "bar", "BAZ": "qux"} + + def test_strips_whitespace(self, tmp_path, fungus_run): + """Keys and values should be stripped of whitespace.""" + from fungus.config_manager import ConfigManager + + mock_cfg = MagicMock() + mock_cfg.get_envars.return_value = [" KEY = value "] + with patch.object(ConfigManager, "__new__", return_value=mock_cfg): + result = fungus_run.load_global_env() + assert result == {"KEY": "value"} + + +# --------------------------------------------------------------------------- +# Test _build_per_game_env +# --------------------------------------------------------------------------- + + +class TestBuildPerGameEnv: + def test_empty_environment(self, fungus_run): + """An empty environment list should return an empty dict.""" + fungus_run.game.environment = [] + assert fungus_run._build_per_game_env() == {} + + def test_parses_env_vars(self, fungus_run): + """Valid KEY=VALUE lines should be parsed.""" + fungus_run.game.environment = ["WINEDLLOVERRIDES=winmm=n,b", "CUSTOM=val"] + result = fungus_run._build_per_game_env() + assert result == {"WINEDLLOVERRIDES": "winmm=n,b", "CUSTOM": "val"} + + def test_ignores_malformed_lines(self, fungus_run): + """Lines without '=' should be silently skipped.""" + fungus_run.game.environment = ["FOO=bar", "malformed", "BAZ=qux"] + result = fungus_run._build_per_game_env() + assert result == {"FOO": "bar", "BAZ": "qux"} + + def test_splits_on_first_equals_only(self, fungus_run): + """Values containing '=' should be preserved.""" + fungus_run.game.environment = ["KEY=value=with=equals"] + result = fungus_run._build_per_game_env() assert result == {"KEY": "value=with=equals"} - def test_sets_os_environ(self, tmp_path, fungus_run): - env_path = tmp_path / "env.txt" - env_path.write_text("TEST_VAR=hello\n", encoding="utf-8") - fungus_run.load_env_from_file(str(env_path)) - assert os.environ.get("TEST_VAR") == "hello" + def test_strips_whitespace(self, fungus_run): + """Keys and values should be stripped of whitespace.""" + fungus_run.game.environment = [" KEY = value "] + result = fungus_run._build_per_game_env() + assert result == {"KEY": "value"} + + def test_duplicate_keys_later_wins(self, fungus_run): + """If the same key appears twice, the later entry wins.""" + fungus_run.game.environment = ["FOO=bar", "FOO=baz"] + result = fungus_run._build_per_game_env() + assert result == {"FOO": "baz"} # --------------------------------------------------------------------------- @@ -325,15 +381,26 @@ class TestBuildBwrapCommand: assert bwrap_args[bind_idx + 1] == game_dir assert bwrap_args[bind_idx + 2] == game_dir - def test_env_from_file_merged(self, tmp_path, fungus_run, env_file): + def test_global_env_merged(self, fungus_run): """Environment variables from file should be in sandbox_env.""" - env_data = fungus_run.load_env_from_file(str(env_file)) + env_data = {"FOO": "bar", "BAZ": "qux"} _, sandbox_env, _ = fungus_run.build_bwrap_command( fungus_run.game, [], env_data, ) assert sandbox_env["FOO"] == "bar" assert sandbox_env["BAZ"] == "qux" + def test_per_game_env_overrides_file_env(self, fungus_run): + """Per-game env should override global env for the same key.""" + env_data = {"FOO": "bar", "BAZ": "qux"} + per_game_data = {"FOO": "override", "CUSTOM": "val"} + _, sandbox_env, _ = fungus_run.build_bwrap_command( + fungus_run.game, [], env_data, per_game_data, + ) + assert sandbox_env["FOO"] == "override" + assert sandbox_env["BAZ"] == "qux" + assert sandbox_env["CUSTOM"] == "val" + def test_ro_bind_entries_present(self, fungus_run): """Read-only system binds should be present.""" bwrap_args, _, _ = fungus_run.build_bwrap_command( |
