steam-backlog-enforcer/_installer_import/steam_installer/appinfo.py
Krzysztof kuhy Rudnicki aaf9c18a8a fix(recognize): stop Steam re-downloading after a hand-finished install
The KCD2 run reported success but Steam re-downloaded 90 GB anyway. Two
independent causes, plus a defect that hid both.

force_install_dir sets a Steam *library root*, not an install directory.
Pointing it at the game folder made steamcmd search <game>/steamapps/ for
manifests ("Loaded 0 apps from install folder"), create that stray dir, and
fail the app with "Invalid platform" for lack of depot context. Dropped it;
the app already lives in a registered library. Separately, a Linux steamcmd
needs +@sSteamCmdForcePlatformType windows for a Windows-only title.

Steam then discarded the manifest because it was self-contradictory:
StateFlags=4 while BytesDownloaded (22 GB) != BytesToDownload (92 GB), with
tens of GB still staged under steamapps/downloading/. Across every genuinely
installed manifest the byte counters are equal in pairs, StagingSize is 0 and
staging is empty; DownloadType is kept, not dropped. Settle all of it, and
refuse to call an install real until it holds.

The defect that hid this: steamcmd exited 8 having done nothing and the tool
still wrote StateFlags=4, printed a success line and returned 0. Now gated on
depotdownloader succeeding, every required depot being cached, real game
content on disk, a matching buildid and no running Steam client -- and it
re-reads the manifest after writing.

Also fixes data corruption found in review: vdf.dumps never re-escaped
backslashes, so each parse/dump cycle halved them and silently mangled the
Windows paths in appmanifest_228980.acf's InstallScripts. Manifest writes are
now atomic with a preserved pristine .acf.bak.

Adds per-run logging to ~/.local/state/steam-game-installer (argv, exit codes,
full subprocess output, manifest before/after), teed through a pty so
steamcmd's password prompt still works.

Verified end-to-end on KCD2: Steam logged "Fully Installed, App Running" and
the game launched with no download queued. Coverage 100% statements+branches,
enforced by fail_under.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EK4urCmbTqN4Vrc3nGBcXF
2026-08-05 10:11:34 +02:00

143 lines
4.8 KiB
Python

"""Look up app metadata via steamcmd's app_info_print (anonymous, no login needed)."""
from __future__ import annotations
import re
import subprocess
from dataclasses import dataclass
from steam_installer import vdf
class AppInfoError(Exception):
pass
@dataclass
class AppMetadata:
appid: int
name: str
installdir: str
@dataclass
class DepotPlan:
"""Which depots a given (os, language) install is actually supposed to contain.
Needed to check that a download finished. "Every depot in app_info" is the
wrong bar: KCD2 lists 12 depots but an english/windows install only ever
fetches 3 of them, the rest being other languages, DLC and other platforms.
"""
required: set[str]
shared: set[str]
@property
def all_expected(self) -> set[str]:
return self.required | self.shared
def _fetch_app_block(appid: int) -> dict:
result = subprocess.run(
[
"steamcmd",
# Without this, a Linux steamcmd resolves a Windows-only app's depot
# list against the host platform and can come back empty.
"+@sSteamCmdForcePlatformType",
"windows",
"+login",
"anonymous",
"+app_info_print",
str(appid),
"+quit",
],
capture_output=True,
text=True,
timeout=60,
)
output = result.stdout
# app_info_print emits `"<appid>"\n{ ... }` inside a stream of steamcmd's own log lines;
# slice from the first line that starts the VDF block onward.
match = re.search(rf'^"{appid}"\s*$', output, re.MULTILINE)
if not match:
raise AppInfoError(f"steamcmd did not return app info for {appid}:\n{output}")
data = vdf.parse(output[match.start() :])
app_block = data.get(str(appid), {})
if not isinstance(app_block, dict):
raise AppInfoError(f"unexpected app_info_print structure for {appid}")
return app_block
def get_metadata(appid: int) -> AppMetadata:
"""Fetch the fields this project actually needs: display name and installdir."""
app_block = _fetch_app_block(appid)
common = app_block.get("common", {})
if not isinstance(common, dict):
raise AppInfoError(f"no 'common' section in app info for {appid}")
name = common.get("name")
if not isinstance(name, str):
raise AppInfoError(f"no name field found for app {appid}")
installdir = common.get("installdir")
if not isinstance(installdir, str):
config = app_block.get("config", {})
installdir = config.get("installdir") if isinstance(config, dict) else None
if not isinstance(installdir, str):
raise AppInfoError(f"no installdir field found for app {appid}")
return AppMetadata(appid=appid, name=name, installdir=installdir)
def get_build_id(appid: int, branch: str = "public") -> str | None:
"""Current buildid for `branch`, used to sanity-check the manifest we write."""
app_block = _fetch_app_block(appid)
depots = app_block.get("depots", {})
if not isinstance(depots, dict):
return None
branches = depots.get("branches", {})
if not isinstance(branches, dict):
return None
entry = branches.get(branch, {})
if not isinstance(entry, dict):
return None
build_id = entry.get("buildid")
return build_id if isinstance(build_id, str) else None
def get_depot_plan(
appid: int, language: str = "english", os_name: str = "windows"
) -> DepotPlan:
"""Depots an (os, language) install should end up with.
Skips depots belonging to another language, another OS, a DLC (`dlcappid`)
or marked `optional` -- none of those are fetched by a default install, so
demanding them would make a healthy download look incomplete.
"""
app_block = _fetch_app_block(appid)
depots = app_block.get("depots", {})
if not isinstance(depots, dict):
raise AppInfoError(f"no 'depots' section in app info for {appid}")
required: set[str] = set()
shared: set[str] = set()
for depot_id, entry in depots.items():
if not depot_id.isdigit() or not isinstance(entry, dict):
continue
# A shared depot is installed once under its owning app, not here.
if "depotfromapp" in entry or "sharedinstall" in entry:
shared.add(depot_id)
continue
if entry.get("dlcappid") or entry.get("optional") == "1":
continue
config = entry.get("config", {})
config = config if isinstance(config, dict) else {}
oslist = config.get("oslist")
if isinstance(oslist, str) and oslist and os_name not in oslist.split(","):
continue
depot_language = config.get("language")
if isinstance(depot_language, str) and depot_language != language:
continue
required.add(depot_id)
return DepotPlan(required=required, shared=shared)