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

113 lines
3.7 KiB
Python

"""Work out which Steam app the user meant from one free-form argument.
Four accepted forms, all resolving to the same app:
284160
https://steamcommunity.com/app/284160/guides/
https://store.steampowered.com/app/284160/BeamNGdrive/
BeamNG.drive
BeamNG
Whatever the input, the appid is always confirmed through steamcmd's own
`app_info_print` before anything acts on it, so the name and installdir used
downstream come from Steam rather than from a search index that ranks
"Portal 2" above "Portal".
"""
from __future__ import annotations
import re
import sys
from dataclasses import dataclass
from steam_installer import appinfo, resolve
# `app/<digits>` preceded by a delimiter: matches both store and community
# URLs, any trailing path or query, and `steam://` links. Not anchored to a
# scheme, so a bare "steamcommunity.com/app/284160" works too.
APP_URL_RE = re.compile(r"(?:^|[/?&])app/(\d+)(?:[/?#]|$)")
class TargetError(Exception):
"""The input could not be resolved to exactly one Steam app."""
@dataclass(frozen=True)
class Resolved:
metadata: appinfo.AppMetadata
source: str # "flag" | "appid" | "url" | "exact" | "picked"
def parse_literal(text: str) -> tuple[int, str] | None:
"""(appid, source) when the text literally names one, else None."""
stripped = text.strip()
if stripped.isdigit() and int(stripped) > 0:
return int(stripped), "appid"
match = APP_URL_RE.search(stripped)
if match:
return int(match.group(1)), "url"
return None
def _confirm(appid: int, source: str) -> Resolved:
try:
return Resolved(appinfo.get_metadata(appid), source)
except appinfo.AppInfoError as exc:
raise TargetError(f"appid {appid} is not a known Steam app ({exc})") from exc
def _by_name(text: str, *, interactive: bool) -> Resolved:
try:
results = resolve.search(text)
except resolve.SearchUnavailable as exc:
raise TargetError(
f"Steam search is unavailable ({exc}). Pass the numeric AppID instead."
) from exc
if not results:
raise TargetError(f"No Steam app matches {text!r}.")
if len(results) == 1:
return _confirm(results[0].appid, "only match")
# Exact title first: Steam ranks "Portal 2" above "Portal", so without this
# a fully-typed name silently installs the sequel.
exact = resolve.exact_match(results, text)
if exact is not None:
return _confirm(exact.appid, "exact")
if not interactive:
# Fail closed. Guessing here is how the wrong 90 GB gets downloaded.
print(f"{text!r} is ambiguous. Candidates:", file=sys.stderr)
for result in results:
print(f" {result.appid} {result.name}", file=sys.stderr)
raise TargetError(
"Ambiguous name in a non-interactive run. Re-run with the exact "
"title or the numeric AppID."
)
return _confirm(resolve.prompt_confirm(results).appid, "picked")
def resolve_target(
text: str | None, appid: int | None, *, interactive: bool
) -> Resolved:
"""Resolve --appid, or a free-form target, to confirmed app metadata."""
if appid is not None:
return _confirm(appid, "flag")
if text is None:
raise TargetError("No target given.")
literal = parse_literal(text)
if literal is not None:
candidate, source = literal
try:
return _confirm(candidate, source)
except TargetError:
# Digits are not unambiguous -- a game literally called "2048"
# exists -- so an unknown appid falls through to a name search
# rather than dead-ending. A URL cannot be a name, so it doesn't.
if source != "appid":
raise
return _by_name(text, interactive=interactive)