mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-24 04:16:17 +01:00
Initial implementation: fast Steam installs via depotdownloader + steamcmd
Wraps depotdownloader for the bulk content pull (bypasses Steam's own capped download speed) and steamcmd's app_update --validate to make Steam recognize the result, with a manual-manifest fallback for the confirmed steamcmd install-script segfault bug when no fix is available. Name search via store.steampowered.com is best-effort since that endpoint TLS-rejects scripted clients on this network; --appid plus steamcmd's own app_info_print is the reliable primary path. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
commit
72390acc2c
5
_installer_import/.gitignore
vendored
Normal file
5
_installer_import/.gitignore
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
*.egg-info/
|
||||
24
_installer_import/install.sh
Executable file
24
_installer_import/install.sh
Executable file
@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
# Checks for depotdownloader and steamcmd on PATH. steamcmd is AUR-only and
|
||||
# needs an interactive license/sudo prompt, so it's never installed for you --
|
||||
# this just tells you the command to run.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
missing=0
|
||||
|
||||
if ! command -v depotdownloader >/dev/null 2>&1; then
|
||||
echo "missing: depotdownloader (see ~/depotdownloader)" >&2
|
||||
missing=1
|
||||
fi
|
||||
|
||||
if ! command -v steamcmd >/dev/null 2>&1; then
|
||||
echo "missing: steamcmd -- run: yay -S steamcmd" >&2
|
||||
missing=1
|
||||
fi
|
||||
|
||||
if [[ "$missing" -eq 0 ]]; then
|
||||
echo "All dependencies present."
|
||||
fi
|
||||
|
||||
exit "$missing"
|
||||
16
_installer_import/pyproject.toml
Normal file
16
_installer_import/pyproject.toml
Normal file
@ -0,0 +1,16 @@
|
||||
[project]
|
||||
name = "steam-game-installer"
|
||||
version = "0.1.0"
|
||||
description = "Fast Steam game installs: depotdownloader for speed, steamcmd for recognition."
|
||||
requires-python = ">=3.11"
|
||||
dependencies = []
|
||||
|
||||
[project.scripts]
|
||||
steam-game-installer = "steam_installer.cli:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
0
_installer_import/steam_installer/__init__.py
Normal file
0
_installer_import/steam_installer/__init__.py
Normal file
61
_installer_import/steam_installer/appinfo.py
Normal file
61
_installer_import/steam_installer/appinfo.py
Normal file
@ -0,0 +1,61 @@
|
||||
"""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
|
||||
|
||||
|
||||
def _fetch_app_block(appid: int) -> dict:
|
||||
result = subprocess.run(
|
||||
["steamcmd", "+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)
|
||||
121
_installer_import/steam_installer/cli.py
Normal file
121
_installer_import/steam_installer/cli.py
Normal file
@ -0,0 +1,121 @@
|
||||
"""Entry point: resolve -> confirm -> fast download -> make Steam recognize it."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
|
||||
from steam_installer import appinfo, depotdl, recognize, resolve
|
||||
from steam_installer.library import find_steam_root, list_libraries, pick_install_target
|
||||
|
||||
|
||||
def _require_tool(name: str, install_hint: str) -> None:
|
||||
if shutil.which(name) is None:
|
||||
print(f"error: `{name}` not found on PATH. {install_hint}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def _resolve_appid(args: argparse.Namespace) -> int:
|
||||
"""Prefer an explicit --appid; fall back to search, which is best-effort
|
||||
(store.steampowered.com is known to reject scripted clients on some
|
||||
networks -- see resolve.py). Either way, the final confirmation uses the
|
||||
real name from steamcmd's own app info, not whatever the search returned.
|
||||
"""
|
||||
if args.appid is not None:
|
||||
return args.appid
|
||||
|
||||
try:
|
||||
results = resolve.search(args.name)
|
||||
except resolve.SearchUnavailable as exc:
|
||||
print(f"Store search unavailable ({exc}).", file=sys.stderr)
|
||||
print(
|
||||
"Find the numeric AppID yourself (e.g. from the store URL) and pass --appid.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
chosen = resolve.prompt_confirm(results)
|
||||
return chosen.appid
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Download an owned Steam game fast, then make Steam recognize it."
|
||||
)
|
||||
parser.add_argument("name", nargs="?", default=None, help="Game name to search for")
|
||||
parser.add_argument(
|
||||
"--appid", type=int, default=None, help="Steam AppID (skips search)"
|
||||
)
|
||||
parser.add_argument("--username", required=True, help="Steam account username")
|
||||
parser.add_argument(
|
||||
"--language", default=None, help="Language depot to fetch (default: prompts)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-downloads", type=int, default=depotdl.DEFAULT_MAX_DOWNLOADS
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.appid is None and args.name is None:
|
||||
parser.error("provide a game name to search for, or --appid directly")
|
||||
|
||||
_require_tool("depotdownloader", "See ~/depotdownloader.")
|
||||
_require_tool("steamcmd", "Run: yay -S steamcmd")
|
||||
|
||||
appid = _resolve_appid(args)
|
||||
metadata = appinfo.get_metadata(appid)
|
||||
print(f"Confirmed: {metadata.name} (appid {metadata.appid})")
|
||||
answer = input("Proceed? [y/N]: ").strip().lower()
|
||||
if answer != "y":
|
||||
print("Cancelled.")
|
||||
return 1
|
||||
|
||||
steam_root = find_steam_root()
|
||||
libraries = list_libraries(steam_root)
|
||||
target = pick_install_target(libraries, metadata.installdir)
|
||||
print(f"Install target: {target}")
|
||||
|
||||
language = args.language
|
||||
if language is None:
|
||||
language = input("Language [english]: ").strip() or "english"
|
||||
|
||||
print("Downloading via depotdownloader (fast path)...")
|
||||
depotdl.download(
|
||||
appid=metadata.appid,
|
||||
install_dir=target,
|
||||
username=args.username,
|
||||
language=language,
|
||||
max_downloads=args.max_downloads,
|
||||
)
|
||||
|
||||
print("Reconciling with steamcmd (validate)...")
|
||||
library = next(lib for lib in libraries if lib.common == target.parent)
|
||||
result = recognize.run_steamcmd_validate(metadata.appid, target, args.username)
|
||||
|
||||
if result.completed:
|
||||
print("steamcmd finished cleanly -- Steam should show Play.")
|
||||
return 0
|
||||
|
||||
if result.crashed_on_install_script:
|
||||
print(
|
||||
"steamcmd hit the known install-script crash; finishing the manifest manually..."
|
||||
)
|
||||
manifest_path = recognize.finish_manifest_manually(
|
||||
library=library,
|
||||
appid=metadata.appid,
|
||||
install_dir=target,
|
||||
now_unix=int(time.time()),
|
||||
)
|
||||
print(f"Wrote {manifest_path} -- launch Steam and confirm Play works.")
|
||||
return 0
|
||||
|
||||
print(
|
||||
"steamcmd failed for an unrecognized reason -- output above, not auto-resolved."
|
||||
)
|
||||
print(result.output[-4000:])
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
46
_installer_import/steam_installer/depotdl.py
Normal file
46
_installer_import/steam_installer/depotdl.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""Wraps depotdownloader for the bulk content pull -- this is the fast path.
|
||||
|
||||
No `-depot` filter is passed: depotdownloader's own per-depot ownership check
|
||||
(AccountHasAccess, checked before any key fetch) already skips depots the
|
||||
account doesn't own and continues with the rest, as long as `-os` is set
|
||||
correctly. Without `-os`, it defaults to the host OS and can filter out every
|
||||
real (Windows-tagged) depot, leaving only stray OS-agnostic ones -- that's
|
||||
what caused the very first "0 bytes from 0 depots" failure this project was
|
||||
built to avoid.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_MAX_DOWNLOADS = 32
|
||||
|
||||
|
||||
def download(
|
||||
appid: int,
|
||||
install_dir: Path,
|
||||
username: str,
|
||||
language: str = "english",
|
||||
os_name: str = "windows",
|
||||
max_downloads: int = DEFAULT_MAX_DOWNLOADS,
|
||||
) -> None:
|
||||
"""Run depotdownloader against `install_dir`, streaming its own progress output live."""
|
||||
install_dir.mkdir(parents=True, exist_ok=True)
|
||||
cmd = [
|
||||
"depotdownloader",
|
||||
"-app",
|
||||
str(appid),
|
||||
"-os",
|
||||
os_name,
|
||||
"-language",
|
||||
language,
|
||||
"-max-downloads",
|
||||
str(max_downloads),
|
||||
"-username",
|
||||
username,
|
||||
"-remember-password",
|
||||
"-dir",
|
||||
str(install_dir),
|
||||
]
|
||||
subprocess.run(cmd, check=True)
|
||||
76
_installer_import/steam_installer/library.py
Normal file
76
_installer_import/steam_installer/library.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""Steam library discovery: find install roots and where a given app lives."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from steam_installer import vdf
|
||||
|
||||
DEFAULT_STEAM_ROOT = Path.home() / ".local/share/Steam"
|
||||
|
||||
|
||||
@dataclass
|
||||
class SteamLibrary:
|
||||
path: Path
|
||||
|
||||
@property
|
||||
def common(self) -> Path:
|
||||
return self.path / "steamapps" / "common"
|
||||
|
||||
@property
|
||||
def steamapps(self) -> Path:
|
||||
return self.path / "steamapps"
|
||||
|
||||
|
||||
def find_steam_root() -> Path:
|
||||
"""Locate the Steam installation. Raises if none of the usual paths exist."""
|
||||
for candidate in (DEFAULT_STEAM_ROOT, Path.home() / ".steam/steam"):
|
||||
if (candidate / "steamapps").is_dir():
|
||||
return candidate
|
||||
raise FileNotFoundError(
|
||||
"No Steam installation found at ~/.local/share/Steam or ~/.steam/steam"
|
||||
)
|
||||
|
||||
|
||||
def list_libraries(steam_root: Path) -> list[SteamLibrary]:
|
||||
"""Every Steam library folder, parsed from libraryfolders.vdf (plus steam_root itself)."""
|
||||
libraries = [SteamLibrary(steam_root)]
|
||||
vdf_path = steam_root / "steamapps" / "libraryfolders.vdf"
|
||||
if not vdf_path.is_file():
|
||||
return libraries
|
||||
data = vdf.parse(vdf_path.read_text())
|
||||
folders = data.get("libraryfolders", {})
|
||||
if not isinstance(folders, dict):
|
||||
return libraries
|
||||
seen = {steam_root.resolve()}
|
||||
for entry in folders.values():
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
raw_path = entry.get("path")
|
||||
if not raw_path:
|
||||
continue
|
||||
path = Path(raw_path).resolve()
|
||||
if path not in seen:
|
||||
seen.add(path)
|
||||
libraries.append(SteamLibrary(path))
|
||||
return libraries
|
||||
|
||||
|
||||
def find_existing_install(
|
||||
libraries: list[SteamLibrary], installdir: str
|
||||
) -> Path | None:
|
||||
"""Return the install path if `installdir` already exists in any library."""
|
||||
for library in libraries:
|
||||
candidate = library.common / installdir
|
||||
if candidate.is_dir():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def pick_install_target(libraries: list[SteamLibrary], installdir: str) -> Path:
|
||||
"""Where to install: an existing partial install if one exists, else the primary library."""
|
||||
existing = find_existing_install(libraries, installdir)
|
||||
if existing is not None:
|
||||
return existing
|
||||
return libraries[0].common / installdir
|
||||
137
_installer_import/steam_installer/recognize.py
Normal file
137
_installer_import/steam_installer/recognize.py
Normal file
@ -0,0 +1,137 @@
|
||||
"""Make the Steam client recognize downloaded content as installed.
|
||||
|
||||
Primary path: `steamcmd ... app_update <id> validate`. It hash-checks
|
||||
existing files against the depot manifest and only fetches real deltas --
|
||||
confirmed live against a real 90+ GB install, going from ~24% to ~41%
|
||||
credited in one pass without redownloading from scratch.
|
||||
|
||||
Fallback: some titles ship a post-install script (installscript.vdf) that
|
||||
steamcmd tries to run through a private, headless Proton setup. On at least
|
||||
one real title this hit a confirmed steamcmd bug -- a stack-overflow segfault
|
||||
in the closed-source steamclient.so error-handling path after the script
|
||||
evaluator reports failure (crash backtrace: the same stack frame repeating
|
||||
dozens of times). There's no known fix. When that specific crash is
|
||||
detected, we finish the appmanifest by hand using ONLY values we already
|
||||
verified ourselves: the exact manifest IDs from depotdownloader's own local
|
||||
cache (never guessed), and the real on-disk size via `du`. Steam is left to
|
||||
self-correct the rest (byte counters, staged-file bookkeeping) on its very
|
||||
next launch -- confirmed: it did exactly that in practice, cleaning up the
|
||||
hand-edited fields on its own.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from steam_installer import vdf
|
||||
from steam_installer.library import SteamLibrary
|
||||
|
||||
CRASH_SIGNATURE = "Standalone evaluator returned error code"
|
||||
|
||||
MANIFEST_CACHE_RE = re.compile(r"^(\d+)_(\d+)\.manifest$")
|
||||
|
||||
|
||||
class RecognizeError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class ValidateResult:
|
||||
completed: bool
|
||||
crashed_on_install_script: bool
|
||||
output: str
|
||||
|
||||
|
||||
def run_steamcmd_validate(
|
||||
appid: int, install_dir: Path, username: str
|
||||
) -> ValidateResult:
|
||||
"""Run steamcmd's app_update ... validate. `force_install_dir` must precede `+login`
|
||||
(steamcmd itself warns about this ordering)."""
|
||||
cmd = [
|
||||
"steamcmd",
|
||||
"+force_install_dir",
|
||||
str(install_dir),
|
||||
"+login",
|
||||
username,
|
||||
"+app_update",
|
||||
str(appid),
|
||||
"validate",
|
||||
"+quit",
|
||||
]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
|
||||
output = result.stdout + result.stderr
|
||||
crashed = CRASH_SIGNATURE in output
|
||||
return ValidateResult(
|
||||
completed=result.returncode == 0,
|
||||
crashed_on_install_script=crashed,
|
||||
output=output,
|
||||
)
|
||||
|
||||
|
||||
def discover_cached_depot_manifests(install_dir: Path) -> dict[str, str]:
|
||||
"""Depot ID -> manifest ID, read from depotdownloader's own local cache filenames."""
|
||||
cache_dir = install_dir / ".DepotDownloader"
|
||||
found: dict[str, str] = {}
|
||||
if not cache_dir.is_dir():
|
||||
return found
|
||||
for entry in cache_dir.iterdir():
|
||||
match = MANIFEST_CACHE_RE.match(entry.name)
|
||||
if match:
|
||||
depot_id, manifest_id = match.groups()
|
||||
found[depot_id] = manifest_id
|
||||
return found
|
||||
|
||||
|
||||
def finish_manifest_manually(
|
||||
library: SteamLibrary,
|
||||
appid: int,
|
||||
install_dir: Path,
|
||||
now_unix: int,
|
||||
) -> Path:
|
||||
"""Patch appmanifest_<appid>.acf to StateFlags=4 using only verified-known values.
|
||||
|
||||
Requires steamcmd to have already written a partial manifest (even a crashed
|
||||
run does) -- that's where buildid and SharedDepots come from. This never
|
||||
fabricates a manifest from nothing.
|
||||
"""
|
||||
manifest_path = library.steamapps / f"appmanifest_{appid}.acf"
|
||||
if not manifest_path.is_file():
|
||||
raise RecognizeError(
|
||||
f"No existing {manifest_path.name} to finish -- run steamcmd's "
|
||||
"app_update at least once first (even a crashed run writes one)."
|
||||
)
|
||||
data = vdf.parse(manifest_path.read_text())
|
||||
app_state = data.get("AppState", {})
|
||||
if not isinstance(app_state, dict):
|
||||
raise RecognizeError(f"{manifest_path} is not a valid AppState manifest")
|
||||
|
||||
depot_manifests = discover_cached_depot_manifests(install_dir)
|
||||
if not depot_manifests:
|
||||
raise RecognizeError(
|
||||
f"No cached depot manifests found under {install_dir}/.DepotDownloader"
|
||||
)
|
||||
|
||||
size_on_disk = sum(f.stat().st_size for f in install_dir.rglob("*") if f.is_file())
|
||||
buildid = app_state.get("buildid") or app_state.get("TargetBuildID") or "0"
|
||||
|
||||
installed_depots = {
|
||||
depot_id: {"manifest": manifest_id, "size": "0"}
|
||||
for depot_id, manifest_id in depot_manifests.items()
|
||||
}
|
||||
|
||||
app_state["StateFlags"] = "4"
|
||||
app_state["LastUpdated"] = str(now_unix)
|
||||
app_state["SizeOnDisk"] = str(size_on_disk)
|
||||
app_state["StagingSize"] = "0"
|
||||
app_state["buildid"] = buildid
|
||||
app_state["UpdateResult"] = "0"
|
||||
app_state["InstalledDepots"] = installed_depots
|
||||
app_state.pop("StagedDepots", None)
|
||||
|
||||
backup_path = manifest_path.with_suffix(".acf.bak")
|
||||
backup_path.write_text(manifest_path.read_text())
|
||||
manifest_path.write_text(vdf.dumps("AppState", app_state))
|
||||
return manifest_path
|
||||
61
_installer_import/steam_installer/resolve.py
Normal file
61
_installer_import/steam_installer/resolve.py
Normal file
@ -0,0 +1,61 @@
|
||||
"""Resolve a game name to a Steam AppID via the public store-search endpoint.
|
||||
|
||||
store.steampowered.com is known to TLS-reject scripted clients from at least
|
||||
some networks (confirmed: even its bare homepage fails the TLS handshake for
|
||||
plain curl/urllib here, while every other Steam domain works fine -- looks
|
||||
like storefront-specific bot detection, not a general outage). Treat this as
|
||||
best-effort: search() can fail, and callers should fall back to asking for a
|
||||
numeric AppID directly rather than treating a search failure as fatal.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
|
||||
SEARCH_URL = "https://store.steampowered.com/api/storesearch/?term={term}&cc=us"
|
||||
|
||||
|
||||
@dataclass
|
||||
class SearchResult:
|
||||
appid: int
|
||||
name: str
|
||||
|
||||
|
||||
class ResolveError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class SearchUnavailable(Exception):
|
||||
"""The store search endpoint couldn't be reached (network/TLS block, not a code bug)."""
|
||||
|
||||
|
||||
def search(name: str) -> list[SearchResult]:
|
||||
"""Query Steam's store search API for candidate matches. No auth needed."""
|
||||
url = SEARCH_URL.format(term=urllib.parse.quote(name))
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=15) as response:
|
||||
payload = json.loads(response.read())
|
||||
except (urllib.error.URLError, TimeoutError) as exc:
|
||||
raise SearchUnavailable(str(exc)) from exc
|
||||
items = payload.get("items", [])
|
||||
return [SearchResult(appid=item["id"], name=item["name"]) for item in items]
|
||||
|
||||
|
||||
def prompt_confirm(results: list[SearchResult]) -> SearchResult:
|
||||
"""Show numbered candidates and require an explicit choice. Never guesses."""
|
||||
if not results:
|
||||
raise ResolveError("No matches found on Steam.")
|
||||
print("Matches found:")
|
||||
for i, result in enumerate(results, start=1):
|
||||
print(f" {i}. {result.name} (appid {result.appid})")
|
||||
while True:
|
||||
choice = input(f"Which one? [1-{len(results)}, or 0 to cancel]: ").strip()
|
||||
if choice == "0":
|
||||
raise ResolveError("Cancelled by user.")
|
||||
if choice.isdigit() and 1 <= int(choice) <= len(results):
|
||||
return results[int(choice) - 1]
|
||||
print("Invalid choice, try again.")
|
||||
120
_installer_import/steam_installer/vdf.py
Normal file
120
_installer_import/steam_installer/vdf.py
Normal file
@ -0,0 +1,120 @@
|
||||
"""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 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}"{key}"')
|
||||
lines.append(f"{prefix}{{")
|
||||
_dump_block(value, indent, depth + 1, lines)
|
||||
lines.append(f"{prefix}}}")
|
||||
else:
|
||||
lines.append(f'{prefix}"{key}"\t\t"{value}"')
|
||||
70
_installer_import/tests/test_library.py
Normal file
70
_installer_import/tests/test_library.py
Normal file
@ -0,0 +1,70 @@
|
||||
from pathlib import Path
|
||||
|
||||
from steam_installer.library import (
|
||||
SteamLibrary,
|
||||
find_existing_install,
|
||||
list_libraries,
|
||||
pick_install_target,
|
||||
)
|
||||
|
||||
|
||||
def _make_steam_root(tmp_path: Path, extra_library: Path | None = None) -> Path:
|
||||
root = tmp_path / "Steam"
|
||||
(root / "steamapps").mkdir(parents=True)
|
||||
if extra_library is not None:
|
||||
(root / "steamapps" / "libraryfolders.vdf").write_text(
|
||||
f"""
|
||||
"libraryfolders"
|
||||
{{
|
||||
"0"
|
||||
{{
|
||||
"path" "{extra_library}"
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
)
|
||||
return root
|
||||
|
||||
|
||||
def test_list_libraries_includes_root_when_no_vdf(tmp_path):
|
||||
root = _make_steam_root(tmp_path)
|
||||
libraries = list_libraries(root)
|
||||
assert [lib.path for lib in libraries] == [root]
|
||||
|
||||
|
||||
def test_list_libraries_includes_extra_library_from_vdf(tmp_path):
|
||||
extra = tmp_path / "SecondDrive"
|
||||
root = _make_steam_root(tmp_path, extra_library=extra)
|
||||
libraries = list_libraries(root)
|
||||
assert {lib.path for lib in libraries} == {root, extra.resolve()}
|
||||
|
||||
|
||||
def test_find_existing_install_locates_game_in_any_library(tmp_path):
|
||||
root = _make_steam_root(tmp_path)
|
||||
other = tmp_path / "Other"
|
||||
(other / "steamapps" / "common" / "MyGame").mkdir(parents=True)
|
||||
libraries = [SteamLibrary(root), SteamLibrary(other)]
|
||||
found = find_existing_install(libraries, "MyGame")
|
||||
assert found == other / "steamapps" / "common" / "MyGame"
|
||||
|
||||
|
||||
def test_find_existing_install_returns_none_when_absent(tmp_path):
|
||||
root = _make_steam_root(tmp_path)
|
||||
libraries = [SteamLibrary(root)]
|
||||
assert find_existing_install(libraries, "NoSuchGame") is None
|
||||
|
||||
|
||||
def test_pick_install_target_prefers_existing_install(tmp_path):
|
||||
root = _make_steam_root(tmp_path)
|
||||
other = tmp_path / "Other"
|
||||
(other / "steamapps" / "common" / "MyGame").mkdir(parents=True)
|
||||
libraries = [SteamLibrary(root), SteamLibrary(other)]
|
||||
target = pick_install_target(libraries, "MyGame")
|
||||
assert target == other / "steamapps" / "common" / "MyGame"
|
||||
|
||||
|
||||
def test_pick_install_target_defaults_to_primary_library(tmp_path):
|
||||
root = _make_steam_root(tmp_path)
|
||||
libraries = [SteamLibrary(root)]
|
||||
target = pick_install_target(libraries, "NewGame")
|
||||
assert target == root / "steamapps" / "common" / "NewGame"
|
||||
81
_installer_import/tests/test_recognize.py
Normal file
81
_installer_import/tests/test_recognize.py
Normal file
@ -0,0 +1,81 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from steam_installer import vdf
|
||||
from steam_installer.library import SteamLibrary
|
||||
from steam_installer.recognize import (
|
||||
RecognizeError,
|
||||
discover_cached_depot_manifests,
|
||||
finish_manifest_manually,
|
||||
)
|
||||
|
||||
|
||||
def test_discover_cached_depot_manifests_parses_filenames(tmp_path):
|
||||
cache_dir = tmp_path / ".DepotDownloader"
|
||||
cache_dir.mkdir()
|
||||
(cache_dir / "1771302_257127247679847518.manifest").write_bytes(b"x")
|
||||
(cache_dir / "1771302_257127247679847518.manifest.sha").write_bytes(b"x")
|
||||
(cache_dir / "1771303_1999516201078544527.manifest").write_bytes(b"x")
|
||||
(cache_dir / "depot.config").write_bytes(b"x")
|
||||
|
||||
found = discover_cached_depot_manifests(tmp_path)
|
||||
assert found == {
|
||||
"1771302": "257127247679847518",
|
||||
"1771303": "1999516201078544527",
|
||||
}
|
||||
|
||||
|
||||
def test_discover_cached_depot_manifests_missing_dir_returns_empty(tmp_path):
|
||||
assert discover_cached_depot_manifests(tmp_path) == {}
|
||||
|
||||
|
||||
def _write_partial_manifest(steamapps: Path, appid: int) -> None:
|
||||
steamapps.mkdir(parents=True, exist_ok=True)
|
||||
data = {
|
||||
"appid": str(appid),
|
||||
"StateFlags": "1026",
|
||||
"buildid": "23914554",
|
||||
"SharedDepots": {"228989": "228980"},
|
||||
}
|
||||
(steamapps / f"appmanifest_{appid}.acf").write_text(vdf.dumps("AppState", data))
|
||||
|
||||
|
||||
def test_finish_manifest_manually_requires_existing_manifest(tmp_path):
|
||||
library = SteamLibrary(tmp_path / "Steam")
|
||||
install_dir = tmp_path / "Steam" / "steamapps" / "common" / "Game"
|
||||
install_dir.mkdir(parents=True)
|
||||
with pytest.raises(RecognizeError, match="run steamcmd"):
|
||||
finish_manifest_manually(library, 1771300, install_dir, now_unix=1000)
|
||||
|
||||
|
||||
def test_finish_manifest_manually_requires_cached_depot_manifests(tmp_path):
|
||||
library = SteamLibrary(tmp_path / "Steam")
|
||||
_write_partial_manifest(library.steamapps, 1771300)
|
||||
install_dir = library.common / "Game"
|
||||
install_dir.mkdir(parents=True)
|
||||
with pytest.raises(RecognizeError, match="No cached depot manifests"):
|
||||
finish_manifest_manually(library, 1771300, install_dir, now_unix=1000)
|
||||
|
||||
|
||||
def test_finish_manifest_manually_sets_state_flags_and_depots(tmp_path):
|
||||
library = SteamLibrary(tmp_path / "Steam")
|
||||
_write_partial_manifest(library.steamapps, 1771300)
|
||||
install_dir = library.common / "Game"
|
||||
cache_dir = install_dir / ".DepotDownloader"
|
||||
cache_dir.mkdir(parents=True)
|
||||
(cache_dir / "1771302_257127247679847518.manifest").write_bytes(b"x")
|
||||
(install_dir / "game.bin").write_bytes(b"0123456789")
|
||||
|
||||
manifest_path = finish_manifest_manually(
|
||||
library, 1771300, install_dir, now_unix=1000
|
||||
)
|
||||
|
||||
result = vdf.parse(manifest_path.read_text())
|
||||
app_state = result["AppState"]
|
||||
assert app_state["StateFlags"] == "4"
|
||||
assert app_state["buildid"] == "23914554"
|
||||
assert app_state["InstalledDepots"]["1771302"]["manifest"] == "257127247679847518"
|
||||
assert app_state["SharedDepots"] == {"228989": "228980"}
|
||||
assert "StagedDepots" not in app_state
|
||||
assert manifest_path.with_suffix(".acf.bak").is_file()
|
||||
68
_installer_import/tests/test_vdf.py
Normal file
68
_installer_import/tests/test_vdf.py
Normal file
@ -0,0 +1,68 @@
|
||||
from steam_installer import vdf
|
||||
|
||||
|
||||
def test_parse_flat_block():
|
||||
text = """
|
||||
"AppState"
|
||||
{
|
||||
"appid" "1771300"
|
||||
"name" "Kingdom Come: Deliverance II"
|
||||
}
|
||||
"""
|
||||
result = vdf.parse(text)
|
||||
assert result == {
|
||||
"AppState": {
|
||||
"appid": "1771300",
|
||||
"name": "Kingdom Come: Deliverance II",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def test_parse_nested_blocks():
|
||||
text = """
|
||||
"AppState"
|
||||
{
|
||||
"InstalledDepots"
|
||||
{
|
||||
"1771302"
|
||||
{
|
||||
"manifest" "257127247679847518"
|
||||
"size" "199419496"
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
result = vdf.parse(text)
|
||||
assert (
|
||||
result["AppState"]["InstalledDepots"]["1771302"]["manifest"]
|
||||
== "257127247679847518"
|
||||
)
|
||||
|
||||
|
||||
def test_parse_handles_comments_and_blank_lines():
|
||||
text = """
|
||||
// leading comment
|
||||
"AppState"
|
||||
{
|
||||
|
||||
"appid" "1" // trailing comment
|
||||
}
|
||||
"""
|
||||
result = vdf.parse(text)
|
||||
assert result == {"AppState": {"appid": "1"}}
|
||||
|
||||
|
||||
def test_roundtrip_dumps_then_parse():
|
||||
data = {
|
||||
"appid": "1771300",
|
||||
"InstalledDepots": {
|
||||
"1771302": {"manifest": "257127247679847518", "size": "199419496"},
|
||||
},
|
||||
}
|
||||
text = vdf.dumps("AppState", data)
|
||||
reparsed = vdf.parse(text)
|
||||
assert reparsed == {"AppState": data}
|
||||
|
||||
|
||||
def test_empty_input_returns_empty_dict():
|
||||
assert vdf.parse("") == {}
|
||||
Loading…
Reference in New Issue
Block a user