steam-backlog-enforcer/_installer_import/steam_installer/steamctl.py
Krzysztof kuhy Rudnicki 15f647f639 Install any game from an appid, a URL or a name; adopt Steam's partial downloads
`./run.sh <anything>` is now the entry point. It installs its own dependencies
(steamcmd via yay, DepotDownloader from the SteamRE release, a local .venv) and
works out what the argument is: an appid, a Steam URL, an exact title, or part
of a title. Every route is confirmed through steamcmd's own app_info before
anything acts on it.

Name search moves to steamcommunity.com/actions/SearchApps, which works, with
the storefront API kept as a fallback -- it TLS-rejects scripted clients here,
so search had been effectively dead. DNS on this box fails transiently about one
lookup in three, so each backend is retried before giving up. An exact title now
wins over Steam's own ranking, which puts "Portal 2" above "Portal"; an
ambiguous name shows a picker, or exits 2 rather than guessing.

Two problems found while building this, both now handled:

Anonymous steamcmd has no licence for a paid app and does not say so. It
transfers nothing, prints "Success! App '284160' fully installed.", exits 0, and
writes StateFlags=4 with SizeOnDisk=0 and no depots. A running Steam client then
reads that, decides the app is installed but stale, and downloads the whole game
by itself. `ghost.py` detects that state -- validated read-only against all ten
manifests in a real library, where the nine genuine installs are untouched and
only the fabricated one matches -- and `--repair-ghosts` clears it away. Repair
uses rmdir, never rmtree, so a non-empty directory survives a wrong diagnosis.

And Steam's own in-progress downloads are no longer wasted. `takeover.py`
hardlinks `steamapps/downloading/<appid>/` into the install directory before
depotdownloader runs; depotdownloader hash-checks what is already on disk
(ContentDownloader.cs skips a file when neededChunks is empty) and fetches only
the remainder. Nothing is deleted up front -- the staging tree is cleared only
after the install is verified -- so a failed run still leaves Steam able to
resume. The trees share inodes, so an in-place chunk patch corrects both.

cli.py drops from 311 to 244 lines, back under the repo's 250-line cap, by
moving the install flow to flow.py and the manifest finish to finalize.py.

install.sh had a latent bug: `pip install -e .[dev]` only warns about a missing
extra and exits 0, so the `|| fallback` that installed pytest and coverage never
ran. A fresh venv had no test tools at all; the existing one only worked because
they had been installed by hand earlier. Now named outright and asserted.

246 tests, 100% statement and branch coverage. Verified live: all four input
forms resolve to 284160, an exact "Portal" resolves to 400 and not 620, an
ambiguous name exits 2, ghost detection flags nothing on nine real installs, and
a from-scratch venv bootstraps and runs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sgkb3wH6MU9fYquX328ovT
2026-09-11 21:38:16 +02:00

73 lines
2.2 KiB
Python

"""Stop and start the Steam client around operations it would otherwise fight.
Steam owns `appmanifest_*.acf` while it runs: it rewrites them from its own
in-memory state, so anything this tool writes underneath a live client is
discarded. It also actively writes into `steamapps/downloading/<appid>/`, so
adopting a staged tree while it runs races a live download.
The client is only ever asked to leave politely (`steam -shutdown`). Nothing
here sends a signal: SIGKILLing a client mid-write is how a manifest ends up
truncated, and a hung Steam is a reason to stop and tell the user, not to
escalate.
"""
from __future__ import annotations
import logging
import subprocess
import time
from collections.abc import Callable
from steam_installer import recognize
SHUTDOWN_TIMEOUT = 60.0
POLL_INTERVAL = 0.5
class SteamStillRunning(Exception):
"""Steam was asked to exit and did not."""
def stop(
logger: logging.Logger,
*,
timeout: float = SHUTDOWN_TIMEOUT,
sleep: Callable[[float], None] = time.sleep,
) -> bool:
"""Shut Steam down. Returns True if it had been running, False if it wasn't.
Raises SteamStillRunning if it refuses to exit, so callers can abort
without having touched anything.
"""
if not recognize.steam_client_pids():
return False
logger.info("Shutting down the Steam client...")
subprocess.run(["steam", "-shutdown"], check=False, capture_output=True)
waited = 0.0
while waited < timeout:
if not recognize.steam_client_pids():
logger.info("Steam exited after %.0fs.", waited)
return True
sleep(POLL_INTERVAL)
waited += POLL_INTERVAL
pids = recognize.steam_client_pids()
raise SteamStillRunning(
f"Steam is still running after {timeout:.0f}s (pid "
f"{', '.join(str(p) for p in pids)}). Close it by hand and re-run."
)
def start(logger: logging.Logger) -> None:
"""Relaunch Steam, detached, so it outlives this process."""
logger.info("Restarting the Steam client...")
# Detached on purpose: Steam outlives this process and is never waited on.
subprocess.Popen(
["steam"],
start_new_session=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)