mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-22 23:22:18 +01:00
Install by target, dry run and Valve Proton
The install job takes optional target (AppID, URL or name), dry_run and valve_proton params. The target is resolved inside the games allowed today (allowed_games plus approved exceptions) and refused otherwise; the installer only gets the checked --appid. Dry run runs the installer's --dry-run alone, so it is safe while a game runs. The no-target picker now offers not-installed approved exceptions too. Todo: 6ee260a4 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWZCxnNWLtpVwFLVk9w
This commit is contained in:
parent
56aa1a3898
commit
c9ae0bf0b1
@ -186,6 +186,9 @@ with explicit params, a `Progress` reporter and a `Prompter`.
|
|||||||
its text search for the same step.
|
its text search for the same step.
|
||||||
- `result` — `{ok, summary, data?}` exactly once at the end.
|
- `result` — `{ok, summary, data?}` exactly once at the end.
|
||||||
|
|
||||||
|
`install`'s target, dry run, Valve-Proton switch and result data: see
|
||||||
|
[DOCS-web-install.md](DOCS-web-install.md).
|
||||||
|
|
||||||
## Friction (server/daemon-enforced)
|
## Friction (server/daemon-enforced)
|
||||||
|
|
||||||
| Command | Phrase (exact) | Extra |
|
| Command | Phrase (exact) | Extra |
|
||||||
|
|||||||
29
DOCS-web-install.md
Normal file
29
DOCS-web-install.md
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
# `install` job params and result
|
||||||
|
|
||||||
|
Part of the web control API ([DOCS-web-control-api.md](DOCS-web-control-api.md));
|
||||||
|
the TS mirror of the result is `InstallResultData` in `web/src/api/contract.ts`.
|
||||||
|
|
||||||
|
All three params are optional (`_command_params.PARAMS["install"]`):
|
||||||
|
|
||||||
|
- `target` (string): an AppID, a Steam URL (`…/app/<id>/…`) or a name, as
|
||||||
|
the installer's own `TARGET` argument. The job resolves it, never the
|
||||||
|
installer: inside the games allowed today, which are `allowed_games(state)`
|
||||||
|
plus the approved exceptions (named from the owned records). AppIDs and URLs
|
||||||
|
are parsed locally; names match exact title first, then substring (case
|
||||||
|
ignored), with no Steam search. Several matches → a `choice` prompt; no
|
||||||
|
match, or an id outside that set → the job fails (`locked`) and no
|
||||||
|
installer runs. The installer only ever gets the checked `--appid`.
|
||||||
|
Without `target`, the job offers every allowed game not yet fully
|
||||||
|
installed, approved exceptions included (`choice` when more than one).
|
||||||
|
- `dry_run` (bool): runs only `steam_installer.cli --appid <id> --dry-run`
|
||||||
|
and relays its report as `log` lines. No manifest is queued, Steam is not
|
||||||
|
closed, there is no `steam://` fallback, so it is allowed while a game runs.
|
||||||
|
An installer failure fails the job (`op_failed`).
|
||||||
|
- `valve_proton` (bool): passes `--valve-proton` to the installer.
|
||||||
|
|
||||||
|
The result `data` is `InstallResultData` `{app_id, dry_run,
|
||||||
|
fast_install_skipped}` once a game was chosen (else the assignment). The
|
||||||
|
installer closes Steam, so a real install while a game runs skips the fast
|
||||||
|
path (`_fast_install._refusal`) and Steam's own download starts:
|
||||||
|
`fast_install_skipped` is then `"game_running"`, and the UI paints the
|
||||||
|
`result.game-running` mark on the result (`result.dry-run` for a dry run).
|
||||||
@ -65,6 +65,32 @@ PARAMS: Final[dict[str, tuple[ParamSpec, ...]]] = {
|
|||||||
help="Leave unchecked to keep playing them alongside the new pick.",
|
help="Leave unchecked to keep playing them alongside the new pick.",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
# No target: the picker over every allowed game not yet installed.
|
||||||
|
"install": (
|
||||||
|
ParamSpec(
|
||||||
|
"target",
|
||||||
|
"AppID, Steam URL or name",
|
||||||
|
"string",
|
||||||
|
required=False,
|
||||||
|
help="Only games allowed today; an ambiguous name asks.",
|
||||||
|
),
|
||||||
|
ParamSpec(
|
||||||
|
"dry_run",
|
||||||
|
"Dry run",
|
||||||
|
"bool",
|
||||||
|
required=False,
|
||||||
|
default=0,
|
||||||
|
help="Shows what the installer would do and changes nothing.",
|
||||||
|
),
|
||||||
|
ParamSpec(
|
||||||
|
"valve_proton",
|
||||||
|
"Valve Proton",
|
||||||
|
"bool",
|
||||||
|
required=False,
|
||||||
|
default=0,
|
||||||
|
help="Keep the game on Valve's default Proton.",
|
||||||
|
),
|
||||||
|
),
|
||||||
"pick-manual": (_APP_ID,),
|
"pick-manual": (_APP_ID,),
|
||||||
"abandon-pick": (_APP_ID,),
|
"abandon-pick": (_APP_ID,),
|
||||||
"add-exception": (
|
"add-exception": (
|
||||||
|
|||||||
@ -189,7 +189,11 @@ def _wait_detached(app_id: int, label: str) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def fast_install(
|
def fast_install(
|
||||||
app_id: int, label: str, prepare: Callable[[], object] = lambda: None
|
app_id: int,
|
||||||
|
label: str,
|
||||||
|
prepare: Callable[[], object] = lambda: None,
|
||||||
|
*,
|
||||||
|
valve_proton: bool = False,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""Install *app_id* with steam-game-installer.
|
"""Install *app_id* with steam-game-installer.
|
||||||
|
|
||||||
@ -213,7 +217,7 @@ def fast_install(
|
|||||||
_echo(f" Fast install of {label} skipped: {reason}.")
|
_echo(f" Fast install of {label} skipped: {reason}.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
cmd = build_cmd(installer, app_id, user)
|
cmd = build_cmd(installer, app_id, user, valve_proton=valve_proton)
|
||||||
prepare()
|
prepare()
|
||||||
if not sys.stdin.isatty():
|
if not sys.stdin.isatty():
|
||||||
_spawn_detached(cmd, app_id, label)
|
_spawn_detached(cmd, app_id, label)
|
||||||
|
|||||||
@ -51,11 +51,20 @@ def steam_account_name() -> str | None:
|
|||||||
return match.group(1) if match else None
|
return match.group(1) if match else None
|
||||||
|
|
||||||
|
|
||||||
def build_cmd(installer: Path, app_id: int, user: str | None) -> list[str]:
|
def build_cmd(
|
||||||
|
installer: Path,
|
||||||
|
app_id: int,
|
||||||
|
user: str | None,
|
||||||
|
*,
|
||||||
|
valve_proton: bool = False,
|
||||||
|
dry_run: bool = False,
|
||||||
|
) -> list[str]:
|
||||||
"""The installer invocation, dropped to the desktop user when root.
|
"""The installer invocation, dropped to the desktop user when root.
|
||||||
|
|
||||||
Launched as ``python3 -m steam_installer.cli`` with the checkout on
|
Launched as ``python3 -m steam_installer.cli`` with the checkout on
|
||||||
``PYTHONPATH``: ``sudo`` resets the environment, so it is named in the argv.
|
``PYTHONPATH``: ``sudo`` resets the environment, so it is named in the argv.
|
||||||
|
*valve_proton* keeps the game on Valve's default Proton; *dry_run* only
|
||||||
|
reports what the installer would do.
|
||||||
"""
|
"""
|
||||||
cmd = [
|
cmd = [
|
||||||
"env",
|
"env",
|
||||||
@ -69,6 +78,10 @@ def build_cmd(installer: Path, app_id: int, user: str | None) -> list[str]:
|
|||||||
"--language",
|
"--language",
|
||||||
_LANGUAGE,
|
_LANGUAGE,
|
||||||
]
|
]
|
||||||
|
if valve_proton:
|
||||||
|
cmd.append("--valve-proton")
|
||||||
|
if dry_run:
|
||||||
|
cmd.append("--dry-run")
|
||||||
account = steam_account_name()
|
account = steam_account_name()
|
||||||
if account:
|
if account:
|
||||||
cmd += ["--username", account]
|
cmd += ["--username", account]
|
||||||
|
|||||||
@ -138,6 +138,7 @@ def install_game(
|
|||||||
steam_id: str,
|
steam_id: str,
|
||||||
*,
|
*,
|
||||||
use_steam_protocol: bool = False,
|
use_steam_protocol: bool = False,
|
||||||
|
valve_proton: bool = False,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""Install a game, through steam-game-installer when it can be used.
|
"""Install a game, through steam-game-installer when it can be used.
|
||||||
|
|
||||||
@ -145,22 +146,19 @@ def install_game(
|
|||||||
below it is the fallback for when it is refused or fails.
|
below it is the fallback for when it is refused or fails.
|
||||||
|
|
||||||
When *use_steam_protocol* is True the ``steam://install`` URI handler
|
When *use_steam_protocol* is True the ``steam://install`` URI handler
|
||||||
is used, which lets Steam determine the correct install directory from
|
is used, so Steam picks the canonical ``installdir`` from its own
|
||||||
its own metadata. This avoids mismatches between the display name and
|
metadata (a display-name mismatch causes "Missing game executable").
|
||||||
the canonical ``installdir`` that can cause "Missing game executable"
|
Falls back to a fabricated appmanifest if the handler is unavailable.
|
||||||
errors. Falls back to writing a fabricated appmanifest if the URI
|
|
||||||
handler is unavailable.
|
|
||||||
|
|
||||||
When *use_steam_protocol* is False (the default) a minimal
|
When False (the default) a minimal appmanifest with StateFlags=1026 is
|
||||||
appmanifest with StateFlags=1026 is written directly. This is
|
written directly: no Steam dialog, for non-interactive / daemon use.
|
||||||
suitable for non-interactive / daemon contexts where opening a Steam
|
|
||||||
dialog is undesirable.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
app_id: Steam application ID.
|
app_id: Steam application ID.
|
||||||
game_name: Human-readable game name.
|
game_name: Human-readable game name.
|
||||||
steam_id: Steam64 ID of the account that owns the game.
|
steam_id: Steam64 ID of the account that owns the game.
|
||||||
use_steam_protocol: Prefer the ``steam://install`` URI handler.
|
use_steam_protocol: Prefer the ``steam://install`` URI handler.
|
||||||
|
valve_proton: Keep the game on Valve's default Proton (fast path).
|
||||||
|
|
||||||
Returns True if the install was triggered successfully.
|
Returns True if the install was triggered successfully.
|
||||||
"""
|
"""
|
||||||
@ -170,9 +168,8 @@ def install_game(
|
|||||||
return ready
|
return ready
|
||||||
|
|
||||||
# The installer only finishes a manifest it finds: queue a fresh install first.
|
# The installer only finishes a manifest it finds: queue a fresh install first.
|
||||||
if fast_install(
|
prepare = partial(_queue_download, app_id, game_name, steam_id)
|
||||||
app_id, label, partial(_queue_download, app_id, game_name, steam_id)
|
if fast_install(app_id, label, prepare, valve_proton=valve_proton):
|
||||||
):
|
|
||||||
return True
|
return True
|
||||||
# Steam already has a download of its own going: let it carry on, rather
|
# Steam already has a download of its own going: let it carry on, rather
|
||||||
# than overwrite its manifest with the fabricated one below.
|
# than overwrite its manifest with the fabricated one below.
|
||||||
|
|||||||
@ -104,6 +104,22 @@ def _pick(
|
|||||||
return _assignment(state)
|
return _assignment(state)
|
||||||
|
|
||||||
|
|
||||||
|
def _install(
|
||||||
|
params: Mapping[str, ParamValue], _progress: Progress, _prompter: Prompter
|
||||||
|
) -> JobResult:
|
||||||
|
"""``install``: optional target, dry run and Valve-Proton switch."""
|
||||||
|
state = State.load()
|
||||||
|
target = params.get("target")
|
||||||
|
data = cmd_install(
|
||||||
|
Config.load(),
|
||||||
|
state,
|
||||||
|
target=str(target) if target else None,
|
||||||
|
dry_run=bool(params.get("dry_run")),
|
||||||
|
valve_proton=bool(params.get("valve_proton")),
|
||||||
|
)
|
||||||
|
return data if data is not None else _assignment(state)
|
||||||
|
|
||||||
|
|
||||||
def _enforce_demo(
|
def _enforce_demo(
|
||||||
params: Mapping[str, ParamValue], _progress: Progress, _prompter: Prompter
|
params: Mapping[str, ParamValue], _progress: Progress, _prompter: Prompter
|
||||||
) -> JobResult:
|
) -> JobResult:
|
||||||
@ -157,7 +173,7 @@ HANDLERS: dict[str, JobHandler] = {
|
|||||||
"pick": _pick,
|
"pick": _pick,
|
||||||
"pick-manual": _with_args(cmd_pick_manual, "app_id"),
|
"pick-manual": _with_args(cmd_pick_manual, "app_id"),
|
||||||
"abandon-pick": _with_args(cmd_abandon_pick, "app_id"),
|
"abandon-pick": _with_args(cmd_abandon_pick, "app_id"),
|
||||||
"install": _cli(cmd_install),
|
"install": _install,
|
||||||
"uninstall": _cli(cmd_uninstall),
|
"uninstall": _cli(cmd_uninstall),
|
||||||
"hide": _cli(cmd_hide),
|
"hide": _cli(cmd_hide),
|
||||||
"unhide": _cli(cmd_unhide),
|
"unhide": _cli(cmd_unhide),
|
||||||
|
|||||||
112
steam_backlog_enforcer/main/_install_target.py
Normal file
112
steam_backlog_enforcer/main/_install_target.py
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
"""Which game ``install`` may touch, and the installer's dry run.
|
||||||
|
|
||||||
|
The web ``install`` takes a target the way the installer does (AppID, Steam
|
||||||
|
URL or name), but the enforcer resolves it, inside the set of games allowed
|
||||||
|
today, before the installer runs. The installer then only ever gets the
|
||||||
|
checked ``--appid``: handing it the raw text would let its own Steam search
|
||||||
|
pick an app this check never saw. Names are matched locally, so a refused
|
||||||
|
game costs no network call and an ambiguous one is a choice, never a guess.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._actions import allowed_games
|
||||||
|
from steam_backlog_enforcer._desktop_env import resolve_desktop_user
|
||||||
|
from steam_backlog_enforcer._echo import _echo
|
||||||
|
from steam_backlog_enforcer._fast_install_cmd import build_cmd, installer_path
|
||||||
|
from steam_backlog_enforcer._owned_apps_cache import load_owned_records
|
||||||
|
from steam_backlog_enforcer._prompter import PromptOption, current_prompter
|
||||||
|
from steam_backlog_enforcer._whitelist_locking import get_approved_exception_ids
|
||||||
|
from steam_backlog_enforcer.jobs._errors import JobError
|
||||||
|
from steam_installer.target import parse_literal
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from steam_backlog_enforcer.config import Config, State
|
||||||
|
|
||||||
|
# The dry run only reads Steam's app cache and library folders.
|
||||||
|
_DRY_RUN_TIMEOUT_SECONDS = 50
|
||||||
|
|
||||||
|
|
||||||
|
def install_candidates(config: Config, state: State) -> list[tuple[int, str]]:
|
||||||
|
"""Every game ``install`` may install today, as ``(app_id, name)``.
|
||||||
|
|
||||||
|
The enforcer's allowed games (assignment first, then manual picks) plus
|
||||||
|
the approved exceptions, named from the owned-games records.
|
||||||
|
"""
|
||||||
|
games = allowed_games(state)
|
||||||
|
known = {aid for aid, _ in games}
|
||||||
|
records = load_owned_records(config.steam_id) or []
|
||||||
|
names = {int(r["app_id"]): str(r.get("name") or "") for r in records}
|
||||||
|
for app_id in sorted(get_approved_exception_ids() - known):
|
||||||
|
games.append((app_id, names.get(app_id, "")))
|
||||||
|
return games
|
||||||
|
|
||||||
|
|
||||||
|
def _refuse(text: str) -> JobError:
|
||||||
|
"""The refusal for a game that is not allowed today."""
|
||||||
|
return JobError(f"{text!r} is not a game allowed today.", code="locked")
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_target(text: str, candidates: list[tuple[int, str]]) -> tuple[int, str]:
|
||||||
|
"""Resolve *text* to one of *candidates*.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
JobError: ``locked`` when the target is not an allowed game.
|
||||||
|
"""
|
||||||
|
literal = parse_literal(text)
|
||||||
|
if literal is not None:
|
||||||
|
game = next((g for g in candidates if g[0] == literal[0]), None)
|
||||||
|
if game is None:
|
||||||
|
raise _refuse(text)
|
||||||
|
return game
|
||||||
|
wanted = text.strip().casefold()
|
||||||
|
exact = [g for g in candidates if g[1].casefold() == wanted]
|
||||||
|
matches = exact or [g for g in candidates if wanted in g[1].casefold()]
|
||||||
|
if not matches:
|
||||||
|
raise _refuse(text)
|
||||||
|
if len(matches) == 1:
|
||||||
|
return matches[0]
|
||||||
|
options = [PromptOption(str(aid), name) for aid, name in matches]
|
||||||
|
picked = int(current_prompter().choice("Install which game", options))
|
||||||
|
return next(g for g in matches if g[0] == picked)
|
||||||
|
|
||||||
|
|
||||||
|
def dry_run_install(app_id: int, name: str, *, valve_proton: bool) -> None:
|
||||||
|
"""Run the installer's ``--dry-run`` for *app_id* and relay its report.
|
||||||
|
|
||||||
|
Never goes through ``install_game``: no manifest is queued, Steam is not
|
||||||
|
closed and there is no ``steam://`` fallback, so it is safe while a game
|
||||||
|
is running.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
JobError: ``op_failed`` when the installer is missing or fails.
|
||||||
|
"""
|
||||||
|
installer = installer_path()
|
||||||
|
if installer is None:
|
||||||
|
msg = "steam-game-installer is missing from this checkout."
|
||||||
|
raise JobError(msg, code="op_failed")
|
||||||
|
cmd = build_cmd(
|
||||||
|
installer,
|
||||||
|
app_id,
|
||||||
|
resolve_desktop_user(),
|
||||||
|
valve_proton=valve_proton,
|
||||||
|
dry_run=True,
|
||||||
|
)
|
||||||
|
_echo(f"Dry run for {name or f'AppID={app_id}'}:")
|
||||||
|
proc = subprocess.run(
|
||||||
|
cmd,
|
||||||
|
check=False,
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.STDOUT,
|
||||||
|
text=True,
|
||||||
|
timeout=_DRY_RUN_TIMEOUT_SECONDS,
|
||||||
|
)
|
||||||
|
for line in proc.stdout.splitlines():
|
||||||
|
_echo(f" {line}")
|
||||||
|
if proc.returncode:
|
||||||
|
msg = f"Dry run failed (installer exit {proc.returncode})."
|
||||||
|
raise JobError(msg, code="op_failed")
|
||||||
@ -14,6 +14,7 @@ from steam_backlog_enforcer._prompter import (
|
|||||||
current_prompter,
|
current_prompter,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._steam_errors import SteamUnavailableError
|
from steam_backlog_enforcer._steam_errors import SteamUnavailableError
|
||||||
|
from steam_backlog_enforcer._steam_restart_guard import game_is_running
|
||||||
from steam_backlog_enforcer._steam_state import is_game_fully_installed
|
from steam_backlog_enforcer._steam_state import is_game_fully_installed
|
||||||
from steam_backlog_enforcer.game_install import (
|
from steam_backlog_enforcer.game_install import (
|
||||||
_echo,
|
_echo,
|
||||||
@ -26,6 +27,11 @@ from steam_backlog_enforcer.library_hider import (
|
|||||||
try_hide_other_games,
|
try_hide_other_games,
|
||||||
unhide_all_games,
|
unhide_all_games,
|
||||||
)
|
)
|
||||||
|
from steam_backlog_enforcer.main._install_target import (
|
||||||
|
dry_run_install,
|
||||||
|
install_candidates,
|
||||||
|
resolve_target,
|
||||||
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from steam_backlog_enforcer.config import Config, State
|
from steam_backlog_enforcer.config import Config, State
|
||||||
@ -78,16 +84,16 @@ def cmd_uninstall(_config: Config, state: State) -> None:
|
|||||||
_echo(f"\nUninstalled {count} games.")
|
_echo(f"\nUninstalled {count} games.")
|
||||||
|
|
||||||
|
|
||||||
def _pick_install_target(state: State) -> tuple[int, str] | None:
|
def _pick_install_target(
|
||||||
|
candidates: list[tuple[int, str]],
|
||||||
|
) -> tuple[int, str] | None:
|
||||||
"""The allowed game to install: the only unfinished one, or the user's pick.
|
"""The allowed game to install: the only unfinished one, or the user's pick.
|
||||||
|
|
||||||
Every allowed game counts, not just the assignment: a manual pick whose
|
Every allowed game counts, not just the assignment: a manual pick whose
|
||||||
fast install was skipped (a game was running at pick time) needs a way to
|
fast install was skipped (a game was running at pick time) needs a way to
|
||||||
start it later too.
|
start it later too, and so does an approved exception.
|
||||||
"""
|
"""
|
||||||
pending = [
|
pending = [(aid, n) for aid, n in candidates if not is_game_fully_installed(aid)]
|
||||||
(aid, n) for aid, n in allowed_games(state) if not is_game_fully_installed(aid)
|
|
||||||
]
|
|
||||||
if not pending:
|
if not pending:
|
||||||
_echo("All allowed games are already installed.")
|
_echo("All allowed games are already installed.")
|
||||||
return None
|
return None
|
||||||
@ -98,31 +104,71 @@ def _pick_install_target(state: State) -> tuple[int, str] | None:
|
|||||||
return next(game for game in pending if game[0] == picked)
|
return next(game for game in pending if game[0] == picked)
|
||||||
|
|
||||||
|
|
||||||
def cmd_install(config: Config, state: State) -> None:
|
def cmd_install(
|
||||||
|
config: Config,
|
||||||
|
state: State,
|
||||||
|
*,
|
||||||
|
target: str | None = None,
|
||||||
|
dry_run: bool = False,
|
||||||
|
valve_proton: bool = False,
|
||||||
|
) -> dict[str, object] | None:
|
||||||
"""Install an allowed game, through the fast installer when it can be used.
|
"""Install an allowed game, through the fast installer when it can be used.
|
||||||
|
|
||||||
A download Steam already started is taken over, so this is also how a
|
A download Steam already started is taken over, so this is also how a
|
||||||
fast install that was skipped earlier gets started.
|
fast install that was skipped earlier gets started. *target* (AppID, URL
|
||||||
|
or name) must be a game allowed today; *dry_run* only reports what the
|
||||||
|
installer would do.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{app_id, dry_run, fast_install_skipped}`` once a game was chosen,
|
||||||
|
else ``None``.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
JobError: ``locked`` for a target that is not allowed today.
|
||||||
"""
|
"""
|
||||||
if not allowed_games(state):
|
candidates = install_candidates(config, state)
|
||||||
|
if not candidates:
|
||||||
_echo("No game currently assigned. Run 'scan' first.")
|
_echo("No game currently assigned. Run 'scan' first.")
|
||||||
return
|
return None
|
||||||
target = _pick_install_target(state)
|
if target:
|
||||||
if target is None:
|
chosen: tuple[int, str] | None = resolve_target(target, candidates)
|
||||||
return
|
else:
|
||||||
app_id, name = target
|
chosen = _pick_install_target(candidates)
|
||||||
|
if chosen is None:
|
||||||
|
return None
|
||||||
|
app_id, name = chosen
|
||||||
|
result: dict[str, object] = {
|
||||||
|
"app_id": app_id,
|
||||||
|
"dry_run": dry_run,
|
||||||
|
"fast_install_skipped": None,
|
||||||
|
}
|
||||||
|
if dry_run:
|
||||||
|
current_progress().phase(f"Dry run of {name or app_id}")
|
||||||
|
dry_run_install(app_id, name, valve_proton=valve_proton)
|
||||||
|
return result
|
||||||
|
# The installer closes Steam: with a game running the fast path is
|
||||||
|
# refused (Steam's own download starts instead), and the UI says why.
|
||||||
|
if game_is_running():
|
||||||
|
result["fast_install_skipped"] = "game_running"
|
||||||
|
|
||||||
_echo(f"Installing {name} (AppID={app_id})...")
|
_echo(f"Installing {name} (AppID={app_id})...")
|
||||||
# install_game only *starts* the download (fast installer or steam://);
|
# install_game only *starts* the download (fast installer or steam://);
|
||||||
# there is no download-progress loop to report on yet.
|
# there is no download-progress loop to report on yet.
|
||||||
current_progress().phase(f"Starting install of {name}")
|
current_progress().phase(f"Starting install of {name}")
|
||||||
if not install_game(app_id, name, config.steam_id, use_steam_protocol=True):
|
if not install_game(
|
||||||
|
app_id,
|
||||||
|
name,
|
||||||
|
config.steam_id,
|
||||||
|
use_steam_protocol=True,
|
||||||
|
valve_proton=valve_proton,
|
||||||
|
):
|
||||||
_echo("Failed to start the install.")
|
_echo("Failed to start the install.")
|
||||||
elif fast_install_failure(app_id) is None:
|
elif fast_install_failure(app_id) is None:
|
||||||
_echo("Done!")
|
_echo("Done!")
|
||||||
else:
|
else:
|
||||||
# The fast install already printed its "Failed: ..." line.
|
# The fast install already printed its "Failed: ..." line.
|
||||||
_echo("Steam's own download was started instead.")
|
_echo("Steam's own download was started instead.")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
def cmd_hide(config: Config, state: State) -> None:
|
def cmd_hide(config: Config, state: State) -> None:
|
||||||
|
|||||||
@ -110,3 +110,12 @@ class TestIsFastInstalling:
|
|||||||
_RUNS.append(_DetachedRun(5, MagicMock(), Path("/nonexistent")))
|
_RUNS.append(_DetachedRun(5, MagicMock(), Path("/nonexistent")))
|
||||||
assert _fast_install.is_fast_installing(5) is True
|
assert _fast_install.is_fast_installing(5) is True
|
||||||
assert _fast_install.is_fast_installing(6) is False
|
assert _fast_install.is_fast_installing(6) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_cmd_valve_proton_and_dry_run() -> None:
|
||||||
|
"""The two install switches become the installer's own flags."""
|
||||||
|
with patch.object(_fast_install_cmd, "steam_account_name", return_value=None):
|
||||||
|
cmd = _fast_install_cmd.build_cmd(
|
||||||
|
Path("/x/steam_installer/cli.py"), 7, None, valve_proton=True, dry_run=True
|
||||||
|
)
|
||||||
|
assert cmd[-2:] == ["--valve-proton", "--dry-run"]
|
||||||
|
|||||||
@ -27,7 +27,9 @@ class TestQueueBeforeFastInstall:
|
|||||||
install is queued with Steam before the installer runs, not after."""
|
install is queued with Steam before the installer runs, not after."""
|
||||||
seen: list[bool] = []
|
seen: list[bool] = []
|
||||||
|
|
||||||
def fast(_app_id: int, _label: str, prepare: Callable[[], object]) -> bool:
|
def fast(
|
||||||
|
_app_id: int, _label: str, prepare: Callable[[], object], **_kw: object
|
||||||
|
) -> bool:
|
||||||
prepare()
|
prepare()
|
||||||
seen.append((tmp_path / "appmanifest_440.acf").exists())
|
seen.append((tmp_path / "appmanifest_440.acf").exists())
|
||||||
return True
|
return True
|
||||||
|
|||||||
228
steam_backlog_enforcer/tests/test_install_target.py
Normal file
228
steam_backlog_enforcer/tests/test_install_target.py
Normal file
@ -0,0 +1,228 @@
|
|||||||
|
"""Tests for ``install`` with a target, a dry run and the Valve-Proton switch.
|
||||||
|
|
||||||
|
The locker stays intact: the target is resolved and checked by the enforcer
|
||||||
|
against the games allowed today (the assignment, manual picks and approved
|
||||||
|
exceptions), and the installer only ever gets the checked ``--appid``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._command_params import validate_params
|
||||||
|
from steam_backlog_enforcer._prompter import use_prompter
|
||||||
|
from steam_backlog_enforcer.config import Config, State
|
||||||
|
from steam_backlog_enforcer.jobs import _registry
|
||||||
|
from steam_backlog_enforcer.jobs._errors import JobError
|
||||||
|
from steam_backlog_enforcer.main import cmd_install
|
||||||
|
from steam_backlog_enforcer.main._install_target import (
|
||||||
|
install_candidates,
|
||||||
|
resolve_target,
|
||||||
|
)
|
||||||
|
from steam_backlog_enforcer.tests._fake_prompter import FakePrompter
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
|
||||||
|
PKG = "steam_backlog_enforcer.main.install"
|
||||||
|
TGT = "steam_backlog_enforcer.main._install_target"
|
||||||
|
CANDIDATES = [(1, "Portal"), (2, "Portal 2"), (3, "Hades")]
|
||||||
|
|
||||||
|
|
||||||
|
def _state() -> State:
|
||||||
|
return State(
|
||||||
|
current_app_id=1,
|
||||||
|
current_game_name="Portal",
|
||||||
|
manual_picks=[{"app_id": 2, "game_name": "Portal 2"}],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(name="env")
|
||||||
|
def _env() -> Iterator[dict[str, MagicMock]]:
|
||||||
|
"""Exceptions = {3: Hades}; nothing installed; no game running."""
|
||||||
|
with (
|
||||||
|
patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({3})),
|
||||||
|
patch(
|
||||||
|
f"{TGT}.load_owned_records",
|
||||||
|
return_value=[{"app_id": 3, "name": "Hades"}],
|
||||||
|
),
|
||||||
|
patch(f"{PKG}.is_game_fully_installed", return_value=False),
|
||||||
|
patch(f"{PKG}.install_game", return_value=True) as install,
|
||||||
|
patch(f"{PKG}.fast_install_failure", return_value=None),
|
||||||
|
patch(f"{PKG}.game_is_running", return_value=False) as running,
|
||||||
|
patch(f"{TGT}.subprocess.run") as run,
|
||||||
|
patch(f"{TGT}.installer_path", return_value=MagicMock()),
|
||||||
|
patch(f"{TGT}.build_cmd", return_value=["installer"]) as build,
|
||||||
|
patch(f"{PKG}._echo"),
|
||||||
|
patch(f"{TGT}._echo"),
|
||||||
|
):
|
||||||
|
run.return_value = MagicMock(returncode=0, stdout="would install\n")
|
||||||
|
yield {"install": install, "run": run, "build": build, "running": running}
|
||||||
|
|
||||||
|
|
||||||
|
class TestCandidates:
|
||||||
|
"""Allowed today = allowed_games plus approved exceptions."""
|
||||||
|
|
||||||
|
def test_exception_is_a_candidate_with_its_owned_name(self) -> None:
|
||||||
|
"""An approved exception is offered under its owned-records name."""
|
||||||
|
with (
|
||||||
|
patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({3})),
|
||||||
|
patch(
|
||||||
|
f"{TGT}.load_owned_records",
|
||||||
|
return_value=[{"app_id": 3, "name": "Hades"}, {"app_id": 9}],
|
||||||
|
),
|
||||||
|
):
|
||||||
|
assert install_candidates(Config(steam_id="i"), _state()) == CANDIDATES
|
||||||
|
|
||||||
|
def test_exception_without_records_gets_an_empty_name(self) -> None:
|
||||||
|
"""No owned records: the exception still counts, nameless."""
|
||||||
|
with (
|
||||||
|
patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({1, 5})),
|
||||||
|
patch(f"{TGT}.load_owned_records", return_value=None),
|
||||||
|
):
|
||||||
|
got = install_candidates(Config(steam_id="i"), _state())
|
||||||
|
assert got == [(1, "Portal"), (2, "Portal 2"), (5, "")]
|
||||||
|
|
||||||
|
|
||||||
|
class TestResolveTarget:
|
||||||
|
"""AppID, URL and name all resolve inside the allowed set only."""
|
||||||
|
|
||||||
|
def test_appid(self) -> None:
|
||||||
|
"""A bare allowed AppID resolves to itself."""
|
||||||
|
assert resolve_target("2", CANDIDATES) == (2, "Portal 2")
|
||||||
|
|
||||||
|
def test_url(self) -> None:
|
||||||
|
"""A store URL resolves through its ``app/<id>``."""
|
||||||
|
url = "https://store.steampowered.com/app/3/Hades/"
|
||||||
|
assert resolve_target(url, CANDIDATES) == (3, "Hades")
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"text", ["999", "https://steamcommunity.com/app/999/guides/", "Doom"]
|
||||||
|
)
|
||||||
|
def test_not_allowed_is_refused(self, text: str) -> None:
|
||||||
|
"""Any game outside the allowed set is refused as ``locked``."""
|
||||||
|
with pytest.raises(JobError) as exc:
|
||||||
|
resolve_target(text, CANDIDATES)
|
||||||
|
assert exc.value.code == "locked"
|
||||||
|
|
||||||
|
def test_exact_name_wins(self) -> None:
|
||||||
|
"""A fully typed title does not install the sequel."""
|
||||||
|
assert resolve_target("portal", CANDIDATES) == (1, "Portal")
|
||||||
|
|
||||||
|
def test_unique_partial_name(self) -> None:
|
||||||
|
"""A unique partial name resolves without asking."""
|
||||||
|
assert resolve_target("had", CANDIDATES) == (3, "Hades")
|
||||||
|
|
||||||
|
def test_ambiguous_name_asks(self) -> None:
|
||||||
|
"""Several matches are offered as a choice, never guessed."""
|
||||||
|
prompter = FakePrompter(choices=["2"])
|
||||||
|
with use_prompter(prompter):
|
||||||
|
assert resolve_target("Port", CANDIDATES) == (2, "Portal 2")
|
||||||
|
assert prompter.asked[0][1] == ["1", "2"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestInstallJob:
|
||||||
|
"""cmd_install with the web job's params."""
|
||||||
|
|
||||||
|
def test_picker_offers_not_installed_exception(
|
||||||
|
self, env: dict[str, MagicMock]
|
||||||
|
) -> None:
|
||||||
|
"""Todo 6ee260a4: the no-target picker includes approved exceptions."""
|
||||||
|
prompter = FakePrompter(choices=["3"])
|
||||||
|
with use_prompter(prompter):
|
||||||
|
cmd_install(Config(steam_id="i"), _state())
|
||||||
|
assert prompter.asked[0][1] == ["1", "2", "3"]
|
||||||
|
assert env["install"].call_args.args[:2] == (3, "Hades")
|
||||||
|
|
||||||
|
def test_disallowed_target_starts_nothing(self, env: dict[str, MagicMock]) -> None:
|
||||||
|
"""A refused target never reaches the installer."""
|
||||||
|
with pytest.raises(JobError):
|
||||||
|
cmd_install(Config(steam_id="i"), _state(), target="999")
|
||||||
|
env["install"].assert_not_called()
|
||||||
|
env["run"].assert_not_called()
|
||||||
|
|
||||||
|
def test_allowed_target_installs(self, env: dict[str, MagicMock]) -> None:
|
||||||
|
"""An allowed target installs, Valve Proton passed through."""
|
||||||
|
result = cmd_install(
|
||||||
|
Config(steam_id="i"), _state(), target="Hades", valve_proton=True
|
||||||
|
)
|
||||||
|
assert env["install"].call_args.args[:2] == (3, "Hades")
|
||||||
|
assert env["install"].call_args.kwargs["valve_proton"] is True
|
||||||
|
assert result == {"app_id": 3, "dry_run": False, "fast_install_skipped": None}
|
||||||
|
|
||||||
|
def test_game_running_is_reported(self, env: dict[str, MagicMock]) -> None:
|
||||||
|
"""The fast-install guard's refusal is in the result data for the UI."""
|
||||||
|
env["running"].return_value = True
|
||||||
|
result = cmd_install(Config(steam_id="i"), _state(), target="3")
|
||||||
|
assert result is not None
|
||||||
|
assert result["fast_install_skipped"] == "game_running"
|
||||||
|
|
||||||
|
def test_dry_run_changes_nothing(self, env: dict[str, MagicMock]) -> None:
|
||||||
|
"""Dry run: only the installer's --dry-run, even with a game running."""
|
||||||
|
env["running"].return_value = True
|
||||||
|
result = cmd_install(
|
||||||
|
Config(steam_id="i"), _state(), target="3", dry_run=True, valve_proton=True
|
||||||
|
)
|
||||||
|
env["install"].assert_not_called()
|
||||||
|
assert env["build"].call_args.kwargs == {"valve_proton": True, "dry_run": True}
|
||||||
|
assert env["build"].call_args.args[1] == 3
|
||||||
|
assert result == {"app_id": 3, "dry_run": True, "fast_install_skipped": None}
|
||||||
|
|
||||||
|
def test_failed_dry_run_fails_the_job(self, env: dict[str, MagicMock]) -> None:
|
||||||
|
"""A dry run the installer rejects is a failed job, not a success."""
|
||||||
|
env["run"].return_value = MagicMock(returncode=1, stdout="ERROR x\n")
|
||||||
|
with pytest.raises(JobError) as exc:
|
||||||
|
cmd_install(Config(steam_id="i"), _state(), target="3", dry_run=True)
|
||||||
|
assert exc.value.code == "op_failed"
|
||||||
|
|
||||||
|
def test_dry_run_without_installer(self, env: dict[str, MagicMock]) -> None:
|
||||||
|
"""No installer in the checkout: the dry run fails loudly."""
|
||||||
|
with (
|
||||||
|
patch(f"{TGT}.installer_path", return_value=None),
|
||||||
|
pytest.raises(JobError),
|
||||||
|
):
|
||||||
|
cmd_install(Config(steam_id="i"), _state(), target="3", dry_run=True)
|
||||||
|
env["run"].assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestInstallParamsAndHandler:
|
||||||
|
"""The web form's params reach cmd_install unchanged."""
|
||||||
|
|
||||||
|
def test_install_params_are_optional(self) -> None:
|
||||||
|
"""target / dry_run / valve_proton are all optional."""
|
||||||
|
assert validate_params("install", {}) == {"dry_run": 0, "valve_proton": 0}
|
||||||
|
got = validate_params("install", {"target": " Hades ", "dry_run": 1})
|
||||||
|
assert got == {"target": "Hades", "dry_run": 1, "valve_proton": 0}
|
||||||
|
|
||||||
|
def test_handler_maps_params(self) -> None:
|
||||||
|
"""The job handler turns the flat params into cmd_install kwargs."""
|
||||||
|
with (
|
||||||
|
patch.object(_registry, "cmd_install", return_value={"app_id": 3}) as cmd,
|
||||||
|
patch.object(_registry.State, "load", return_value=_state()),
|
||||||
|
patch.object(_registry.Config, "load", return_value=Config()),
|
||||||
|
):
|
||||||
|
out = _registry.HANDLERS["install"](
|
||||||
|
{"target": "3", "dry_run": 1, "valve_proton": 0},
|
||||||
|
MagicMock(),
|
||||||
|
MagicMock(),
|
||||||
|
)
|
||||||
|
assert out == {"app_id": 3}
|
||||||
|
assert cmd.call_args.kwargs == {
|
||||||
|
"target": "3",
|
||||||
|
"dry_run": True,
|
||||||
|
"valve_proton": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_handler_without_target(self) -> None:
|
||||||
|
"""No target: the picker path, and None data becomes the assignment."""
|
||||||
|
with (
|
||||||
|
patch.object(_registry, "cmd_install", return_value=None) as cmd,
|
||||||
|
patch.object(_registry.State, "load", return_value=_state()),
|
||||||
|
patch.object(_registry.Config, "load", return_value=Config()),
|
||||||
|
):
|
||||||
|
out = _registry.HANDLERS["install"]({}, MagicMock(), MagicMock())
|
||||||
|
assert cmd.call_args.kwargs["target"] is None
|
||||||
|
assert out == {"current_app_id": 1, "current_game_name": "Portal"}
|
||||||
Loading…
Reference in New Issue
Block a user