steam-backlog-enforcer/_installer_import/steam_installer/vdf.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

135 lines
4.1 KiB
Python

"""Minimal reader/writer for Valve's KeyValues (VDF) text format.
Steam uses this format for appmanifest_*.acf, libraryfolders.vdf, and
steamcmd's `app_info_print` output. Only the plain-text variant is
supported (no binary VDF) -- that covers every file this project touches.
"""
from __future__ import annotations
from dataclasses import dataclass
VdfValue = "str | dict[str, VdfValue]"
@dataclass
class VdfParseError(Exception):
message: str
position: int
def __str__(self) -> str:
return f"{self.message} (at position {self.position})"
def parse(text: str) -> dict[str, VdfValue]:
"""Parse VDF text into a nested dict. Returns the top-level block's contents."""
tokens = _tokenize(text)
pos = 0
def parse_block() -> tuple[dict[str, VdfValue], int]:
nonlocal pos
result: dict[str, VdfValue] = {}
while pos < len(tokens):
token = tokens[pos]
if token == "}":
pos += 1
return result, pos
key = token
pos += 1
if pos >= len(tokens):
raise VdfParseError(f"unexpected end of input after key {key!r}", pos)
if tokens[pos] == "{":
pos += 1
value, pos = parse_block()
else:
value = tokens[pos]
pos += 1
result[key] = value
return result, pos
# A VDF file is one root key followed by one root block.
if not tokens:
return {}
root_key = tokens[0]
pos = 1
if pos >= len(tokens) or tokens[pos] != "{":
raise VdfParseError("expected '{' after root key", pos)
pos += 1
root_value, pos = parse_block()
return {root_key: root_value}
def _tokenize(text: str) -> list[str]:
tokens: list[str] = []
i = 0
n = len(text)
while i < n:
ch = text[i]
if ch in " \t\r\n":
i += 1
continue
if ch == "/" and i + 1 < n and text[i + 1] == "/":
while i < n and text[i] != "\n":
i += 1
continue
if ch in "{}":
tokens.append(ch)
i += 1
continue
if ch == '"':
j = i + 1
buf = []
while j < n and text[j] != '"':
if text[j] == "\\" and j + 1 < n:
buf.append(text[j + 1])
j += 2
else:
buf.append(text[j])
j += 1
tokens.append("".join(buf))
i = j + 1
continue
# Unquoted token (rare in Steam's own files, but tolerate it).
j = i
while j < n and text[j] not in " \t\r\n{}":
j += 1
tokens.append(text[i:j])
i = j
return tokens
def _escape(value: str) -> str:
r"""Re-escape a value for VDF output.
The tokenizer consumes `\` escapes, so a manifest holding
`_CommonRedist\\vcredist\\2015\\installscript.vdf` parses to a value with
single backslashes. Writing that back verbatim would halve them on every
parse/dump cycle and silently corrupt the path -- confirmed against the
real appmanifest_228980.acf (Steamworks Common Redistributables), whose
InstallScripts entries are Windows paths and whose depot 228989 is shared
with other games.
"""
return value.replace("\\", "\\\\").replace('"', '\\"')
def dumps(root_key: str, data: dict[str, VdfValue], indent: str = "\t") -> str:
"""Serialize a dict back to VDF text, matching Steam's own tab-indented style."""
lines = [f'"{root_key}"', "{"]
_dump_block(data, indent, 1, lines)
lines.append("}")
return "\n".join(lines) + "\n"
def _dump_block(
data: dict[str, VdfValue], indent: str, depth: int, lines: list[str]
) -> None:
prefix = indent * depth
for key, value in data.items():
if isinstance(value, dict):
lines.append(f'{prefix}"{_escape(key)}"')
lines.append(f"{prefix}{{")
_dump_block(value, indent, depth + 1, lines)
lines.append(f"{prefix}}}")
else:
lines.append(f'{prefix}"{_escape(key)}"\t\t"{_escape(value)}"')