mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-26 00:27:26 +01:00
Remove unneeded Steam tools after an uninstall
Steamworks Common Redistributables, Steam Linux Runtime 4.0 and Proton Experimental stay in PROTECTED_APP_IDS, so no guard ever calls them an unauthorized game. uninstall_other_games now ends with a step that uninstalls them, through uninstall_game, only when all of these hold: - Steam is not running (pgrep steam.sh, as _ensure_steam_running); - config.vdf parses and has a CompatToolMapping block; - every installed non-tool appmanifest maps to proton-cachyos-native; - that tool's toolmanifest.vdf exists. Anything else keeps all three and logs "kept Steam tools: <reason>"; a running Steam logs "Steam running, deferring tool removal". No game installed counts as not needed and says so. - _tool_need.py decides. Every error keeps the tools. - _vdf_text.py is a stdlib KeyValues parser. The repo had none, and the root daemon's system python has no vdf package. - _steam_client.steam_client_running() returns None when pgrep cannot tell. _ensure_steam_running behaves as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a3c7c279a5
commit
01d750f36d
@ -57,6 +57,26 @@ def is_game_installed(app_id: int) -> bool:
|
|||||||
return manifest.exists()
|
return manifest.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def steam_client_running() -> bool | None:
|
||||||
|
"""Whether the Steam main client (``steam.sh``, not just helpers) runs.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None when pgrep is missing or fails: callers that delete on "not
|
||||||
|
running" must treat that as running.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["/usr/bin/pgrep", "-f", "steam.sh"],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
# pgrep: 0 matched, 1 matched nothing, anything else is its own error.
|
||||||
|
return {0: True, 1: False}.get(result.returncode)
|
||||||
|
|
||||||
|
|
||||||
def _ensure_steam_running() -> None:
|
def _ensure_steam_running() -> None:
|
||||||
"""Start the Steam client if it is not already running.
|
"""Start the Steam client if it is not already running.
|
||||||
|
|
||||||
@ -70,19 +90,10 @@ def _ensure_steam_running() -> None:
|
|||||||
logger.info("steam-game-installer is running — leaving Steam closed.")
|
logger.info("steam-game-installer is running — leaving Steam closed.")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Check if any steam process is running (main client, not just helpers).
|
# None (pgrep cannot tell) falls through to a start, as it always has.
|
||||||
try:
|
if steam_client_running():
|
||||||
result = subprocess.run(
|
logger.debug("Steam client already running")
|
||||||
["/usr/bin/pgrep", "-f", "steam.sh"],
|
return
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
check=False,
|
|
||||||
)
|
|
||||||
if result.returncode == 0:
|
|
||||||
logger.debug("Steam client already running")
|
|
||||||
return
|
|
||||||
except FileNotFoundError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
real_user = _get_real_user()
|
real_user = _get_real_user()
|
||||||
logger.info("Starting Steam client...")
|
logger.info("Starting Steam client...")
|
||||||
|
|||||||
130
steam_backlog_enforcer/_tool_need.py
Normal file
130
steam_backlog_enforcer/_tool_need.py
Normal file
@ -0,0 +1,130 @@
|
|||||||
|
"""Whether the three Steam tools Proton games lean on are still needed.
|
||||||
|
|
||||||
|
Steamworks Common Redistributables, Steam Linux Runtime 4.0 and Proton
|
||||||
|
Experimental stay in :data:`PROTECTED_APP_IDS`, so no sweep or guard ever
|
||||||
|
treats them as an unauthorized game. This module names the one case where they
|
||||||
|
may still go (kuhy's rule): Steam is closed, and every installed game is mapped
|
||||||
|
to ``proton-cachyos-native``, which is itself installed.
|
||||||
|
|
||||||
|
An earlier version removed Steam Linux Runtime 4.0 while a game needed it, so
|
||||||
|
every doubt (a read error, a malformed file, a missing key, an exception)
|
||||||
|
means "needed". Reads only; config.vdf holds private values, so a reason names
|
||||||
|
the file or an AppID, never a line of it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import re
|
||||||
|
from typing import TYPE_CHECKING, Final
|
||||||
|
|
||||||
|
from steam_backlog_enforcer import _steam_state
|
||||||
|
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
|
||||||
|
from steam_backlog_enforcer._protected_apps import PROTECTED_APP_IDS
|
||||||
|
from steam_backlog_enforcer._steam_client import steam_client_running
|
||||||
|
from steam_backlog_enforcer._vdf_text import VdfNode, lookup, parse_vdf
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
STEAM_TOOLS: Final = {
|
||||||
|
228980: "Steamworks Common Redistributables",
|
||||||
|
4183110: "Steam Linux Runtime 4.0",
|
||||||
|
1493710: "Proton Experimental",
|
||||||
|
}
|
||||||
|
NATIVE_TOOL: Final = "proton-cachyos-native"
|
||||||
|
_MAPPING: Final = ("InstallConfigStore", "Software", "Valve", "Steam")
|
||||||
|
_MANIFEST: Final = re.compile(r"appmanifest_\d+\.acf")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ToolNeed:
|
||||||
|
"""The verdict and its one-line reason; ``deferred`` means Steam runs."""
|
||||||
|
|
||||||
|
needed: bool
|
||||||
|
reason: str
|
||||||
|
deferred: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
def _keep(reason: str) -> ToolNeed:
|
||||||
|
return ToolNeed(needed=True, reason=reason)
|
||||||
|
|
||||||
|
|
||||||
|
def _compat_mapping(steam_root: Path) -> dict[str, VdfNode] | ToolNeed:
|
||||||
|
"""config.vdf's CompatToolMapping block, or the reason to keep the tools."""
|
||||||
|
try:
|
||||||
|
text = (steam_root / "config" / "config.vdf").read_text(encoding="utf-8")
|
||||||
|
except OSError, UnicodeDecodeError:
|
||||||
|
return _keep("config.vdf unreadable")
|
||||||
|
try:
|
||||||
|
tree = parse_vdf(text)
|
||||||
|
except ValueError:
|
||||||
|
return _keep("config.vdf malformed")
|
||||||
|
mapping = lookup(tree, *_MAPPING, "CompatToolMapping")
|
||||||
|
if not isinstance(mapping, dict):
|
||||||
|
return _keep("config.vdf has no CompatToolMapping")
|
||||||
|
return mapping
|
||||||
|
|
||||||
|
|
||||||
|
def _unmapped(steamapps: Path, mapping: dict[str, VdfNode]) -> ToolNeed | int:
|
||||||
|
"""The reason to keep the tools, or how many installed games are mapped."""
|
||||||
|
games = 0
|
||||||
|
# iterdir, not glob: glob reads an unlistable directory as empty, which
|
||||||
|
# would read as "no game installed".
|
||||||
|
for manifest in sorted(steamapps.iterdir()):
|
||||||
|
if not _MANIFEST.fullmatch(manifest.name):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
tree = parse_vdf(manifest.read_text(encoding="utf-8"))
|
||||||
|
except OSError, ValueError:
|
||||||
|
return _keep(f"{manifest.name} unreadable")
|
||||||
|
app_id = lookup(tree, "AppState", "appid")
|
||||||
|
if not isinstance(app_id, str) or not app_id.isdigit():
|
||||||
|
return _keep(f"{manifest.name} has no appid")
|
||||||
|
if int(app_id) in PROTECTED_APP_IDS:
|
||||||
|
continue
|
||||||
|
if lookup(mapping, app_id, "name") != NATIVE_TOOL:
|
||||||
|
return _keep(f"AppID={app_id} has no {NATIVE_TOOL} mapping")
|
||||||
|
games += 1
|
||||||
|
return games
|
||||||
|
|
||||||
|
|
||||||
|
def _decide(steamapps: Path) -> ToolNeed:
|
||||||
|
running = steam_client_running()
|
||||||
|
if running is None:
|
||||||
|
return _keep("cannot tell whether Steam runs")
|
||||||
|
if running:
|
||||||
|
return ToolNeed(needed=True, reason="Steam running", deferred=True)
|
||||||
|
steam_root = steamapps.parent
|
||||||
|
mapping = _compat_mapping(steam_root)
|
||||||
|
if isinstance(mapping, ToolNeed):
|
||||||
|
return mapping
|
||||||
|
games = _unmapped(steamapps, mapping)
|
||||||
|
if isinstance(games, ToolNeed):
|
||||||
|
return games
|
||||||
|
toolmanifest = steam_root / "compatibilitytools.d" / NATIVE_TOOL
|
||||||
|
if not (toolmanifest / "toolmanifest.vdf").is_file():
|
||||||
|
return _keep(f"{NATIVE_TOOL} toolmanifest.vdf missing")
|
||||||
|
# No game installed means no game needs them; the reason says so in the log.
|
||||||
|
reason = (
|
||||||
|
f"every installed game runs on {NATIVE_TOOL}" if games else "no game installed"
|
||||||
|
)
|
||||||
|
return ToolNeed(needed=False, reason=reason)
|
||||||
|
|
||||||
|
|
||||||
|
def tool_need(steamapps: Path | None = None) -> ToolNeed:
|
||||||
|
"""Decide whether :data:`STEAM_TOOLS` must stay installed.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
steamapps: The library to judge; defaults to the canonical
|
||||||
|
``_steam_state.STEAMAPPS_PATH`` (read at call time, so a test
|
||||||
|
fixture's redirect holds). Its parent is the Steam root.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``needed=False`` only when every condition holds; anything else,
|
||||||
|
including an exception, keeps them.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return _decide(_steam_state.STEAMAPPS_PATH if steamapps is None else steamapps)
|
||||||
|
except FAIL_SAFE_ERRORS as exc:
|
||||||
|
return _keep(f"check failed ({type(exc).__name__})")
|
||||||
88
steam_backlog_enforcer/_vdf_text.py
Normal file
88
steam_backlog_enforcer/_vdf_text.py
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
"""A read-only parser for Valve's KeyValues text (``config.vdf``, ``*.acf``).
|
||||||
|
|
||||||
|
Stdlib only: the root daemon runs on the system interpreter, which carries no
|
||||||
|
``vdf`` package, and an import that failed there would quietly turn every
|
||||||
|
decision built on it into "keep". Malformed input raises ``ValueError`` rather
|
||||||
|
than returning part of a tree, so a caller deciding something destructive can
|
||||||
|
fail closed. Error messages carry an offset, never file content: config.vdf
|
||||||
|
holds private values.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
type VdfNode = dict[str, VdfNode] | str
|
||||||
|
|
||||||
|
# One token per match: whitespace, a // comment, a quoted string (group 1), a
|
||||||
|
# brace (group 2), a [$PLATFORM] conditional, or a bare word (group 3).
|
||||||
|
_TOKEN: Final = re.compile(
|
||||||
|
r'\s+|//[^\n]*|"((?:[^"\\]|\\.)*)"|([{}])|\[[^\]\n]*\]|([^\s"{}\[]+)',
|
||||||
|
re.DOTALL,
|
||||||
|
)
|
||||||
|
_ESCAPES: Final = {"n": "\n", "t": "\t", "\\": "\\", '"': '"'}
|
||||||
|
_ESCAPE: Final = re.compile(r"\\(.)", re.DOTALL)
|
||||||
|
|
||||||
|
|
||||||
|
def _malformed(offset: int) -> ValueError:
|
||||||
|
return ValueError(f"malformed KeyValues at offset {offset}")
|
||||||
|
|
||||||
|
|
||||||
|
def _unescape(raw: str) -> str:
|
||||||
|
return _ESCAPE.sub(lambda m: _ESCAPES.get(m.group(1), m.group(0)), raw)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_vdf(text: str) -> dict[str, VdfNode]:
|
||||||
|
"""Parse KeyValues *text* into nested dicts (a repeated key: last wins).
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: on any unterminated string, stray or missing brace, or a
|
||||||
|
key with no value.
|
||||||
|
"""
|
||||||
|
root: dict[str, VdfNode] = {}
|
||||||
|
stack = [root]
|
||||||
|
key: str | None = None
|
||||||
|
pos = 0
|
||||||
|
while pos < len(text):
|
||||||
|
match = _TOKEN.match(text, pos)
|
||||||
|
if match is None:
|
||||||
|
raise _malformed(pos)
|
||||||
|
quoted, brace, bare = match.groups()
|
||||||
|
if brace == "{":
|
||||||
|
if key is None:
|
||||||
|
raise _malformed(pos)
|
||||||
|
child: dict[str, VdfNode] = {}
|
||||||
|
stack[-1][key] = child
|
||||||
|
stack.append(child)
|
||||||
|
key = None
|
||||||
|
elif brace == "}":
|
||||||
|
if key is not None or len(stack) == 1:
|
||||||
|
raise _malformed(pos)
|
||||||
|
stack.pop()
|
||||||
|
elif quoted is not None or bare is not None:
|
||||||
|
word = _unescape(quoted) if quoted is not None else str(bare)
|
||||||
|
if key is None:
|
||||||
|
key = word
|
||||||
|
else:
|
||||||
|
stack[-1][key] = word
|
||||||
|
key = None
|
||||||
|
pos = match.end()
|
||||||
|
if key is not None or len(stack) != 1:
|
||||||
|
raise _malformed(pos)
|
||||||
|
return root
|
||||||
|
|
||||||
|
|
||||||
|
def lookup(node: VdfNode | None, *keys: str) -> VdfNode | None:
|
||||||
|
"""Walk *keys* down from *node*, matching each one case-insensitively.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The node found, or None when a key is missing or the path runs
|
||||||
|
through a plain string.
|
||||||
|
"""
|
||||||
|
for key in keys:
|
||||||
|
if not isinstance(node, dict):
|
||||||
|
return None
|
||||||
|
wanted = key.casefold()
|
||||||
|
node = next((v for k, v in node.items() if k.casefold() == wanted), None)
|
||||||
|
return node
|
||||||
@ -13,12 +13,14 @@ import re
|
|||||||
import shutil
|
import shutil
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from steam_backlog_enforcer import _steam_state
|
||||||
from steam_backlog_enforcer._achievement_skip import zero_achievement_ids
|
from steam_backlog_enforcer._achievement_skip import zero_achievement_ids
|
||||||
from steam_backlog_enforcer._game_names import _is_protected_name
|
from steam_backlog_enforcer._game_names import _is_protected_name
|
||||||
from steam_backlog_enforcer._progress import tracked
|
from steam_backlog_enforcer._progress import tracked
|
||||||
from steam_backlog_enforcer._protected_apps import PROTECTED_APP_IDS
|
from steam_backlog_enforcer._protected_apps import PROTECTED_APP_IDS
|
||||||
from steam_backlog_enforcer._research_game import kept_ids
|
from steam_backlog_enforcer._research_game import kept_ids
|
||||||
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH, _assert_not_real_steam
|
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH, _assert_not_real_steam
|
||||||
|
from steam_backlog_enforcer._tool_need import STEAM_TOOLS, tool_need
|
||||||
from steam_backlog_enforcer._whitelist_locking import get_approved_exception_ids
|
from steam_backlog_enforcer._whitelist_locking import get_approved_exception_ids
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -174,9 +176,34 @@ def uninstall_other_games(allowed_app_ids: set[int]) -> int:
|
|||||||
if uninstall_game(app_id, name):
|
if uninstall_game(app_id, name):
|
||||||
count += 1
|
count += 1
|
||||||
|
|
||||||
|
# After the games: what is left installed decides whether the tools stay.
|
||||||
|
remove_unneeded_tools()
|
||||||
return count
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def remove_unneeded_tools() -> int:
|
||||||
|
"""Uninstall :data:`STEAM_TOOLS` when :func:`tool_need` says nothing needs them.
|
||||||
|
|
||||||
|
Silent when none of them is installed; otherwise one line says what was
|
||||||
|
decided and why. Returns how many were removed.
|
||||||
|
"""
|
||||||
|
# The canonical binding, read now: the test suite redirects it for every
|
||||||
|
# test, so no test can reach a live Steam root through this step.
|
||||||
|
steamapps = _steam_state.STEAMAPPS_PATH
|
||||||
|
present = [a for a in STEAM_TOOLS if (steamapps / f"appmanifest_{a}.acf").exists()]
|
||||||
|
if not present:
|
||||||
|
return 0
|
||||||
|
need = tool_need(steamapps)
|
||||||
|
if need.deferred:
|
||||||
|
logger.info("Steam running, deferring tool removal")
|
||||||
|
return 0
|
||||||
|
if need.needed:
|
||||||
|
logger.info("kept Steam tools: %s", need.reason)
|
||||||
|
return 0
|
||||||
|
logger.info("removing Steam tools: %s", need.reason)
|
||||||
|
return sum(uninstall_game(app_id, STEAM_TOOLS[app_id]) for app_id in present)
|
||||||
|
|
||||||
|
|
||||||
def is_infrastructure_app(app_id: int) -> bool:
|
def is_infrastructure_app(app_id: int) -> bool:
|
||||||
"""Return True if *app_id* is a Steam runtime or compatibility tool.
|
"""Return True if *app_id* is a Steam runtime or compatibility tool.
|
||||||
|
|
||||||
|
|||||||
73
steam_backlog_enforcer/tests/_tool_home.py
Normal file
73
steam_backlog_enforcer/tests/_tool_home.py
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
"""Fixture Steam homes for the Steam-tool removal tests.
|
||||||
|
|
||||||
|
Builds ``<root>/steamapps``, ``<root>/config/config.vdf`` and
|
||||||
|
``<root>/compatibilitytools.d`` under a tmp dir, never the real Steam root.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._tool_need import NATIVE_TOOL, STEAM_TOOLS
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def acf(app_id: int, name: str) -> str:
|
||||||
|
"""A minimal fully-installed appmanifest."""
|
||||||
|
return (
|
||||||
|
f'"AppState"\n{{\n\t"appid"\t\t"{app_id}"\n\t"name"\t\t"{name}"\n'
|
||||||
|
f'\t"installdir"\t\t"dir{app_id}"\n\t"StateFlags"\t\t"4"\n}}\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def config_vdf(mapping: dict[int, str]) -> str:
|
||||||
|
"""A config.vdf with Steam's real nesting (and its lowercase ``valve``)."""
|
||||||
|
entries = "".join(
|
||||||
|
f'\t\t\t\t\t"{app_id}"\n\t\t\t\t\t{{\n\t\t\t\t\t\t"name"\t\t"{tool}"\n'
|
||||||
|
f'\t\t\t\t\t\t"config"\t\t""\n\t\t\t\t\t\t"priority"\t\t"250"\n'
|
||||||
|
"\t\t\t\t\t}\n"
|
||||||
|
for app_id, tool in mapping.items()
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
'"InstallConfigStore"\n{\n\t"Software"\n\t{\n\t\t"valve"\n\t\t{\n'
|
||||||
|
'\t\t\t"Steam"\n\t\t\t{\n\t\t\t\t"CompatToolMapping"\n\t\t\t\t{\n'
|
||||||
|
'\t\t\t\t\t"0"\n\t\t\t\t\t{\n\t\t\t\t\t\t"name"\t\t"proton_experimental"\n'
|
||||||
|
f"\t\t\t\t\t}}\n{entries}\t\t\t\t}}\n\t\t\t}}\n\t\t}}\n\t}}\n}}\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def make_home(
|
||||||
|
root: Path,
|
||||||
|
games: dict[int, str | None],
|
||||||
|
*,
|
||||||
|
tools: bool = True,
|
||||||
|
toolmanifest: bool = True,
|
||||||
|
) -> Path:
|
||||||
|
"""Write a fixture Steam root; return its ``steamapps``.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
root: Directory to become the Steam root.
|
||||||
|
games: Installed game app id -> its CompatToolMapping tool name, or
|
||||||
|
None for a game with no mapping entry.
|
||||||
|
tools: Install the three Steam tools (manifest + files).
|
||||||
|
toolmanifest: Install proton-cachyos-native's toolmanifest.vdf.
|
||||||
|
"""
|
||||||
|
steamapps = root / "steamapps"
|
||||||
|
(steamapps / "common").mkdir(parents=True)
|
||||||
|
installed = {app_id: f"Game {app_id}" for app_id in games}
|
||||||
|
if tools:
|
||||||
|
installed |= STEAM_TOOLS
|
||||||
|
for app_id, name in installed.items():
|
||||||
|
(steamapps / f"appmanifest_{app_id}.acf").write_text(acf(app_id, name))
|
||||||
|
(steamapps / "common" / f"dir{app_id}").mkdir()
|
||||||
|
(steamapps / "common" / f"dir{app_id}" / "file.bin").write_text("x")
|
||||||
|
(root / "config").mkdir()
|
||||||
|
mapping = {app_id: tool for app_id, tool in games.items() if tool}
|
||||||
|
(root / "config" / "config.vdf").write_text(config_vdf(mapping))
|
||||||
|
if toolmanifest:
|
||||||
|
tool_dir = root / "compatibilitytools.d" / NATIVE_TOOL
|
||||||
|
tool_dir.mkdir(parents=True)
|
||||||
|
(tool_dir / "toolmanifest.vdf").write_text('"manifest"\n{\n}\n')
|
||||||
|
return steamapps
|
||||||
125
steam_backlog_enforcer/tests/test_game_uninstall_tools.py
Normal file
125
steam_backlog_enforcer/tests/test_game_uninstall_tools.py
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
"""The uninstall path's Steam-tool step, on fixture homes."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._tool_need import NATIVE_TOOL, STEAM_TOOLS
|
||||||
|
from steam_backlog_enforcer.game_uninstall import (
|
||||||
|
remove_unneeded_tools,
|
||||||
|
uninstall_other_games,
|
||||||
|
)
|
||||||
|
from steam_backlog_enforcer.tests._tool_home import make_home
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PKG = "steam_backlog_enforcer.game_uninstall"
|
||||||
|
RUNNING = "steam_backlog_enforcer._tool_need.steam_client_running"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(name="home")
|
||||||
|
def fixture_home(tmp_path: Path) -> Iterator[Path]:
|
||||||
|
"""Point both steamapps bindings at a fixture Steam root."""
|
||||||
|
steamapps = tmp_path / "Steam" / "steamapps"
|
||||||
|
with (
|
||||||
|
patch("steam_backlog_enforcer._steam_state.STEAMAPPS_PATH", steamapps),
|
||||||
|
patch(f"{PKG}.STEAMAPPS_PATH", steamapps),
|
||||||
|
patch(RUNNING, return_value=False),
|
||||||
|
):
|
||||||
|
yield tmp_path / "Steam"
|
||||||
|
|
||||||
|
|
||||||
|
def _tools_left(steamapps: Path) -> set[int]:
|
||||||
|
return {
|
||||||
|
app_id
|
||||||
|
for app_id in STEAM_TOOLS
|
||||||
|
if (steamapps / f"appmanifest_{app_id}.acf").exists()
|
||||||
|
or (steamapps / "common" / f"dir{app_id}").exists()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _messages(caplog: pytest.LogCaptureFixture) -> list[str]:
|
||||||
|
return [r.getMessage() for r in caplog.records if r.name == PKG]
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapped_games_remove_the_tools(
|
||||||
|
home: Path, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""All mapped: the three tools go, the game stays, one line says why."""
|
||||||
|
steamapps = make_home(home, {10: NATIVE_TOOL})
|
||||||
|
with caplog.at_level(logging.INFO, logger=PKG):
|
||||||
|
assert remove_unneeded_tools() == 3
|
||||||
|
assert _tools_left(steamapps) == set()
|
||||||
|
assert (steamapps / "appmanifest_10.acf").exists()
|
||||||
|
messages = _messages(caplog)
|
||||||
|
assert messages[0] == (
|
||||||
|
f"removing Steam tools: every installed game runs on {NATIVE_TOOL}"
|
||||||
|
)
|
||||||
|
assert "Removed manifest for Steam Linux Runtime 4.0 (AppID=4183110)" in messages
|
||||||
|
|
||||||
|
|
||||||
|
def test_unmapped_game_keeps_the_tools(
|
||||||
|
home: Path, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""An unmapped game keeps them with one line naming it."""
|
||||||
|
steamapps = make_home(home, {10: NATIVE_TOOL, 20: None})
|
||||||
|
with caplog.at_level(logging.INFO, logger=PKG):
|
||||||
|
assert remove_unneeded_tools() == 0
|
||||||
|
assert _tools_left(steamapps) == set(STEAM_TOOLS)
|
||||||
|
assert _messages(caplog) == [
|
||||||
|
f"kept Steam tools: AppID=20 has no {NATIVE_TOOL} mapping"
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_steam_running_defers(home: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||||
|
"""A running Steam defers the decision."""
|
||||||
|
steamapps = make_home(home, {10: NATIVE_TOOL})
|
||||||
|
with caplog.at_level(logging.INFO, logger=PKG), patch(RUNNING, return_value=True):
|
||||||
|
assert remove_unneeded_tools() == 0
|
||||||
|
assert _tools_left(steamapps) == set(STEAM_TOOLS)
|
||||||
|
assert _messages(caplog) == ["Steam running, deferring tool removal"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unreadable_config_keeps_and_says_why(
|
||||||
|
home: Path, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""C22: config.vdf unreadable -> tools kept, one line naming the reason."""
|
||||||
|
steamapps = make_home(home, {10: NATIVE_TOOL})
|
||||||
|
config = home / "config" / "config.vdf"
|
||||||
|
config.unlink()
|
||||||
|
config.mkdir()
|
||||||
|
with caplog.at_level(logging.INFO, logger=PKG):
|
||||||
|
assert remove_unneeded_tools() == 0
|
||||||
|
assert _tools_left(steamapps) == set(STEAM_TOOLS)
|
||||||
|
assert _messages(caplog) == ["kept Steam tools: config.vdf unreadable"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_tools_installed_is_silent(
|
||||||
|
home: Path, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""No tool installed: no decision, no log line."""
|
||||||
|
make_home(home, {10: None}, tools=False)
|
||||||
|
with (
|
||||||
|
caplog.at_level(logging.INFO, logger=PKG),
|
||||||
|
patch(f"{PKG}.tool_need") as need,
|
||||||
|
):
|
||||||
|
assert remove_unneeded_tools() == 0
|
||||||
|
need.assert_not_called()
|
||||||
|
assert _messages(caplog) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_uninstall_sweep_runs_the_step_after_removing_games(home: Path) -> None:
|
||||||
|
"""The sweep removes the unmapped game first, then the now-unneeded tools.
|
||||||
|
|
||||||
|
The game count it returns still counts games only.
|
||||||
|
"""
|
||||||
|
steamapps = make_home(home, {10: NATIVE_TOOL, 20: None})
|
||||||
|
assert uninstall_other_games({10}) == 1
|
||||||
|
assert not (steamapps / "appmanifest_20.acf").exists()
|
||||||
|
assert _tools_left(steamapps) == set()
|
||||||
26
steam_backlog_enforcer/tests/test_steam_client_running.py
Normal file
26
steam_backlog_enforcer/tests/test_steam_client_running.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
"""Tests for steam_client_running: yes, no, or cannot tell."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._steam_client import steam_client_running
|
||||||
|
|
||||||
|
RUN = "steam_backlog_enforcer._steam_client.subprocess.run"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("returncode", "expected"), [(0, True), (1, False), (2, None), (3, None)]
|
||||||
|
)
|
||||||
|
def test_pgrep_exit_code(returncode: int, *, expected: bool | None) -> None:
|
||||||
|
"""0 is running, 1 is not, anything else cannot tell."""
|
||||||
|
with patch(RUN, return_value=MagicMock(returncode=returncode)):
|
||||||
|
assert steam_client_running() is expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_pgrep_cannot_tell() -> None:
|
||||||
|
"""A missing pgrep cannot tell."""
|
||||||
|
with patch(RUN, side_effect=FileNotFoundError):
|
||||||
|
assert steam_client_running() is None
|
||||||
159
steam_backlog_enforcer/tests/test_tool_need.py
Normal file
159
steam_backlog_enforcer/tests/test_tool_need.py
Normal file
@ -0,0 +1,159 @@
|
|||||||
|
"""Tests for _tool_need: when the three Steam tools may go, on fixture homes."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._tool_need import NATIVE_TOOL, ToolNeed, tool_need
|
||||||
|
from steam_backlog_enforcer.tests._tool_home import make_home
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PKG = "steam_backlog_enforcer._tool_need"
|
||||||
|
KEEP_UNMAPPED = ToolNeed(needed=True, reason=f"AppID=20 has no {NATIVE_TOOL} mapping")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(name="root")
|
||||||
|
def fixture_root(tmp_path: Path) -> Path:
|
||||||
|
"""A fixture Steam root (conftest already owns tmp_path/steamapps)."""
|
||||||
|
return tmp_path / "Steam"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _steam_closed() -> Iterator[None]:
|
||||||
|
"""Steam is closed unless a test says otherwise: never ask the live pgrep."""
|
||||||
|
with patch(f"{PKG}.steam_client_running", return_value=False):
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def test_all_mapped_means_not_needed(root: Path) -> None:
|
||||||
|
"""Every game on proton-cachyos-native: the tools may go."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL, 20: NATIVE_TOOL})
|
||||||
|
assert tool_need(steamapps) == ToolNeed(
|
||||||
|
needed=False, reason=f"every installed game runs on {NATIVE_TOOL}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_one_unmapped_game_keeps(root: Path) -> None:
|
||||||
|
"""One game with no mapping entry keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL, 20: None})
|
||||||
|
assert tool_need(steamapps) == KEEP_UNMAPPED
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapping_naming_another_tool_keeps(root: Path) -> None:
|
||||||
|
"""A game mapped to another tool keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL, 20: "proton_experimental"})
|
||||||
|
assert tool_need(steamapps) == KEEP_UNMAPPED
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapping_entry_that_is_not_a_block_keeps(root: Path) -> None:
|
||||||
|
"""A mapping entry with no name block keeps them."""
|
||||||
|
steamapps = make_home(root, {20: NATIVE_TOOL})
|
||||||
|
config = root / "config" / "config.vdf"
|
||||||
|
config.write_text(
|
||||||
|
'"InstallConfigStore" { "Software" { "Valve" { "Steam" {'
|
||||||
|
' "CompatToolMapping" { "20" "proton-cachyos-native" } } } } }'
|
||||||
|
)
|
||||||
|
assert tool_need(steamapps) == KEEP_UNMAPPED
|
||||||
|
|
||||||
|
|
||||||
|
def test_steam_running_defers(root: Path) -> None:
|
||||||
|
"""A running Steam defers the decision."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
with patch(f"{PKG}.steam_client_running", return_value=True):
|
||||||
|
need = tool_need(steamapps)
|
||||||
|
assert need == ToolNeed(needed=True, reason="Steam running", deferred=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_steam_state_keeps(root: Path) -> None:
|
||||||
|
"""pgrep that cannot tell keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
with patch(f"{PKG}.steam_client_running", return_value=None):
|
||||||
|
need = tool_need(steamapps)
|
||||||
|
assert need == ToolNeed(needed=True, reason="cannot tell whether Steam runs")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("damage", ["directory", "binary", "missing"])
|
||||||
|
def test_unreadable_config_keeps(root: Path, damage: str) -> None:
|
||||||
|
"""C22: an unreadable config.vdf keeps the tools and says why."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
config = root / "config" / "config.vdf"
|
||||||
|
config.unlink()
|
||||||
|
if damage == "directory":
|
||||||
|
config.mkdir()
|
||||||
|
elif damage == "binary":
|
||||||
|
config.write_bytes(b'"InstallConfigStore" { "\xff\xfe" }')
|
||||||
|
assert tool_need(steamapps) == ToolNeed(needed=True, reason="config.vdf unreadable")
|
||||||
|
|
||||||
|
|
||||||
|
def test_malformed_config_keeps(root: Path) -> None:
|
||||||
|
"""A config.vdf that does not parse keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
(root / "config" / "config.vdf").write_text('"InstallConfigStore" { "a"')
|
||||||
|
assert tool_need(steamapps) == ToolNeed(needed=True, reason="config.vdf malformed")
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_without_mapping_keeps(root: Path) -> None:
|
||||||
|
"""A config.vdf with no CompatToolMapping keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
(root / "config" / "config.vdf").write_text(
|
||||||
|
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { "x" "1" } } } }'
|
||||||
|
)
|
||||||
|
assert tool_need(steamapps) == ToolNeed(
|
||||||
|
needed=True, reason="config.vdf has no CompatToolMapping"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_toolmanifest_keeps(root: Path) -> None:
|
||||||
|
"""No proton-cachyos-native toolmanifest.vdf keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL}, toolmanifest=False)
|
||||||
|
assert tool_need(steamapps) == ToolNeed(
|
||||||
|
needed=True, reason=f"{NATIVE_TOOL} toolmanifest.vdf missing"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_game_installed_is_not_needed(root: Path) -> None:
|
||||||
|
"""No game installed: no game needs them."""
|
||||||
|
steamapps = make_home(root, {})
|
||||||
|
assert tool_need(steamapps) == ToolNeed(needed=False, reason="no game installed")
|
||||||
|
|
||||||
|
|
||||||
|
def test_unreadable_manifest_keeps(root: Path) -> None:
|
||||||
|
"""An unreadable appmanifest keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
(steamapps / "appmanifest_30.acf").mkdir()
|
||||||
|
assert tool_need(steamapps) == ToolNeed(
|
||||||
|
needed=True, reason="appmanifest_30.acf unreadable"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_manifest_without_appid_keeps(root: Path) -> None:
|
||||||
|
"""An appmanifest with no appid keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
(steamapps / "appmanifest_30.acf").write_text('"AppState" { "name" "x" }')
|
||||||
|
assert tool_need(steamapps) == ToolNeed(
|
||||||
|
needed=True, reason="appmanifest_30.acf has no appid"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unlistable_steamapps_keeps(root: Path) -> None:
|
||||||
|
"""A steamapps that cannot be listed keeps them."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
shutil.rmtree(steamapps)
|
||||||
|
steamapps.write_text("not a directory")
|
||||||
|
assert tool_need(steamapps) == ToolNeed(
|
||||||
|
needed=True, reason="check failed (NotADirectoryError)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_defaults_to_the_canonical_steamapps(root: Path) -> None:
|
||||||
|
"""With no argument it judges _steam_state.STEAMAPPS_PATH."""
|
||||||
|
steamapps = make_home(root, {10: NATIVE_TOOL})
|
||||||
|
with patch("steam_backlog_enforcer._steam_state.STEAMAPPS_PATH", steamapps):
|
||||||
|
assert not tool_need().needed
|
||||||
61
steam_backlog_enforcer/tests/test_vdf_text.py
Normal file
61
steam_backlog_enforcer/tests/test_vdf_text.py
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
"""Tests for the stdlib KeyValues (``.vdf`` / ``.acf``) parser."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._vdf_text import lookup, parse_vdf
|
||||||
|
|
||||||
|
TREE = {"Outer": {"Inner": {"leaf": "v"}, "flat": "s"}}
|
||||||
|
|
||||||
|
|
||||||
|
class TestParse:
|
||||||
|
"""parse_vdf builds the whole tree or raises."""
|
||||||
|
|
||||||
|
def test_nested_blocks(self) -> None:
|
||||||
|
"""Blocks nest and empty strings survive."""
|
||||||
|
text = '"A"\n{\n\t"b"\t\t"1"\n\t"C"\n\t{\n\t\t"d"\t""\n\t}\n}\n'
|
||||||
|
assert parse_vdf(text) == {"A": {"b": "1", "C": {"d": ""}}}
|
||||||
|
|
||||||
|
def test_escapes_comments_conditionals_and_bare_tokens(self) -> None:
|
||||||
|
"""Escapes, comments, conditionals and bare words parse."""
|
||||||
|
text = (
|
||||||
|
"// header comment\n"
|
||||||
|
'"root" {\n'
|
||||||
|
' "path" "C:\\\\Games\\"x\\"\\n\\t" [$WIN32]\n'
|
||||||
|
" bare word // trailing\n"
|
||||||
|
"}\n"
|
||||||
|
)
|
||||||
|
assert parse_vdf(text) == {"root": {"path": 'C:\\Games"x"\n\t', "bare": "word"}}
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"text",
|
||||||
|
[
|
||||||
|
'"a" "unterminated',
|
||||||
|
'"a" "1" }',
|
||||||
|
'"a" { "b" "1"',
|
||||||
|
'{ "b" "1" }',
|
||||||
|
'"a" { "b" }',
|
||||||
|
'"dangling"',
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_malformed_raises(self, text: str) -> None:
|
||||||
|
"""Every malformed shape raises instead of returning part of a tree."""
|
||||||
|
with pytest.raises(ValueError, match="malformed KeyValues"):
|
||||||
|
parse_vdf(text)
|
||||||
|
|
||||||
|
|
||||||
|
class TestLookup:
|
||||||
|
"""lookup walks keys case-insensitively."""
|
||||||
|
|
||||||
|
def test_case_insensitive_path(self) -> None:
|
||||||
|
"""Keys match regardless of case."""
|
||||||
|
assert lookup(TREE, "outer", "INNER", "Leaf") == "v"
|
||||||
|
|
||||||
|
def test_missing_key(self) -> None:
|
||||||
|
"""A missing key returns None."""
|
||||||
|
assert lookup(TREE, "outer", "nope") is None
|
||||||
|
|
||||||
|
def test_through_a_string(self) -> None:
|
||||||
|
"""A path through a plain string returns None."""
|
||||||
|
assert lookup(TREE, "outer", "flat", "deeper") is None
|
||||||
Loading…
Reference in New Issue
Block a user