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
This commit is contained in:
Krzysztof Rudnicki 2026-09-11 21:38:16 +02:00
parent 4c35dc9b63
commit 15f647f639
25 changed files with 2722 additions and 364 deletions

View File

@ -5,14 +5,73 @@ better than the Steam client), then make the Steam client accept the result as
a real install so **Play** works.
```bash
./install.sh # checks depotdownloader + steamcmd are present
pip install -e .
steam-game-installer --appid 1771300 --username <steam-user>
./run.sh BeamNG.drive
```
**Close the Steam client first.** Steam owns `appmanifest_<appid>.acf` while it
That is the whole thing. `run.sh` installs its own dependencies (steamcmd via
`yay`, DepotDownloader from the SteamRE release, and a local `.venv`) on first
use, then works out what you meant. All four of these install the same game:
```bash
./run.sh 284160 # an AppID
./run.sh https://steamcommunity.com/app/284160/guides/ # any Steam URL
./run.sh BeamNG.drive # the exact name
./run.sh BeamNG # part of the name
```
An exact title always wins, so `./run.sh Portal` installs Portal and not
Portal 2 — even though Steam's own search ranks the sequel first. An ambiguous
name shows a numbered picker, and in a non-interactive run it lists the
candidates and exits 2 rather than guessing.
Useful flags: `--dry-run` (resolve and report, change nothing), `--yes`
(no prompts), `--repair-ghosts` (see below), `--username` (remembered after the
first run, in `~/.config/steam-game-installer/config`; never a password).
**Steam gets closed for you.** Steam owns `appmanifest_<appid>.acf` while it
runs and rewrites it from its own in-memory state, so anything written
underneath a live client is discarded. The tool refuses to start if it sees one.
underneath a live client is discarded. The tool asks, shuts it down with
`steam -shutdown`, and restarts it afterwards. It never sends a signal: a client
that refuses to exit aborts the run instead.
## It takes over a download Steam already started
Steam stages an in-progress download into `steamapps/downloading/<appid>/`, laid
out exactly like the finished game. Those bytes are yours — you waited for them
— so the tool **hardlinks them into place** before calling depotdownloader,
which hash-checks what is already on disk and fetches only the remainder.
Hardlinks, not moves and not copies. Nothing is deleted up front: the staging
tree is cleared only at the very end, so a failed run still leaves Steam able to
resume its own download. Linking is free, where copying a 47 GB tree would cost
47 GB.
Because the two trees share inodes, depotdownloader patching a partial file in
place also rewrites Steam's copy. That is deliberate — both names converge on
the same corrected content — but it does mean the staged bytes are working data,
not a frozen backup. On ext4 there is no reflink that would give you both.
## Ghost installs
`steamcmd +login anonymous +app_update <paid appid>` has no licence for the app.
It does not say so. It transfers nothing, prints `Success! App '...' fully
installed.`, exits 0, and writes a manifest claiming `StateFlags=4` with
`SizeOnDisk=0` and an empty `InstalledDepots`.
That manifest is not harmless: a running Steam client reads it, concludes the
app is installed but out of date, and downloads the entire game by itself.
```bash
./run.sh --repair-ghosts
```
finds them across every library and clears them away — but only the *cold* ones.
A ghost with staged content behind it is a real partial download; it is reported
and left alone, to be adopted by a normal install instead. Detection requires
all of: the manifest claims installed, `InstalledDepots` is empty, `SizeOnDisk`
is `0`, there are zero content bytes on disk, and there is no `.DepotDownloader`
state. Repair uses `rmdir`, never `rmtree`, so a non-empty directory cannot be
deleted even if the diagnosis were wrong.
## Run logs
@ -50,7 +109,7 @@ The tool refuses to mark an app installed, and exits non-zero, unless:
optional and shared depots — KCD2 lists 12 depots but an english/windows
install only ever fetches 3);
- the manifest carries a real `buildid` matching the current public build;
- no Steam client is running;
- no Steam client is running (it is closed first, and restarted afterwards);
- the manifest reads back as a real install *after* being written.
This matters: an earlier version wrote `StateFlags=4` and reported success after

View File

@ -1,50 +1,169 @@
#!/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.
# ============================================================================
# Install everything this tool shells out to, then set up the dev environment.
#
# steamcmd AUR package, via yay
# depotdownloader official self-contained release from SteamRE/DepotDownloader
# .venv local virtualenv with the package installed editable
#
# Idempotent: every step no-ops when its target is already in place, so run.sh
# can call it on every run. `yay` shells out to `sudo pacman`, so installing
# steamcmd may prompt for a password -- that is the one interactive step.
# ============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly VENV="${SCRIPT_DIR}/.venv"
readonly STAMP="${VENV}/.deps-ok"
readonly DD_REPO="SteamRE/DepotDownloader"
readonly DD_HOME="${XDG_DATA_HOME:-$HOME/.local/share}/steam-game-installer/depotdownloader"
readonly BIN_DIR="${HOME}/.local/bin"
missing=0
CHECK_ONLY=0
TEMP_DIR=""
if ! command -v depotdownloader >/dev/null 2>&1; then
echo "missing: depotdownloader (see ~/vendor/depotdownloader)" >&2
missing=1
fi
cleanup() {
if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then
rm -rf -- "$TEMP_DIR"
fi
}
trap cleanup EXIT
if ! command -v steamcmd >/dev/null 2>&1; then
echo "missing: steamcmd -- run: yay -S steamcmd" >&2
missing=1
fi
usage() {
echo "Usage: install.sh [OPTIONS]"
echo "Options:"
echo " --check-only Report missing dependencies without installing anything"
echo " -h, --help Show this help"
exit 0
}
die() {
echo "error: $*" >&2
exit 1
}
ensure_steamcmd() {
if command -v steamcmd >/dev/null 2>&1; then
return 0
fi
if [[ "$CHECK_ONLY" -eq 1 ]]; then
echo "missing: steamcmd -- run: yay -S steamcmd" >&2
return 1
fi
command -v yay >/dev/null 2>&1 ||
die "steamcmd is missing and yay is not installed. Install it, then: yay -S steamcmd"
echo "Installing steamcmd (yay may ask for your sudo password)..."
yay -S --needed --noconfirm --answerdiff None --answeredit None steamcmd
command -v steamcmd >/dev/null 2>&1 || die "steamcmd still not on PATH after install"
}
# Build from source only if the published binary can't be fetched. The upstream
# global.json pins the SDK to 9.0.x with rollForward=latestMinor, which will NOT
# roll forward to dotnet 10 -- so this needs dotnet-sdk-9.0 specifically.
build_depotdownloader() {
local src="${HOME}/vendor/depotdownloader"
[[ -d "$src" ]] || die "could not download DepotDownloader and no source tree at $src"
command -v yay >/dev/null 2>&1 || die "need yay to install dotnet-sdk-9.0"
pacman -Qq dotnet-sdk-9.0 >/dev/null 2>&1 ||
yay -S --needed --noconfirm dotnet-sdk-9.0
(cd "$src" && dotnet build -c Release)
ln -sfn "${src}/DepotDownloader/bin/Release/net9.0/DepotDownloader" \
"${BIN_DIR}/depotdownloader"
}
ensure_depotdownloader() {
if command -v depotdownloader >/dev/null 2>&1; then
return 0
fi
if [[ "$CHECK_ONLY" -eq 1 ]]; then
echo "missing: depotdownloader -- run ./install.sh" >&2
return 1
fi
mkdir -p "$BIN_DIR"
echo "Fetching the latest DepotDownloader release..."
local url=""
url="$(curl -fsSL "https://api.github.com/repos/${DD_REPO}/releases/latest" |
grep -oE '"browser_download_url": *"[^"]*linux-x64\.zip"' |
cut -d'"' -f4 || true)"
if [[ -n "$url" ]]; then
TEMP_DIR="$(mktemp -d)"
mkdir -p "$DD_HOME"
# bsdtar ships with libarchive, a pacman dependency; unzip may not exist.
curl -fsSL -o "${TEMP_DIR}/dd.zip" "$url" &&
bsdtar -xf "${TEMP_DIR}/dd.zip" -C "$DD_HOME" &&
chmod +x "${DD_HOME}/DepotDownloader" &&
ln -sfn "${DD_HOME}/DepotDownloader" "${BIN_DIR}/depotdownloader"
else
echo "Release download unavailable; falling back to a source build." >&2
build_depotdownloader
fi
command -v depotdownloader >/dev/null 2>&1 ||
die "depotdownloader installed to ${BIN_DIR} but is not on PATH. Add ${BIN_DIR} to PATH."
}
# The suite requires 100% coverage (pyproject: fail_under = 100), and one test
# runs `python -m steam_installer.cli` in a subprocess. Coverage in a child is
# only recorded if it calls coverage.process_startup() at interpreter start,
# which is what this .pth does. Without it a clean clone reports 99% and fails.
setup_dev_env() {
# The test suite requires 100% coverage (pyproject: fail_under = 100), and
# one test runs `python -m steam_installer.cli` in a subprocess. Coverage in
# a child process is only recorded if it calls coverage.process_startup() at
# interpreter start, which is what this .pth does. Without it a clean clone
# reports 99% and the suite fails.
local venv="${SCRIPT_DIR}/.venv"
[[ -d "$venv" ]] || return 0
if [[ ! -x "${VENV}/bin/python" ]]; then
echo "Creating ${VENV}..."
python3 -m venv "$VENV"
fi
local python="${venv}/bin/python"
"$python" -m pip install -q -e "${SCRIPT_DIR}[dev]" 2>/dev/null ||
"$python" -m pip install -q -e "$SCRIPT_DIR" pytest pytest-cov
local python="${VENV}/bin/python"
"$python" -m pip install -q --upgrade pip
# Named outright rather than via an extra: pyproject declares none, and pip
# only *warns* about a missing extra before exiting 0 -- so the old
# `[dev] || fallback` form silently installed no test tools at all on a
# fresh venv, and the .pth below then failed to import coverage.
"$python" -m pip install -q -e "$SCRIPT_DIR" pytest pytest-cov coverage
local site_packages
site_packages="$("$python" -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')"
cat >"${site_packages}/steam_installer_coverage.pth" <<-'PTH'
import os, coverage; os.environ.get("COVERAGE_PROCESS_START") and coverage.process_startup()
PTH
"$python" -c 'import pytest, coverage' ||
die "dev environment incomplete: pytest/coverage did not install"
echo "Dev environment ready (subprocess coverage enabled)."
}
if [[ "$missing" -eq 0 ]]; then
main() {
local missing=0
ensure_steamcmd || missing=1
ensure_depotdownloader || missing=1
if [[ "$CHECK_ONLY" -eq 1 ]]; then
[[ "$missing" -eq 0 ]] && echo "All dependencies present."
exit "$missing"
fi
setup_dev_env
echo "All dependencies present."
fi
: >"$STAMP"
}
setup_dev_env
while [[ $# -gt 0 ]]; do
case $1 in
--check-only)
CHECK_ONLY=1
shift
;;
-h | --help)
usage
;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
exit "$missing"
main

102
_installer_import/run.sh Executable file
View File

@ -0,0 +1,102 @@
#!/bin/bash
# ============================================================================
# Install a Steam game from whatever you happen to have: an AppID, a Steam URL,
# or the game's name.
#
# ./run.sh 284160
# ./run.sh https://steamcommunity.com/app/284160/guides/
# ./run.sh BeamNG.drive
# ./run.sh BeamNG
#
# Dependencies install themselves on first run. Every other argument is passed
# straight through to the CLI, so `./run.sh --help` lists the full set.
# ============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly VENV_PY="${SCRIPT_DIR}/.venv/bin/python"
readonly STAMP="${SCRIPT_DIR}/.venv/.deps-ok"
readonly INSTALLER="${SCRIPT_DIR}/install.sh"
SKIP_DEPS="${SGI_SKIP_DEPS:-0}"
DEPS_ONLY=0
ARGS=()
usage() {
echo "Usage: run.sh [TARGET] [OPTIONS]"
echo
echo "TARGET is any of:"
echo " 284160 an AppID"
echo " https://steamcommunity.com/app/284160/... a Steam URL"
echo " BeamNG.drive the exact name"
echo " BeamNG part of the name"
echo
echo "run.sh options:"
echo " --no-deps Skip the dependency check (also: SGI_SKIP_DEPS=1)"
echo " --deps-only Install dependencies and exit"
echo " -h, --help Show this help, then the installer's own options"
echo
if [[ -x "$VENV_PY" ]]; then
"$VENV_PY" -m steam_installer.cli --help
fi
exit 0
}
# Dependencies are only re-checked when the stamp is missing or older than the
# files that decide what gets installed, so a normal run adds no startup cost.
deps_are_current() {
[[ -x "$VENV_PY" ]] || return 1
[[ -f "$STAMP" ]] || return 1
[[ "$STAMP" -nt "$INSTALLER" ]] || return 1
[[ "$STAMP" -nt "${SCRIPT_DIR}/pyproject.toml" ]] || return 1
"$VENV_PY" -c 'import steam_installer' >/dev/null 2>&1
}
main() {
if [[ "$SKIP_DEPS" != "1" ]] && ! deps_are_current; then
"$INSTALLER"
fi
if [[ "$DEPS_ONLY" -eq 1 ]]; then
exit 0
fi
[[ -x "$VENV_PY" ]] || {
echo "error: no virtualenv at ${VENV_PY}. Run ./install.sh" >&2
exit 1
}
# `-m` rather than the console script, so a stale .venv shim can never
# shadow the working tree.
exec "$VENV_PY" -m steam_installer.cli "${ARGS[@]}"
}
while [[ $# -gt 0 ]]; do
case $1 in
--no-deps)
SKIP_DEPS=1
shift
;;
--deps-only)
DEPS_ONLY=1
shift
;;
-h | --help)
usage
;;
--)
shift
ARGS+=("$@")
break
;;
*)
ARGS+=("$1")
shift
;;
esac
done
main

View File

@ -1,66 +1,71 @@
"""Entry point: resolve -> confirm -> fast download -> make Steam recognize it."""
"""Entry point: resolve -> confirm -> adopt what exists -> fast download -> recognize."""
from __future__ import annotations
import argparse
import shutil
import sys
import time
from pathlib import Path
from steam_installer import appinfo, depotdl, recognize, resolve, runlog
from steam_installer.library import (
SteamLibrary,
find_steam_root,
list_libraries,
pick_install_target,
from steam_installer import (
config,
depotdl,
deps,
flow,
ghost,
resolve,
runlog,
takeover,
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
from steam_installer.library import find_steam_root, list_libraries, pick_install_target
def _build_parser() -> argparse.ArgumentParser:
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)"
"target",
nargs="?",
default=None,
metavar="TARGET",
help=(
"AppID (284160), a Steam URL "
"(https://steamcommunity.com/app/284160/guides/), or a game name "
"(BeamNG.drive, or just BeamNG)"
),
)
parser.add_argument(
"--appid", type=int, default=None, help="Steam AppID (skips detection)"
)
parser.add_argument(
"--username",
default=None,
help="Steam account username (default: $STEAM_USERNAME, then the saved one)",
)
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
)
parser.add_argument(
"--yes",
action="store_true",
help="Assume yes for every prompt. Ambiguous names still fail rather than guess.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Resolve the target and report what would happen. Changes nothing.",
)
parser.add_argument(
"--repair-ghosts",
action="store_true",
help=(
"Scan every library for the fake 'installed' manifests anonymous "
"steamcmd leaves behind, and clear them away."
),
)
parser.add_argument(
"--skip-steamcmd",
action="store_true",
@ -84,10 +89,11 @@ def main(argv: list[str] | None = None) -> int:
parser = _build_parser()
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")
if not args.repair_ghosts and args.appid is None and args.target is None:
parser.error("provide an AppID, a Steam URL, a game name, or --repair-ghosts")
log = runlog.setup(args.appid, verbose=args.verbose)
literal = target.parse_literal(args.target) if args.target else None
log = runlog.setup(args.appid or (literal[0] if literal else None), args.verbose)
logger = log.logger
# Printed up front as well as at the end: if the run dies badly, the path
# still has to be on screen to copy-paste.
@ -102,198 +108,136 @@ def main(argv: list[str] | None = None) -> int:
return 1
def _run(args: argparse.Namespace, log: runlog.RunLog) -> int:
def _is_interactive(args: argparse.Namespace) -> bool:
return sys.stdin.isatty() and not args.yes
def _ask(args: argparse.Namespace, interactive: bool, question: str) -> bool:
if args.yes:
return True
if not interactive:
return False
return input(question).strip().lower() == "y"
def _repair_ghosts(log: runlog.RunLog) -> int:
"""Report every ghost manifest; delete only the ones with nothing behind them."""
logger = log.logger
reports = ghost.scan(list_libraries(find_steam_root()))
if not reports:
logger.info("No ghost installs found.")
return 0
_require_tool("depotdownloader", "See ~/depotdownloader.")
if not args.skip_steamcmd:
_require_tool("steamcmd", "Run: yay -S steamcmd")
appid = _resolve_appid(args)
metadata = appinfo.get_metadata(appid)
logger.info("Confirmed: %s (appid %s)", metadata.name, metadata.appid)
answer = input("Proceed? [y/N]: ").strip().lower()
if answer != "y":
logger.info("Cancelled.")
return 1
steam_root = find_steam_root()
libraries = list_libraries(steam_root)
target = pick_install_target(libraries, metadata.installdir)
logger.info("Install target: %s", target)
language = args.language
if language is None:
language = input("Language [english]: ").strip() or "english"
# Refuse early rather than after an hour of downloading: a live Steam client
# rewrites the manifest from its own state and discards whatever we write.
running = recognize.steam_client_pids()
if running:
logger.error(
"The Steam client is running (pid %s). It owns appmanifest_%s.acf and "
"will overwrite anything this tool writes. Close Steam, then re-run.",
", ".join(str(p) for p in running),
metadata.appid,
)
logger.info("Run log (send this): %s", log.path)
return 1
depot_plan = appinfo.get_depot_plan(metadata.appid, language)
expected_build_id = appinfo.get_build_id(metadata.appid)
log.section("Plan")
logger.debug("language=%s max_downloads=%s", language, args.max_downloads)
logger.debug("required depots: %s", sorted(depot_plan.required))
logger.debug("shared depots: %s", sorted(depot_plan.shared))
logger.debug("expected buildid: %s", expected_build_id)
library = next(lib for lib in libraries if lib.common == target.parent)
manifest_path = library.steamapps / f"appmanifest_{metadata.appid}.acf"
log.file_contents("Manifest before run", manifest_path)
logger.info("Downloading via depotdownloader (fast path)...")
log.section("depotdownloader")
returncode = depotdl.download(
appid=metadata.appid,
install_dir=target,
username=args.username,
language=language,
max_downloads=args.max_downloads,
logger=logger,
)
if returncode != 0:
logger.error(
"depotdownloader failed (exit %d) -- not touching the manifest.", returncode
)
logger.info("Run log (send this): %s", log.path)
return 1
log.section("depotdownloader cache")
for depot_id, mid in sorted(
recognize.discover_cached_depot_manifests(target).items()
):
logger.debug("depot %s -> manifest %s", depot_id, mid)
recognize.ensure_installdir_correct(library, metadata.appid, target)
if not args.skip_steamcmd:
logger.info("Reconciling with steamcmd (validate)...")
log.section("steamcmd app_update validate")
result = recognize.run_steamcmd_validate(metadata.appid, args.username, logger)
log.file_contents("Manifest after steamcmd", manifest_path)
# Never trust steamcmd's exit code alone -- verify the manifest actually
# reflects a real install before believing it. A "clean" exit has
# produced a manifest steamcmd itself hadn't finished updating before.
if (
not result.crashed_on_install_script
and recognize.manifest_reflects_real_install(
library, metadata.appid, target
for report in reports:
logger.info("Ghost: appid %s (%s)", report.appid, report.manifest_path.name)
for reason in report.reasons:
logger.info(" - %s", reason)
if report.is_warm:
logger.warning(
" Steam has %.2f GB staged for this app. Those bytes are a real "
"partial download, so nothing is deleted -- install it normally "
"(this tool adopts them) instead of repairing it.",
report.staging_bytes / 1e9,
)
):
logger.info("steamcmd finished cleanly -- Steam should show Play.")
logger.info("Run log: %s", log.path)
return 0
if result.crashed_on_install_script:
logger.info(
"steamcmd hit the known install-script crash; finishing the manifest manually..."
)
else:
logger.info(
"steamcmd exited %d but the manifest doesn't reflect a real install; "
"checking whether it is safe to finish it manually...",
result.returncode,
)
return _finish(
log,
library,
metadata,
target,
depot_plan,
expected_build_id,
skipped_steamcmd=args.skip_steamcmd,
)
def _finish(
log: runlog.RunLog,
library: SteamLibrary,
metadata: appinfo.AppMetadata,
target: Path,
depot_plan: appinfo.DepotPlan,
expected_build_id: str | None,
skipped_steamcmd: bool,
) -> int:
"""Hand-finish the manifest, but only if every precondition really holds."""
logger = log.logger
manifest_path = library.steamapps / f"appmanifest_{metadata.appid}.acf"
if not manifest_path.is_file():
# Reachable two ways, so don't blame steamcmd unconditionally: under
# --skip-steamcmd it never runs at all, and nothing else in this tool
# creates a manifest from scratch.
logger.error(
"No %s exists, so there is nothing to finish. This tool only ever "
"patches a manifest Steam or steamcmd already wrote; it never "
"fabricates one. %s",
manifest_path,
(
"Re-run without --skip-steamcmd so steamcmd creates it (it writes "
"one even when it crashes)."
if skipped_steamcmd
else "steamcmd writes one even when it crashes, so its absence "
"means steamcmd never ran far enough."
),
)
logger.info("Run log (send this): %s", log.path)
return 1
app_state = recognize.read_app_state(manifest_path)
problems = recognize.check_ready_to_finish(
install_dir=target,
app_state=app_state,
required_depots=depot_plan.required,
expected_build_id=expected_build_id,
)
if problems:
# Fail closed. Writing StateFlags=4 here is what previously turned a
# steamcmd run that did nothing at all into a reported success.
logger.error("Refusing to mark %s as installed:", metadata.name)
for problem in problems:
logger.error(" - %s", problem)
logger.info("Run log (send this): %s", log.path)
return 1
# Do this before writing the manifest: a StateFlags=4 manifest alongside a
# staging tree full of pending chunks is the same contradiction that made
# Steam resume the download last time.
freed = recognize.clear_steam_staging(library, metadata.appid)
if freed:
logger.info("Cleared %.1f GB of stale Steam staging data.", freed / 1e9)
written = recognize.finish_manifest_manually(
library=library,
appid=metadata.appid,
install_dir=target,
now_unix=int(time.time()),
)
log.file_contents("Manifest after manual finish", written)
# Re-read from disk: claiming success without checking the write landed is
# the same fail-open mistake in a different place.
if not recognize.manifest_reflects_real_install(library, metadata.appid, target):
logger.error(
"Wrote %s but it still does not read back as a real install.", written
)
logger.info("Run log (send this): %s", log.path)
return 1
logger.info("Wrote %s -- launch Steam and confirm Play works.", written)
continue
ghost.repair(report, logger)
logger.info("Run log: %s", log.path)
return 0
def _describe(logger, metadata, install_target, report, staged) -> int:
"""--dry-run output: everything the real run would act on, and nothing done."""
logger.info("Install target: %s", install_target)
if report.is_ghost:
logger.warning("This app currently has a GHOST manifest:")
for reason in report.reasons:
logger.warning(" - %s", reason)
if staged is not None:
logger.info(
"Steam has %.2f GB staged in %s (%d files) -- these would be adopted, "
"not re-downloaded.",
staged.bytes_staged / 1e9,
staged.staging_dir,
staged.file_count,
)
logger.info("Dry run: nothing was changed.")
return 0
def _run(args: argparse.Namespace, log: runlog.RunLog) -> int:
logger = log.logger
interactive = _is_interactive(args)
if args.repair_ghosts:
return _repair_ghosts(log)
try:
deps.require(skip_steamcmd=args.skip_steamcmd)
resolved = target.resolve_target(
args.target, args.appid, interactive=interactive
)
except deps.DependencyError as exc:
logger.error("%s", exc)
return 1
except (target.TargetError, resolve.ResolveError) as exc:
logger.error("%s", exc)
return 2
metadata = resolved.metadata
logger.info(
"Confirmed: %s (appid %s, matched by %s)",
metadata.name,
metadata.appid,
resolved.source,
)
libraries = list_libraries(find_steam_root())
install_target = pick_install_target(libraries, metadata.installdir)
library = next(lib for lib in libraries if lib.common == install_target.parent)
report = ghost.inspect(library, metadata.appid)
staged = takeover.find_staged(library, metadata.appid, install_target)
if args.dry_run:
return _describe(logger, metadata, install_target, report, staged)
if report.is_ghost and not report.is_warm:
logger.error(
"appid %s has a ghost manifest (a fake 'installed' state with nothing "
"behind it). Clear it first: ./run.sh --repair-ghosts",
metadata.appid,
)
return 1
try:
username = config.resolve_username(args.username, interactive=interactive)
except config.ConfigError as exc:
logger.error("%s", exc)
return 1
logger.info("Install target: %s", install_target)
if not _ask(args, interactive, "Proceed? [y/N]: "):
logger.info("Cancelled (use --yes for a non-interactive run).")
return 1
language = args.language
if language is None:
language = (
(input("Language [english]: ").strip() or "english")
if interactive
else "english"
)
return flow.install(
args=args,
log=log,
library=library,
metadata=metadata,
install_target=install_target,
staged=staged,
username=username,
language=language,
)
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,63 @@
"""Remember the Steam username so every run doesn't ask for it again.
Only the username is ever persisted. Passwords and Steam Guard codes stay
where they belong: with steamcmd's own cached login token (prompted through
the pty in `runlog.run_logged`) and depotdownloader's `-remember-password`.
Writing either of those to a dotfile would be a downgrade in security over
what Steam's own tooling already does.
"""
from __future__ import annotations
import os
from pathlib import Path
CONFIG_DIR = Path.home() / ".config" / "steam-game-installer"
CONFIG_PATH = CONFIG_DIR / "config"
USERNAME_KEY = "username"
ENV_VAR = "STEAM_USERNAME"
class ConfigError(Exception):
pass
def load_username() -> str | None:
"""The saved username, or None if nothing has been saved yet."""
if not CONFIG_PATH.is_file():
return None
for line in CONFIG_PATH.read_text().splitlines():
key, sep, value = line.partition("=")
if sep and key.strip() == USERNAME_KEY:
return value.strip() or None
return None
def save_username(username: str) -> None:
"""Persist the username at 0600, replacing any previous value."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_PATH.write_text(f"{USERNAME_KEY}={username}\n")
# Not a secret, but it names an account; no reason for it to be world-readable.
CONFIG_PATH.chmod(0o600)
def resolve_username(cli_value: str | None, *, interactive: bool) -> str:
"""--username > $STEAM_USERNAME > saved config > prompt (and save the answer)."""
if cli_value:
return cli_value
env_value = os.environ.get(ENV_VAR, "").strip()
if env_value:
return env_value
saved = load_username()
if saved:
return saved
if not interactive:
raise ConfigError(
"No Steam username available. Pass --username, set "
f"${ENV_VAR}, or run once interactively to save one."
)
entered = input("Steam username: ").strip()
if not entered:
raise ConfigError("No Steam username entered.")
save_username(entered)
return entered

View File

@ -0,0 +1,31 @@
"""External binaries this tool shells out to, and a clear error when they're missing."""
from __future__ import annotations
import shutil
TOOL_HINTS = {
"depotdownloader": "Run ./install.sh, which fetches it from the SteamRE release.",
"steamcmd": "Run ./install.sh, or: yay -S steamcmd",
}
class DependencyError(Exception):
pass
def missing_tools(*, skip_steamcmd: bool) -> list[str]:
"""Which required binaries are not on PATH, in the order they'd be used."""
needed = ["depotdownloader"]
if not skip_steamcmd:
needed.append("steamcmd")
return [tool for tool in needed if shutil.which(tool) is None]
def require(*, skip_steamcmd: bool) -> None:
missing = missing_tools(skip_steamcmd=skip_steamcmd)
if missing:
details = "; ".join(
f"`{tool}` not found -- {TOOL_HINTS[tool]}" for tool in missing
)
raise DependencyError(details)

View File

@ -0,0 +1,92 @@
"""Hand-finish the appmanifest, but only when every precondition really holds.
Split out of cli.py so the entry point stays under the repo's 250-line cap.
The logic is unchanged: it patches a manifest steamcmd or Steam already
wrote, and refuses rather than fabricating one.
"""
from __future__ import annotations
import time
from pathlib import Path
from steam_installer import appinfo, recognize, runlog
from steam_installer.library import SteamLibrary
def finish(
log: runlog.RunLog,
library: SteamLibrary,
metadata: appinfo.AppMetadata,
target: Path,
depot_plan: appinfo.DepotPlan,
expected_build_id: str | None,
skipped_steamcmd: bool,
) -> int:
logger = log.logger
manifest_path = library.steamapps / f"appmanifest_{metadata.appid}.acf"
if not manifest_path.is_file():
# Reachable two ways, so don't blame steamcmd unconditionally: under
# --skip-steamcmd it never runs at all, and nothing else in this tool
# creates a manifest from scratch.
logger.error(
"No %s exists, so there is nothing to finish. This tool only ever "
"patches a manifest Steam or steamcmd already wrote; it never "
"fabricates one. %s",
manifest_path,
(
"Re-run without --skip-steamcmd so steamcmd creates it (it writes "
"one even when it crashes)."
if skipped_steamcmd
else "steamcmd writes one even when it crashes, so its absence "
"means steamcmd never ran far enough."
),
)
logger.info("Run log (send this): %s", log.path)
return 1
app_state = recognize.read_app_state(manifest_path)
problems = recognize.check_ready_to_finish(
install_dir=target,
app_state=app_state,
required_depots=depot_plan.required,
expected_build_id=expected_build_id,
)
if problems:
# Fail closed. Writing StateFlags=4 here is what previously turned a
# steamcmd run that did nothing at all into a reported success.
logger.error("Refusing to mark %s as installed:", metadata.name)
for problem in problems:
logger.error(" - %s", problem)
logger.info("Run log (send this): %s", log.path)
return 1
# Do this before writing the manifest: a StateFlags=4 manifest alongside a
# staging tree full of pending chunks is the same contradiction that made
# Steam resume the download last time. By this point depotdownloader has
# already filled common/, so the staged copies are genuinely redundant.
freed = recognize.clear_steam_staging(library, metadata.appid)
if freed:
logger.info("Cleared %.1f GB of now-redundant Steam staging data.", freed / 1e9)
written = recognize.finish_manifest_manually(
library=library,
appid=metadata.appid,
install_dir=target,
now_unix=int(time.time()),
)
log.file_contents("Manifest after manual finish", written)
# Re-read from disk: claiming success without checking the write landed is
# the same fail-open mistake in a different place.
if not recognize.manifest_reflects_real_install(library, metadata.appid, target):
logger.error(
"Wrote %s but it still does not read back as a real install.", written
)
logger.info("Run log (send this): %s", log.path)
return 1
logger.info("Wrote %s -- launch Steam and confirm Play works.", written)
logger.info("Run log: %s", log.path)
return 0

View File

@ -0,0 +1,182 @@
"""Orchestrate one install: close Steam, adopt staged bytes, download, recognize.
Split out of cli.py so the entry point stays under the repo's 250-line cap.
The manifest-finishing half lives in `finalize.py`.
"""
from __future__ import annotations
from pathlib import Path
from steam_installer import (
appinfo,
depotdl,
recognize,
runlog,
steamctl,
takeover,
)
from steam_installer.finalize import finish
from steam_installer.library import SteamLibrary
def _prepare_steam(args, logger) -> bool | None:
"""Close Steam if it's running. Returns whether it was, or None to abort.
Steam owns the manifest and is actively writing the staging tree, so it has
to be out of the way. Closing someone's Steam is not something to do
silently, so it is confirmed unless --yes was passed.
The caller's own confirmation gate means we only get here with --yes or on
a tty, so prompting is always safe at this point.
"""
if not recognize.steam_client_pids():
return False
if not args.yes:
answer = input("Steam is running and must be closed. Close it now? [y/N]: ")
if answer.strip().lower() != "y":
logger.info("Cancelled.")
return None
try:
return steamctl.stop(logger)
except steamctl.SteamStillRunning as exc:
logger.error("%s", exc)
return None
def install(
*,
args,
log: runlog.RunLog,
library: SteamLibrary,
metadata: appinfo.AppMetadata,
install_target: Path,
staged: takeover.Staged | None,
username: str,
language: str,
) -> int:
"""Adopt anything Steam already fetched, download the rest, make it count."""
logger = log.logger
steam_was_running = _prepare_steam(args, logger)
if steam_was_running is None:
return 1
try:
return _download_and_recognize(
args, log, library, metadata, install_target, staged, username, language
)
finally:
if steam_was_running:
steamctl.start(logger)
def _download_and_recognize(
args,
log: runlog.RunLog,
library: SteamLibrary,
metadata: appinfo.AppMetadata,
install_target: Path,
staged: takeover.Staged | None,
username: str,
language: str,
) -> int:
logger = log.logger
if staged is not None:
log.section("Adopting Steam's staged download")
logger.info(
"Steam already staged %.2f GB for this app (%d files). Hardlinking it "
"into place so depotdownloader verifies instead of refetching.",
staged.bytes_staged / 1e9,
staged.file_count,
)
install_target.mkdir(parents=True, exist_ok=True)
takeover.adopt(staged, logger)
depot_plan = appinfo.get_depot_plan(metadata.appid, language)
expected_build_id = appinfo.get_build_id(metadata.appid)
log.section("Plan")
logger.debug("language=%s max_downloads=%s", language, args.max_downloads)
logger.debug("required depots: %s", sorted(depot_plan.required))
logger.debug("shared depots: %s", sorted(depot_plan.shared))
logger.debug("expected buildid: %s", expected_build_id)
manifest_path = library.steamapps / f"appmanifest_{metadata.appid}.acf"
log.file_contents("Manifest before run", manifest_path)
logger.info("Downloading via depotdownloader (fast path)...")
log.section("depotdownloader")
returncode = depotdl.download(
appid=metadata.appid,
install_dir=install_target,
username=username,
language=language,
max_downloads=args.max_downloads,
logger=logger,
)
if returncode != 0:
logger.error(
"depotdownloader failed (exit %d) -- not touching the manifest.", returncode
)
logger.info("Run log (send this): %s", log.path)
return 1
log.section("depotdownloader cache")
for depot_id, mid in sorted(
recognize.discover_cached_depot_manifests(install_target).items()
):
logger.debug("depot %s -> manifest %s", depot_id, mid)
recognize.ensure_installdir_correct(library, metadata.appid, install_target)
if not args.skip_steamcmd:
logger.info("Reconciling with steamcmd (validate)...")
log.section("steamcmd app_update validate")
result = recognize.run_steamcmd_validate(metadata.appid, username, logger)
log.file_contents("Manifest after steamcmd", manifest_path)
# Never trust steamcmd's exit code alone -- verify the manifest actually
# reflects a real install before believing it. A "clean" exit has
# produced a manifest steamcmd itself hadn't finished updating before.
if (
not result.crashed_on_install_script
and recognize.manifest_reflects_real_install(
library, metadata.appid, install_target
)
):
# The manifest being valid does not mean steamcmd is why. It can
# already have been correct on arrival while steamcmd failed to even
# log in -- reporting that as "steamcmd finished cleanly" credits a
# step that did nothing and hides a real authentication failure.
if result.returncode == 0:
logger.info("steamcmd finished cleanly -- Steam should show Play.")
else:
logger.warning(
"steamcmd exited %d, but %s is already a complete install "
"-- leaving it as is. Steam should show Play.",
result.returncode,
manifest_path.name,
)
logger.info("Run log: %s", log.path)
return 0
if result.crashed_on_install_script:
logger.info(
"steamcmd hit the known install-script crash; finishing the manifest manually..."
)
else:
logger.info(
"steamcmd exited %d but the manifest doesn't reflect a real install; "
"checking whether it is safe to finish it manually...",
result.returncode,
)
return finish(
log,
library,
metadata,
install_target,
depot_plan,
expected_build_id,
skipped_steamcmd=args.skip_steamcmd,
)

View File

@ -0,0 +1,188 @@
"""Detect the fake "fully installed" state anonymous steamcmd leaves behind.
`steamcmd +login anonymous +app_update <paid appid>` has no licence for the
app. It does not say so. It transfers nothing, prints
Update state (0x0) unknown, progress: 0.00 (0 / 0)
Success! App '284160' fully installed.
exits 0, and writes a manifest claiming StateFlags=4 with SizeOnDisk=0 and an
empty InstalledDepots block. Reproduced on this machine on 2026-09-11.
That manifest is not harmless. A running Steam client reads it, concludes the
app is installed but out of date, and starts downloading the whole game by
itself -- which is exactly what happened, to the tune of 22 GB.
Two outcomes, and only one of them deletes anything:
* **Cold ghost** -- the lie and nothing else. Safe to clear away.
* **Warm ghost** -- the same manifest, but Steam has since staged real content
into `steamapps/downloading/<appid>/`. Those bytes are worth keeping: the
whole point of this tool is to make installs faster, and deleting a partial
download to start over is the opposite. Warm ghosts are routed to
`takeover`, never to `repair`.
"""
from __future__ import annotations
import logging
import time
from dataclasses import dataclass
from pathlib import Path
from steam_installer import recognize, vdf
from steam_installer.library import SteamLibrary
INSTALLED_STATE_FLAG = 4
@dataclass(frozen=True)
class GhostReport:
appid: int
manifest_path: Path
install_dir: Path | None
content_bytes: int
staging_bytes: int
reasons: tuple[str, ...]
@property
def is_ghost(self) -> bool:
return bool(self.reasons)
@property
def is_warm(self) -> bool:
"""Steam has staged real content for this app; it must not be deleted."""
return self.staging_bytes > 0
def staging_size(library: SteamLibrary, appid: int) -> int:
staged = library.steamapps / "downloading" / str(appid)
if not staged.is_dir():
return 0
return sum(f.stat().st_size for f in staged.rglob("*") if f.is_file())
def _install_dir(library: SteamLibrary, app_state: dict) -> Path | None:
installdir = app_state.get("installdir")
if not isinstance(installdir, str) or not installdir:
return None
return library.common / installdir
def inspect(library: SteamLibrary, appid: int) -> GhostReport:
"""Classify `appid` in `library`. An empty `reasons` means it is not a ghost.
Every condition is required. They are deliberately a conjunction: a real
install fails several of them at once, and a single `or` anywhere in this
chain is the difference between cleaning up a lie and deleting someone's
game.
"""
manifest_path = library.steamapps / f"appmanifest_{appid}.acf"
empty = GhostReport(appid, manifest_path, None, 0, 0, ())
if not manifest_path.is_file():
return empty
try:
app_state = recognize.read_app_state(manifest_path)
except vdf.VdfParseError:
return empty
if str(app_state.get("appid", "")) != str(appid):
return empty
install_dir = _install_dir(library, app_state)
content_bytes = (
recognize.measure_content_size(install_dir)
if install_dir is not None and install_dir.is_dir()
else 0
)
staged = staging_size(library, appid)
known = GhostReport(appid, manifest_path, install_dir, content_bytes, staged, ())
state_flags = app_state.get("StateFlags", "")
if not (str(state_flags).isdigit() and int(state_flags) & INSTALLED_STATE_FLAG):
return known
depots = app_state.get("InstalledDepots")
if depots:
return known
if str(app_state.get("SizeOnDisk", "0")) != "0":
return known
if content_bytes:
return known
# Our own downloader's cache means a real run is in progress against this
# directory; an empty install dir mid-download is not a ghost.
if install_dir is not None and recognize.discover_cached_depot_manifests(
install_dir
):
return known
return GhostReport(
appid,
manifest_path,
install_dir,
content_bytes,
staged,
(
f"manifest claims StateFlags={state_flags} (installed)",
"InstalledDepots is empty",
"SizeOnDisk is 0",
"no game content on disk",
),
)
def scan(libraries: list[SteamLibrary]) -> list[GhostReport]:
"""Every ghost across every library, checked one manifest at a time."""
found: list[GhostReport] = []
for library in libraries:
if not library.steamapps.is_dir():
continue
for manifest in sorted(library.steamapps.glob("appmanifest_*.acf")):
digits = manifest.stem.removeprefix("appmanifest_")
if not digits.isdigit():
continue
report = inspect(library, int(digits))
if report.is_ghost:
found.append(report)
return found
def repair(
report: GhostReport, logger: logging.Logger, *, now_unix: int | None = None
) -> list[Path]:
"""Clear a COLD ghost away. Returns the paths it touched.
Refuses a warm ghost outright: those bytes belong to `takeover`.
"""
if not report.is_ghost:
raise ValueError(f"appid {report.appid} is not a ghost; refusing to touch it")
if report.is_warm:
raise ValueError(
f"appid {report.appid} has {report.staging_bytes / 1e9:.1f} GB of staged "
"Steam content. That is a partial download, not a ghost to delete -- "
"install it normally so the bytes are reused."
)
stamp = int(time.time()) if now_unix is None else now_unix
touched: list[Path] = []
# Rename rather than unlink: reversible, atomic, and it leaves the evidence
# on disk if the diagnosis was somehow wrong.
backup = report.manifest_path.with_name(
f"{report.manifest_path.name}.ghost-{stamp}"
)
report.manifest_path.rename(backup)
logger.info("Moved bogus manifest to %s", backup)
touched.append(backup)
if report.install_dir is not None and report.install_dir.is_dir():
try:
# rmdir, never rmtree: the kernel refuses a non-empty directory, so
# a real install cannot be destroyed here even if inspect() were wrong.
report.install_dir.rmdir()
except OSError as exc:
logger.warning("Left %s in place: %s", report.install_dir, exc)
else:
logger.info("Removed empty %s", report.install_dir)
touched.append(report.install_dir)
return touched

View File

@ -1,22 +1,46 @@
"""Resolve a game name to a Steam AppID via the public store-search endpoint.
"""Resolve a game name to a Steam AppID.
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.
Two endpoints, tried in order, because the obvious one does not work here:
1. `steamcommunity.com/actions/SearchApps/<term>` -- an undocumented but stable
community-side search. Verified working from this machine; "BeamNG" returns
exactly `284160 BeamNG.drive`.
2. `store.steampowered.com/api/storesearch/` -- the storefront API. It
TLS-rejects scripted clients from at least some networks (confirmed: even
its bare homepage fails the handshake for plain curl/urllib here, while
every other Steam domain works -- storefront-specific bot detection, not an
outage). Kept as a fallback, never relied on.
`ISteamApps/GetAppList` is deliberately not used: it now answers
`404 Method 'GetAppList' not found in interface 'ISteamApps'`.
Either way this is best-effort. search() can fail, and callers fall back to
asking for a numeric AppID rather than treating a search failure as fatal.
"""
from __future__ import annotations
import json
import time
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"
COMMUNITY_SEARCH_URL = "https://steamcommunity.com/actions/SearchApps/{term}"
STORE_SEARCH_URL = "https://store.steampowered.com/api/storesearch/?term={term}&cc=us"
# urllib's default identifies itself as Python-urllib, which Steam's edge
# sometimes refuses outright. A plain browser UA gets a normal response.
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) steam-game-installer"
DEFAULT_TIMEOUT = 15.0
# DNS here fails transiently often enough to lose roughly one lookup in three.
# A search that dies on a blip sends the user off to find an AppID by hand for
# no reason, so retry briefly before giving up on a backend.
ATTEMPTS = 3
RETRY_DELAY = 1.0
@dataclass
@ -30,19 +54,80 @@ class ResolveError(Exception):
class SearchUnavailable(Exception):
"""The store search endpoint couldn't be reached (network/TLS block, not a code bug)."""
"""Neither search endpoint could 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 _fetch_json(url: str, timeout: float, *, attempts: int = ATTEMPTS) -> object:
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
last: Exception = RuntimeError("no attempts made")
for attempt in range(attempts):
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.loads(response.read())
except (urllib.error.URLError, TimeoutError, OSError) as exc:
last = exc
if attempt + 1 < attempts:
# Looked up on the module, not bound as a default, so tests can
# replace it without waiting out the real delay.
time.sleep(RETRY_DELAY)
raise last
def _search_community(term: str, timeout: float) -> list[SearchResult]:
"""Community endpoint. Returns a bare JSON list; appids arrive as strings."""
payload = _fetch_json(COMMUNITY_SEARCH_URL.format(term=term), timeout)
if not isinstance(payload, list):
raise TypeError(f"unexpected community search payload: {type(payload)}")
return [
SearchResult(appid=int(item["appid"]), name=item["name"])
for item in payload
if str(item.get("appid", "")).isdigit()
]
def _search_store(term: str, timeout: float) -> list[SearchResult]:
"""Storefront endpoint. Returns {"items": [{"id": int, "name": str}, ...]}."""
payload = _fetch_json(STORE_SEARCH_URL.format(term=term), timeout)
if not isinstance(payload, dict):
raise TypeError(f"unexpected store search payload: {type(payload)}")
return [
SearchResult(appid=int(item["id"]), name=item["name"])
for item in payload.get("items", [])
]
def search(name: str, *, timeout: float = DEFAULT_TIMEOUT) -> list[SearchResult]:
"""Candidate matches for `name`, newest-working backend first. No auth needed."""
term = urllib.parse.quote(name)
failures: list[str] = []
for label, backend in (
("steamcommunity", _search_community),
("store.steampowered", _search_store),
):
try:
return backend(term, timeout)
except (
urllib.error.URLError,
TimeoutError,
OSError,
TypeError,
ValueError,
KeyError,
) as exc:
failures.append(f"{label}: {exc}")
raise SearchUnavailable("; ".join(failures))
def exact_match(results: list[SearchResult], name: str) -> SearchResult | None:
"""The one result whose title is exactly `name`, case-insensitively.
Steam's own ranking puts "Portal 2" above "Portal", so preferring an exact
title is the difference between typing a full name and getting the sequel.
Ambiguous only in theory: if two apps share a title we refuse to guess.
"""
wanted = name.strip().casefold()
hits = [result for result in results if result.name.strip().casefold() == wanted]
return hits[0] if len(hits) == 1 else None
def prompt_confirm(results: list[SearchResult]) -> SearchResult:

View File

@ -0,0 +1,72 @@
"""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,
)

View File

@ -0,0 +1,118 @@
"""Adopt content the Steam client already downloaded instead of refetching it.
Steam stages an in-progress download into `steamapps/downloading/<appid>/`,
laid out exactly like the finished game (confirmed on a live BeamNG.drive
staging tree: `Bin64/`, `BinLinux/`, `campaigns/`, `content/`), and commits it
into `steamapps/common/<installdir>/` when it finishes.
This tool exists to make installs faster. Throwing away tens of gigabytes the
user already waited for, to start again from zero, would make it slower. So
when a staged tree exists, hardlink it into the install directory first and
let depotdownloader do the rest.
That works because depotdownloader verifies what is already on disk before
fetching: `ContentDownloader.cs` runs `Util.ValidateSteam3FileChecksums()` on
an existing file and skips it entirely when `neededChunks.Count == 0`. It
needs no prior `.DepotDownloader` state to do this, so adopted files count.
Hardlinks, not moves, and not copies. The staged tree keeps its entries until
`finalize.finish` clears it at the very end, so a failed run still leaves Steam
able to resume its own download -- which a move would destroy. Linking costs no
extra disk, where a copy of a 47 GB tree would need 47 GB.
The two trees share inodes, so depotdownloader patching a partial file in place
(it seeks and writes into the existing file rather than replacing it) rewrites
Steam's copy too. That is not a hazard, it is the point: both names converge on
the same corrected content, so whichever downloader finishes the job, the other
one's view is already right. Steam chunk-validates on resume regardless.
This does mean the staged bytes are not a pristine backup. Nothing is deleted,
but they are not frozen either -- on ext4 there is no reflink to get both.
"""
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from pathlib import Path
from steam_installer.library import SteamLibrary
@dataclass(frozen=True)
class Staged:
appid: int
staging_dir: Path
install_dir: Path
file_count: int
bytes_staged: int
@dataclass(frozen=True)
class Adoption:
linked: int
skipped: int
failed: int
bytes_adopted: int
def find_staged(library: SteamLibrary, appid: int, install_dir: Path) -> Staged | None:
"""Steam's in-progress download for `appid`, or None if there isn't one."""
staging_dir = library.steamapps / "downloading" / str(appid)
if not staging_dir.is_dir():
return None
files = [f for f in staging_dir.rglob("*") if f.is_file() and not f.is_symlink()]
if not files:
return None
return Staged(
appid=appid,
staging_dir=staging_dir,
install_dir=install_dir,
file_count=len(files),
bytes_staged=sum(f.stat().st_size for f in files),
)
def adopt(staged: Staged, logger: logging.Logger) -> Adoption:
"""Hardlink the staged tree into the install directory. Originals survive.
Never overwrites a file that is already in place: an existing file is
either content this tool put there or content Steam committed, and
depotdownloader will hash-check both anyway.
"""
linked = skipped = failed = 0
adopted_bytes = 0
for source in sorted(staged.staging_dir.rglob("*")):
if not source.is_file() or source.is_symlink():
continue
relative = source.relative_to(staged.staging_dir)
destination = staged.install_dir / relative
if destination.exists():
skipped += 1
continue
destination.parent.mkdir(parents=True, exist_ok=True)
try:
os.link(source, destination)
except OSError as exc:
# Not fatal: depotdownloader simply downloads whatever we failed to
# adopt. Losing a link is slower, never wrong.
if failed == 0:
logger.warning("Could not hardlink %s: %s", relative, exc)
failed += 1
else:
linked += 1
adopted_bytes += source.stat().st_size
if failed:
logger.warning("%d staged file(s) could not be adopted.", failed)
logger.info(
"Adopted %.2f GB from Steam's staging tree (%d linked, %d already present).",
adopted_bytes / 1e9,
linked,
skipped,
)
return Adoption(
linked=linked, skipped=skipped, failed=failed, bytes_adopted=adopted_bytes
)

View File

@ -0,0 +1,112 @@
"""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)

View File

@ -1,15 +1,32 @@
"""Shared test setup.
"""Shared test setup and fixtures.
`test_module_is_runnable_as_a_script` runs `python -m steam_installer.cli` in a
subprocess. Without the hook below, coverage collected in that child is thrown
away and the `__main__` guard looks uncovered.
The Steam-tree fixtures live here rather than in one test module because
several files need them, and importing a fixture across test modules confuses
both pytest and the linter.
"""
import logging
import os
import pathlib
import pytest
from steam_installer import (
appinfo,
cli,
config,
depotdl,
deps,
recognize,
runlog,
vdf,
)
from steam_installer.library import SteamLibrary
@pytest.fixture
def coverage_subprocess_env():
@ -19,3 +36,98 @@ def coverage_subprocess_env():
env["COVERAGE_PROCESS_START"] = str(root / "pyproject.toml")
env["PYTHONPATH"] = str(root) + os.pathsep + env.get("PYTHONPATH", "")
return env
GHOST_ACF = """"AppState"
{
\t"appid"\t\t"284160"
\t"universe"\t\t"1"
\t"name"\t\t"BeamNG.drive"
\t"StateFlags"\t\t"4"
\t"installdir"\t\t"BeamNG.drive"
\t"LastUpdated"\t\t"0"
\t"SizeOnDisk"\t\t"0"
\t"StagingSize"\t\t"0"
\t"buildid"\t\t"24617469"
\t"DownloadType"\t\t"1"
\t"BytesToDownload"\t\t"0"
\t"BytesDownloaded"\t\t"0"
\t"TargetBuildID"\t\t"24617469"
\t"InstalledDepots"
\t{
\t}
\t"UserConfig"
\t{
\t\t"language"\t\t"english"
\t}
}
"""
@pytest.fixture
def library(tmp_path):
lib = SteamLibrary(tmp_path / "Steam")
lib.steamapps.mkdir(parents=True)
lib.common.mkdir(parents=True)
return lib
def _write(library, appid, text):
path = library.steamapps / f"appmanifest_{appid}.acf"
path.write_text(text)
return path
def _real_install(library, appid=475150, installdir="RealGame", size="13908166765"):
"""A manifest shaped like the genuinely installed apps in a live library."""
_write(
library,
appid,
vdf.dumps(
"AppState",
{
"appid": str(appid),
"StateFlags": "4",
"installdir": installdir,
"SizeOnDisk": size,
"InstalledDepots": {"475151": {"manifest": "123"}},
},
),
)
content = library.common / installdir
content.mkdir(parents=True, exist_ok=True)
(content / "game.pak").write_bytes(b"x" * 4096)
return content
@pytest.fixture
def isolated_cli(tmp_path, monkeypatch):
monkeypatch.setattr(runlog, "LOG_DIR", tmp_path / "state")
monkeypatch.setattr(config, "CONFIG_DIR", tmp_path / "cfg")
monkeypatch.setattr(config, "CONFIG_PATH", tmp_path / "cfg" / "config")
monkeypatch.delenv(config.ENV_VAR, raising=False)
monkeypatch.setattr(deps.shutil, "which", lambda name: f"/usr/bin/{name}")
monkeypatch.setattr(recognize, "steam_client_pids", list)
yield
logger = logging.getLogger(runlog.LOGGER_NAME)
for handler in list(logger.handlers):
logger.removeHandler(handler)
handler.close()
@pytest.fixture
def cli_steam(tmp_path, monkeypatch, isolated_cli):
library = SteamLibrary(tmp_path / "Steam")
library.steamapps.mkdir(parents=True)
library.common.mkdir(parents=True)
monkeypatch.setattr(cli, "find_steam_root", lambda: library.path)
monkeypatch.setattr(cli, "list_libraries", lambda root: [library])
monkeypatch.setattr(
appinfo,
"get_metadata",
lambda appid: appinfo.AppMetadata(appid, "BeamNG.drive", "BeamNG.drive"),
)
monkeypatch.setattr(
depotdl, "download", lambda **kw: pytest.fail("must not download")
)
return library

View File

@ -12,7 +12,7 @@ import sys
import pytest
from steam_installer import appinfo, cli, recognize, resolve, runlog, vdf
from steam_installer import appinfo, cli, depotdl, deps, recognize, runlog, vdf
from steam_installer.library import SteamLibrary
@ -53,21 +53,23 @@ def steam(tmp_path, monkeypatch):
monkeypatch.setattr(cli, "find_steam_root", lambda: root)
monkeypatch.setattr(cli, "list_libraries", lambda r: [library])
monkeypatch.setattr(cli, "pick_install_target", lambda libs, d: install_dir)
monkeypatch.setattr(cli.shutil, "which", lambda name: f"/usr/bin/{name}")
monkeypatch.setattr(deps.shutil, "which", lambda name: f"/usr/bin/{name}")
monkeypatch.setattr(
cli.appinfo,
appinfo,
"get_metadata",
lambda appid: appinfo.AppMetadata(appid, "KCD2", "KingdomComeDeliverance2"),
)
monkeypatch.setattr(
cli.appinfo,
appinfo,
"get_depot_plan",
lambda appid, language: appinfo.DepotPlan({"1771303"}, {"228989"}),
)
monkeypatch.setattr(cli.appinfo, "get_build_id", lambda appid: "23914554")
monkeypatch.setattr(appinfo, "get_build_id", lambda appid: "23914554")
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [])
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [])
monkeypatch.setattr(cli.recognize, "steam_client_pids", lambda: [])
monkeypatch.setattr("builtins.input", lambda *a: "y")
# Prompting is tty-gated now, and pytest's stdin is not a tty.
monkeypatch.setattr(cli, "_is_interactive", lambda args: True)
return library, install_dir
@ -75,12 +77,12 @@ ARGV = ["--appid", "1771300", "--username", "u", "--language", "english"]
def _stub_download(monkeypatch, returncode=0):
monkeypatch.setattr(cli.depotdl, "download", lambda **kw: returncode)
monkeypatch.setattr(depotdl, "download", lambda **kw: returncode)
def _stub_steamcmd(monkeypatch, returncode, crashed=False):
monkeypatch.setattr(
cli.recognize,
recognize,
"run_steamcmd_validate",
lambda appid, username, logger: recognize.ValidateResult(
completed=returncode == 0,
@ -112,7 +114,7 @@ def test_refuses_when_a_required_depot_never_downloaded(steam, monkeypatch):
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=8)
monkeypatch.setattr(
cli.appinfo,
appinfo,
"get_depot_plan",
lambda appid, language: appinfo.DepotPlan({"1771303", "9999999"}, set()),
)
@ -133,13 +135,15 @@ def test_refuses_when_depotdownloader_fails(steam, monkeypatch):
assert app_state["StateFlags"] == "1026"
def test_refuses_before_downloading_when_steam_is_running(steam, monkeypatch):
"""Steam owns the manifest while it runs; refuse up front rather than after
an hour of downloading."""
library, _ = steam
monkeypatch.setattr(cli.recognize, "steam_client_pids", lambda: [4242])
def test_declining_to_close_steam_aborts_before_downloading(steam, monkeypatch):
"""Steam owns the manifest while it runs. The tool offers to close it, but a
"no" must stop the run rather than download for an hour and lose the write."""
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [4242])
monkeypatch.setattr(
"builtins.input", lambda *a: "n" if "Steam is running" in a[0] else "y"
)
called = []
monkeypatch.setattr(cli.depotdl, "download", lambda **kw: called.append(1) or 0)
monkeypatch.setattr(depotdl, "download", lambda **kw: called.append(1) or 0)
assert cli.main(ARGV) == 1
assert called == []
@ -165,10 +169,10 @@ def test_clean_steamcmd_run_short_circuits(steam, monkeypatch):
)
return recognize.ValidateResult(True, False, 0)
monkeypatch.setattr(cli.recognize, "run_steamcmd_validate", fake_validate)
monkeypatch.setattr(recognize, "run_steamcmd_validate", fake_validate)
called = []
monkeypatch.setattr(
cli.recognize,
recognize,
"finish_manifest_manually",
lambda **kw: called.append(1),
)
@ -205,10 +209,10 @@ def test_a_complete_install_after_a_failed_steamcmd_is_not_credited_to_it(
)
return recognize.ValidateResult(True, False, 5)
monkeypatch.setattr(cli.recognize, "run_steamcmd_validate", fake_validate)
monkeypatch.setattr(recognize, "run_steamcmd_validate", fake_validate)
called = []
monkeypatch.setattr(
cli.recognize, "finish_manifest_manually", lambda **kw: called.append(1)
recognize, "finish_manifest_manually", lambda **kw: called.append(1)
)
assert cli.main(ARGV) == 0
@ -221,7 +225,7 @@ def test_a_complete_install_after_a_failed_steamcmd_is_not_credited_to_it(
def test_user_declining_confirmation_aborts(steam, monkeypatch):
monkeypatch.setattr("builtins.input", lambda *a: "n")
called = []
monkeypatch.setattr(cli.depotdl, "download", lambda **kw: called.append(1) or 0)
monkeypatch.setattr(depotdl, "download", lambda **kw: called.append(1) or 0)
assert cli.main(ARGV) == 1
assert called == []
@ -230,7 +234,7 @@ def test_unhandled_error_returns_nonzero_and_names_the_log(steam, monkeypatch, c
def boom(**kwargs):
raise RuntimeError("depotdownloader exploded")
monkeypatch.setattr(cli.depotdl, "download", boom)
monkeypatch.setattr(depotdl, "download", boom)
assert cli.main(ARGV) == 1
assert "Run log" in capsys.readouterr().out
@ -268,43 +272,11 @@ def test_missing_manifest_with_steamcmd_blames_steamcmd(steam, monkeypatch, caps
assert "steamcmd never ran far enough" in capsys.readouterr().out
def test_require_tool_exits_when_binary_missing(monkeypatch, capsys):
monkeypatch.setattr(cli.shutil, "which", lambda name: None)
with pytest.raises(SystemExit):
cli._require_tool("depotdownloader", "See ~/depotdownloader.")
assert "not found on PATH" in capsys.readouterr().err
def test_resolve_appid_uses_search_when_no_appid(monkeypatch):
monkeypatch.setattr(
cli.resolve, "search", lambda name: [resolve.SearchResult(1771300, "KCD2")]
)
monkeypatch.setattr(cli.resolve, "prompt_confirm", lambda results: results[0])
args = cli._build_parser().parse_args(["kingdom", "--username", "u"])
assert cli._resolve_appid(args) == 1771300
def test_resolve_appid_exits_when_search_unavailable(monkeypatch, capsys):
"""store.steampowered.com blocks scripted clients on some networks; tell the
user to pass --appid rather than dying with a traceback."""
def boom(name):
raise resolve.SearchUnavailable("tls blocked")
monkeypatch.setattr(cli.resolve, "search", boom)
args = cli._build_parser().parse_args(["kingdom", "--username", "u"])
with pytest.raises(SystemExit):
cli._resolve_appid(args)
assert "pass --appid" in capsys.readouterr().err
def test_language_defaults_to_english_when_prompt_is_empty(steam, monkeypatch):
seen = {}
monkeypatch.setattr("builtins.input", lambda *a: "y" if "Proceed" in a[0] else "")
monkeypatch.setattr(
cli.appinfo,
appinfo,
"get_depot_plan",
lambda appid, language: (
seen.setdefault("language", language)
@ -328,8 +300,10 @@ def test_reports_the_known_install_script_crash(steam, monkeypatch, capsys):
assert "known install-script crash" in capsys.readouterr().out
def test_reports_cleared_staging(steam, monkeypatch, capsys):
library, _ = steam
def test_adopts_staged_content_then_clears_it(steam, monkeypatch, capsys):
"""Steam's staging tree is adopted into the install dir before downloading,
and only cleared once the install is finished -- never discarded up front."""
library, install_dir = steam
staged = library.steamapps / "downloading" / "1771300"
staged.mkdir(parents=True)
(staged / "big.pak").write_bytes(b"x" * 2_000_000)
@ -337,7 +311,12 @@ def test_reports_cleared_staging(steam, monkeypatch, capsys):
_stub_steamcmd(monkeypatch, returncode=8)
assert cli.main(ARGV) == 0
assert "stale Steam staging data" in capsys.readouterr().out
out = capsys.readouterr().out
assert "Hardlinking it" in out
assert "now-redundant Steam staging data" in out
# Adopted, not copied: the file is one inode with two names.
assert (install_dir / "big.pak").stat().st_size == 2_000_000
def test_fails_when_written_manifest_does_not_read_back_as_installed(
@ -348,7 +327,7 @@ def test_fails_when_written_manifest_does_not_read_back_as_installed(
_stub_download(monkeypatch)
_stub_steamcmd(monkeypatch, returncode=8)
monkeypatch.setattr(
cli.recognize, "manifest_reflects_real_install", lambda *a, **kw: False
recognize, "manifest_reflects_real_install", lambda *a, **kw: False
)
assert cli.main(ARGV) == 1

View File

@ -0,0 +1,51 @@
"""The CLI front door: turning one free-form argument into a resolved target.
test_cli.py covers the download/recognize decision logic; test_cli_steam.py
covers ghosts, usernames and the Steam client. This file covers detection and
the modes that deliberately change nothing.
"""
from steam_installer import cli, deps, target
from tests.conftest import GHOST_ACF
def test_a_bare_appid_resolves_and_reports_without_changing_anything(cli_steam, capsys):
assert cli.main(["--dry-run", "284160"]) == 0
out = capsys.readouterr().out
assert "BeamNG.drive (appid 284160, matched by appid)" in out
assert "nothing was changed" in out
def test_a_steam_url_resolves(cli_steam, capsys):
assert cli.main(["--dry-run", "https://steamcommunity.com/app/284160/guides/"]) == 0
assert "matched by url" in capsys.readouterr().out
def test_a_dry_run_reports_staged_bytes_it_would_adopt(cli_steam, capsys):
staged = cli_steam.steamapps / "downloading" / "284160"
staged.mkdir(parents=True)
(staged / "part.pak").write_bytes(b"x" * 4096)
assert cli.main(["--dry-run", "284160"]) == 0
assert "would be adopted, not re-downloaded" in capsys.readouterr().out
def test_a_dry_run_names_a_ghost_manifest(cli_steam, capsys):
(cli_steam.steamapps / "appmanifest_284160.acf").write_text(GHOST_ACF)
assert cli.main(["--dry-run", "284160"]) == 0
assert "GHOST manifest" in capsys.readouterr().out
def test_an_ambiguous_name_exits_two(cli_steam, monkeypatch):
def boom(text, appid, *, interactive):
raise target.TargetError("Ambiguous name")
monkeypatch.setattr(target, "resolve_target", boom)
assert cli.main(["--dry-run", "witcher"]) == 2
def test_a_missing_dependency_exits_one(cli_steam, monkeypatch, capsys):
monkeypatch.setattr(deps.shutil, "which", lambda name: None)
assert cli.main(["--dry-run", "284160"]) == 1
assert "depotdownloader" in capsys.readouterr().out

View File

@ -0,0 +1,205 @@
"""What the CLI does around a real install: ghosts, usernames, the Steam client.
Split from test_cli_modes.py to keep both files under the repo's 250-line cap.
"""
import pytest
from steam_installer import appinfo, cli, config, depotdl, ghost, recognize
from tests.conftest import GHOST_ACF
def test_a_cold_ghost_blocks_an_install_and_names_the_fix(cli_steam, capsys):
"""Installing over a fabricated manifest is how Steam was tricked into
re-downloading in the first place; stop and say what to run."""
(cli_steam.steamapps / "appmanifest_284160.acf").write_text(GHOST_ACF)
assert cli.main(["--yes", "284160", "--username", "u"]) == 1
assert "./run.sh --repair-ghosts" in capsys.readouterr().out
def test_a_warm_ghost_does_not_block_an_install(cli_steam, monkeypatch):
"""Staged bytes are the whole reason to run this tool, not a blocker."""
(cli_steam.steamapps / "appmanifest_284160.acf").write_text(GHOST_ACF)
staged = cli_steam.steamapps / "downloading" / "284160"
staged.mkdir(parents=True)
(staged / "part.pak").write_bytes(b"x" * 4096)
reached = []
monkeypatch.setattr(depotdl, "download", lambda **kw: reached.append(1) or 1)
monkeypatch.setattr(
appinfo, "get_depot_plan", lambda a, l: appinfo.DepotPlan(set(), set())
)
monkeypatch.setattr(appinfo, "get_build_id", lambda a: "1")
cli.main(["--yes", "284160", "--username", "u"])
assert reached == [1]
def test_repair_ghosts_clears_a_cold_ghost(cli_steam, capsys):
(cli_steam.steamapps / "appmanifest_284160.acf").write_text(GHOST_ACF)
assert cli.main(["--repair-ghosts"]) == 0
assert not (cli_steam.steamapps / "appmanifest_284160.acf").exists()
assert "Ghost: appid 284160" in capsys.readouterr().out
def test_repair_ghosts_refuses_to_discard_a_warm_ghosts_download(cli_steam, capsys):
(cli_steam.steamapps / "appmanifest_284160.acf").write_text(GHOST_ACF)
staged = cli_steam.steamapps / "downloading" / "284160"
staged.mkdir(parents=True)
(staged / "part.pak").write_bytes(b"x" * 4096)
assert cli.main(["--repair-ghosts"]) == 0
assert (cli_steam.steamapps / "appmanifest_284160.acf").exists()
assert (staged / "part.pak").exists()
assert "nothing is deleted" in capsys.readouterr().out
def test_repair_ghosts_says_so_when_there_is_nothing_to_do(cli_steam, capsys):
assert cli.main(["--repair-ghosts"]) == 0
assert "No ghost installs found" in capsys.readouterr().out
def test_repair_ghosts_needs_no_target(cli_steam):
"""It is the one mode that runs without naming a game."""
assert cli.main(["--repair-ghosts"]) == 0
def test_a_saved_username_removes_the_need_for_the_flag(cli_steam, monkeypatch):
config.save_username("saved-user")
seen = {}
monkeypatch.setattr(
depotdl,
"download",
lambda **kw: seen.setdefault("username", kw["username"]) or 1,
)
monkeypatch.setattr(
appinfo, "get_depot_plan", lambda a, l: appinfo.DepotPlan(set(), set())
)
monkeypatch.setattr(appinfo, "get_build_id", lambda a: "1")
cli.main(["--yes", "284160"])
assert seen["username"] == "saved-user"
def test_no_username_anywhere_fails_with_an_explanation(cli_steam, capsys):
assert cli.main(["--yes", "284160"]) == 1
assert "No Steam username available" in capsys.readouterr().out
def test_a_non_interactive_run_without_yes_does_not_start_a_download(cli_steam, capsys):
"""A piped invocation never asked for a 50 GB download; refuse rather than
assume."""
assert cli.main(["284160", "--username", "u"]) == 1
assert "use --yes" in capsys.readouterr().out
def test_language_defaults_to_english_when_not_interactive(cli_steam, monkeypatch):
seen = {}
monkeypatch.setattr(
appinfo,
"get_depot_plan",
lambda a, language: (
seen.setdefault("language", language) or appinfo.DepotPlan(set(), set())
),
)
monkeypatch.setattr(appinfo, "get_build_id", lambda a: "1")
monkeypatch.setattr(depotdl, "download", lambda **kw: 1)
cli.main(["--yes", "284160", "--username", "u"])
assert seen["language"] == "english"
def test_nothing_to_do_at_all_is_a_usage_error():
with pytest.raises(SystemExit):
cli.main(["--username", "u"])
def test_a_ghost_for_a_different_app_does_not_block_this_one(cli_steam, monkeypatch):
(cli_steam.steamapps / "appmanifest_999.acf").write_text(
GHOST_ACF.replace('"appid"\t\t"284160"', '"appid"\t\t"999"')
)
monkeypatch.setattr(depotdl, "download", lambda **kw: 1)
monkeypatch.setattr(
appinfo, "get_depot_plan", lambda a, l: appinfo.DepotPlan(set(), set())
)
monkeypatch.setattr(appinfo, "get_build_id", lambda a: "1")
assert cli.main(["--yes", "284160", "--username", "u"]) == 1
def _installable(monkeypatch, library):
monkeypatch.setattr(
appinfo, "get_depot_plan", lambda a, l: appinfo.DepotPlan(set(), set())
)
monkeypatch.setattr(appinfo, "get_build_id", lambda a: "1")
monkeypatch.setattr(depotdl, "download", lambda **kw: 1)
def test_declining_the_shutdown_prompt_stops_the_run(cli_steam, monkeypatch):
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [42])
monkeypatch.setattr(cli, "_is_interactive", lambda args: True)
monkeypatch.setattr(
"builtins.input", lambda *a: "n" if "Steam is running" in a[0] else "y"
)
monkeypatch.setattr(
depotdl, "download", lambda **kw: pytest.fail("must not download")
)
assert cli.main(["284160", "--username", "u", "--language", "english"]) == 1
def test_steam_is_closed_and_reopened_around_the_install(cli_steam, monkeypatch):
"""It was running before, so it is running after -- whatever the outcome."""
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [42])
monkeypatch.setattr(ghost.recognize, "steam_client_pids", lambda: [42])
events = []
monkeypatch.setattr(
cli.flow.steamctl, "stop", lambda logger: events.append("stop") or True
)
monkeypatch.setattr(
cli.flow.steamctl, "start", lambda logger: events.append("start")
)
_installable(monkeypatch, cli_steam)
assert cli.main(["--yes", "284160", "--username", "u"]) == 1
assert events == ["stop", "start"]
def test_a_steam_that_refuses_to_exit_aborts_the_run(cli_steam, monkeypatch, capsys):
"""Never escalate to a signal: a hung client is the user's to deal with."""
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [42])
def refuse(logger):
raise cli.flow.steamctl.SteamStillRunning("Steam is still running after 60s")
monkeypatch.setattr(cli.flow.steamctl, "stop", refuse)
monkeypatch.setattr(
depotdl, "download", lambda **kw: pytest.fail("must not download")
)
assert cli.main(["--yes", "284160", "--username", "u"]) == 1
assert "still running" in capsys.readouterr().out
def test_accepting_the_shutdown_prompt_closes_and_reopens_steam(cli_steam, monkeypatch):
"""The interactive path: asked, answered yes, Steam cycled around the run."""
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [42])
monkeypatch.setattr(cli, "_is_interactive", lambda args: True)
monkeypatch.setattr("builtins.input", lambda *a: "y")
events = []
monkeypatch.setattr(
cli.flow.steamctl, "stop", lambda logger: events.append("stop") or True
)
monkeypatch.setattr(
cli.flow.steamctl, "start", lambda logger: events.append("start")
)
_installable(monkeypatch, cli_steam)
assert cli.main(["284160", "--username", "u", "--language", "english"]) == 1
assert events == ["stop", "start"]

View File

@ -0,0 +1,95 @@
"""Username persistence and its precedence order."""
import pytest
from steam_installer import config
@pytest.fixture(autouse=True)
def isolated_config(tmp_path, monkeypatch):
"""Never read or write the real ~/.config during a test run."""
monkeypatch.setattr(config, "CONFIG_DIR", tmp_path / "cfg")
monkeypatch.setattr(config, "CONFIG_PATH", tmp_path / "cfg" / "config")
monkeypatch.delenv(config.ENV_VAR, raising=False)
def test_explicit_username_wins_over_everything(monkeypatch):
monkeypatch.setenv(config.ENV_VAR, "from_env")
config.save_username("from_file")
assert config.resolve_username("explicit", interactive=False) == "explicit"
def test_env_wins_over_the_saved_file(monkeypatch):
monkeypatch.setenv(config.ENV_VAR, "from_env")
config.save_username("from_file")
assert config.resolve_username(None, interactive=False) == "from_env"
def test_a_blank_env_var_does_not_shadow_the_saved_file(monkeypatch):
monkeypatch.setenv(config.ENV_VAR, " ")
config.save_username("from_file")
assert config.resolve_username(None, interactive=False) == "from_file"
def test_the_saved_file_is_used_when_nothing_else_is_given():
config.save_username("saved")
assert config.resolve_username(None, interactive=False) == "saved"
def test_saving_creates_the_directory_and_locks_the_file_down():
config.save_username("someone")
assert config.CONFIG_PATH.read_text() == "username=someone\n"
assert config.CONFIG_PATH.stat().st_mode & 0o777 == 0o600
def test_saving_twice_replaces_rather_than_appends():
config.save_username("first")
config.save_username("second")
assert config.load_username() == "second"
def test_load_returns_none_when_nothing_is_saved():
assert config.load_username() is None
def test_load_ignores_other_keys_and_malformed_lines():
config.CONFIG_DIR.mkdir(parents=True)
config.CONFIG_PATH.write_text("# a comment\nnot-a-pair\nother=x\nusername=real\n")
assert config.load_username() == "real"
def test_an_empty_username_value_reads_as_unset():
config.CONFIG_DIR.mkdir(parents=True)
config.CONFIG_PATH.write_text("username=\n")
assert config.load_username() is None
def test_prompting_saves_the_answer(monkeypatch):
monkeypatch.setattr("builtins.input", lambda *a: " typed ")
assert config.resolve_username(None, interactive=True) == "typed"
assert config.load_username() == "typed"
def test_an_empty_answer_is_refused(monkeypatch):
monkeypatch.setattr("builtins.input", lambda *a: "")
with pytest.raises(config.ConfigError, match="No Steam username entered"):
config.resolve_username(None, interactive=True)
def test_non_interactive_with_nothing_available_explains_the_options():
with pytest.raises(config.ConfigError, match="--username"):
config.resolve_username(None, interactive=False)
def test_a_line_with_no_separator_is_skipped_before_a_valid_one():
"""`partition` returns an empty separator for a bare line; that must not be
mistaken for a key with an empty value."""
config.CONFIG_DIR.mkdir(parents=True)
config.CONFIG_PATH.write_text("username\nusername=real\n")
assert config.load_username() == "real"
def test_a_config_file_with_no_username_key_reads_as_unset():
config.CONFIG_DIR.mkdir(parents=True)
config.CONFIG_PATH.write_text("other=x\n# nothing relevant here\n")
assert config.load_username() is None

View File

@ -0,0 +1,31 @@
"""The external-binary check. Moved here from test_cli.py with the code it covers."""
import pytest
from steam_installer import deps
def test_nothing_missing_when_both_tools_are_on_path(monkeypatch):
monkeypatch.setattr(deps.shutil, "which", lambda name: f"/usr/bin/{name}")
assert deps.missing_tools(skip_steamcmd=False) == []
deps.require(skip_steamcmd=False)
def test_steamcmd_is_not_required_when_it_is_skipped(monkeypatch):
monkeypatch.setattr(
deps.shutil, "which", lambda name: None if name == "steamcmd" else "/usr/bin/dd"
)
assert deps.missing_tools(skip_steamcmd=True) == []
assert deps.missing_tools(skip_steamcmd=False) == ["steamcmd"]
def test_missing_tool_raises_with_the_command_that_fixes_it(monkeypatch):
monkeypatch.setattr(deps.shutil, "which", lambda name: None)
with pytest.raises(deps.DependencyError) as excinfo:
deps.require(skip_steamcmd=False)
message = str(excinfo.value)
assert "depotdownloader" in message
assert "steamcmd" in message
assert "./install.sh" in message

View File

@ -0,0 +1,159 @@
"""The fake-install detector.
The anchor test uses the real manifest `steamcmd +login anonymous +app_update
284160` wrote on 2026-09-11 -- a paid app it had no licence for, reported as
"fully installed" after transferring nothing. The negatives are built from the
field signatures of the nine genuinely installed apps in the same library,
because the only failure mode that matters here is deleting a real install.
Shared fixtures (`library`, `GHOST_ACF`, `_write`, `_real_install`) live in
conftest.py; the repair side lives in test_ghost_repair.py.
"""
import pytest
from steam_installer import ghost, vdf
from steam_installer.library import SteamLibrary
from tests.conftest import GHOST_ACF, _real_install, _write
def test_the_real_anonymous_steamcmd_manifest_is_detected(library):
_write(library, 284160, GHOST_ACF)
(library.common / "BeamNG.drive").mkdir()
report = ghost.inspect(library, 284160)
assert report.is_ghost
assert not report.is_warm
assert "InstalledDepots is empty" in report.reasons
assert "no game content on disk" in report.reasons
def test_a_missing_content_directory_is_still_a_ghost(library):
"""The directory need not exist at all -- only the lie has to."""
_write(library, 284160, GHOST_ACF)
assert ghost.inspect(library, 284160).is_ghost
def test_a_real_install_is_never_a_ghost(library):
_real_install(library)
report = ghost.inspect(library, 475150)
assert not report.is_ghost
assert report.content_bytes == 4096
def test_content_on_disk_alone_disqualifies_a_ghost(library):
"""The interlock that matters: even a manifest that looks exactly like the
fake one is not a ghost if there are real bytes behind it."""
_write(library, 284160, GHOST_ACF)
content = library.common / "BeamNG.drive"
content.mkdir()
(content / "game.pak").write_bytes(b"x" * 1024)
assert not ghost.inspect(library, 284160).is_ghost
def test_a_nonzero_size_on_disk_disqualifies_a_ghost(library):
_write(
library, 284160, GHOST_ACF.replace('"SizeOnDisk"\t\t"0"', '"SizeOnDisk"\t\t"9"')
)
assert not ghost.inspect(library, 284160).is_ghost
def test_listed_depots_disqualify_a_ghost(library):
_write(
library,
284160,
GHOST_ACF.replace(
'\t"InstalledDepots"\n\t{\n\t}',
'\t"InstalledDepots"\n\t{\n\t\t"284161"\n\t\t{\n\t\t\t"manifest"\t\t"1"\n\t\t}\n\t}',
),
)
assert not ghost.inspect(library, 284160).is_ghost
@pytest.mark.parametrize("flags", ["1026", "2", "0", "notanumber", ""])
def test_a_manifest_not_claiming_installed_is_not_a_ghost(library, flags):
"""Without bit 4 the manifest is not claiming anything is installed, so
there is no lie to clean up -- 1026 is a normal mid-download state."""
_write(
library,
284160,
GHOST_ACF.replace('"StateFlags"\t\t"4"', f'"StateFlags"\t\t"{flags}"'),
)
assert not ghost.inspect(library, 284160).is_ghost
def test_state_flags_six_still_counts_as_claiming_installed(library):
"""6 is 4|2 -- installed, update required. Every genuinely installed app in
a real library carries it, so the bit test must not be an equality test."""
_write(
library, 284160, GHOST_ACF.replace('"StateFlags"\t\t"4"', '"StateFlags"\t\t"6"')
)
assert ghost.inspect(library, 284160).is_ghost
def test_a_missing_manifest_is_not_a_ghost(library):
assert not ghost.inspect(library, 284160).is_ghost
def test_a_manifest_for_a_different_appid_is_ignored(library):
_write(
library, 284160, GHOST_ACF.replace('"appid"\t\t"284160"', '"appid"\t\t"999"')
)
assert not ghost.inspect(library, 284160).is_ghost
def test_a_manifest_without_an_installdir_is_not_a_ghost(library):
_write(library, 284160, GHOST_ACF.replace('\t"installdir"\t\t"BeamNG.drive"\n', ""))
report = ghost.inspect(library, 284160)
assert report.install_dir is None
assert report.is_ghost
def test_our_own_downloader_state_disqualifies_a_ghost(library):
"""An empty install dir mid-run is not a ghost; .DepotDownloader proves a
real download is in progress against it."""
_write(library, 284160, GHOST_ACF)
cache = library.common / "BeamNG.drive" / ".DepotDownloader"
cache.mkdir(parents=True)
(cache / "284161_999.manifest").write_bytes(b"x")
assert not ghost.inspect(library, 284160).is_ghost
def test_staged_content_makes_a_ghost_warm(library):
_write(library, 284160, GHOST_ACF)
staged = library.steamapps / "downloading" / "284160"
staged.mkdir(parents=True)
(staged / "part.pak").write_bytes(b"x" * 2048)
report = ghost.inspect(library, 284160)
assert report.is_ghost
assert report.is_warm
assert report.staging_bytes == 2048
def test_scan_finds_only_the_ghost(library):
_write(library, 284160, GHOST_ACF)
_real_install(library)
(library.steamapps / "appmanifest_notanumber.acf").write_text(GHOST_ACF)
assert [r.appid for r in ghost.scan([library])] == [284160]
def test_scan_skips_a_library_with_no_steamapps(tmp_path):
assert ghost.scan([SteamLibrary(tmp_path / "nope")]) == []
def test_an_unparseable_manifest_is_not_a_ghost(library, monkeypatch):
"""A manifest we cannot read is not a manifest we may act on."""
_write(library, 284160, "this is not vdf {{{")
def boom(path):
raise vdf.VdfParseError("unbalanced braces", 0)
monkeypatch.setattr(ghost.recognize, "read_app_state", boom)
assert not ghost.inspect(library, 284160).is_ghost

View File

@ -0,0 +1,74 @@
"""Clearing a ghost away, and every case where it must refuse to.
Split from test_ghost.py to keep both files under the repo's 250-line cap.
"""
import logging
import pytest
from steam_installer import ghost
from tests.conftest import GHOST_ACF, _real_install, _write
LOGGER = logging.getLogger("test-ghost-repair")
def test_repair_moves_the_manifest_aside_and_removes_the_empty_directory(library):
_write(library, 284160, GHOST_ACF)
content = library.common / "BeamNG.drive"
content.mkdir()
report = ghost.inspect(library, 284160)
touched = ghost.repair(report, LOGGER, now_unix=1757000000)
assert not report.manifest_path.exists()
backup = library.steamapps / "appmanifest_284160.acf.ghost-1757000000"
assert backup.read_text() == GHOST_ACF
assert not content.exists()
assert touched == [backup, content]
def test_repair_refuses_to_delete_a_non_empty_directory(library, caplog):
"""rmdir, never rmtree: the kernel itself is the last line of defence."""
_write(library, 284160, GHOST_ACF)
content = library.common / "BeamNG.drive"
content.mkdir()
report = ghost.inspect(library, 284160)
# Content appears between the check and the repair.
(content / "surprise.pak").write_bytes(b"x")
with caplog.at_level(logging.WARNING):
touched = ghost.repair(report, LOGGER, now_unix=1)
assert content.exists()
assert (content / "surprise.pak").exists()
assert content not in touched
def test_repair_refuses_a_warm_ghost(library):
"""Staged bytes are a real partial download, not a lie to clean up."""
_write(library, 284160, GHOST_ACF)
staged = library.steamapps / "downloading" / "284160"
staged.mkdir(parents=True)
(staged / "part.pak").write_bytes(b"x" * 3000)
report = ghost.inspect(library, 284160)
with pytest.raises(ValueError, match="partial download"):
ghost.repair(report, LOGGER)
assert report.manifest_path.exists()
assert (staged / "part.pak").exists()
def test_repair_refuses_anything_that_is_not_a_ghost(library):
_real_install(library)
report = ghost.inspect(library, 475150)
with pytest.raises(ValueError, match="not a ghost"):
ghost.repair(report, LOGGER)
def test_repair_defaults_its_timestamp_to_now(library):
_write(library, 284160, GHOST_ACF)
touched = ghost.repair(ghost.inspect(library, 284160), LOGGER)
assert touched[0].name.startswith("appmanifest_284160.acf.ghost-")

View File

@ -1,3 +1,10 @@
"""Name -> AppID search, across both backends.
The community endpoint is primary because the storefront one TLS-rejects
scripted clients from this network; these tests pin the fallback order, the
retry, and the exact-title rule that stops "Portal" installing Portal 2.
"""
import io
import json
import urllib.error
@ -6,6 +13,9 @@ import pytest
from steam_installer import resolve
COMMUNITY_PAYLOAD = [{"appid": "1771300", "name": "Kingdom Come: Deliverance II"}]
STORE_PAYLOAD = {"items": [{"id": 1771300, "name": "Kingdom Come: Deliverance II"}]}
class _FakeResponse(io.BytesIO):
def __enter__(self):
@ -15,12 +25,23 @@ class _FakeResponse(io.BytesIO):
return False
def test_search_parses_items(monkeypatch):
payload = {"items": [{"id": 1771300, "name": "Kingdom Come: Deliverance II"}]}
monkeypatch.setattr(
resolve.urllib.request,
"urlopen",
lambda url, timeout: _FakeResponse(json.dumps(payload).encode()),
def _responder(monkeypatch, handler):
"""Route a fake urlopen by URL so each backend can be driven separately."""
seen = []
def fake_urlopen(request, timeout):
seen.append(request.full_url)
return handler(request.full_url)
monkeypatch.setattr(resolve.urllib.request, "urlopen", fake_urlopen)
monkeypatch.setattr(resolve.time, "sleep", lambda _: None)
return seen
def test_community_backend_is_tried_first_and_parses_string_appids(monkeypatch):
"""The community endpoint returns appid as a string, unlike the store one."""
seen = _responder(
monkeypatch, lambda url: _FakeResponse(json.dumps(COMMUNITY_PAYLOAD).encode())
)
results = resolve.search("kingdom come")
@ -28,45 +49,139 @@ def test_search_parses_items(monkeypatch):
assert results == [
resolve.SearchResult(appid=1771300, name="Kingdom Come: Deliverance II")
]
assert "steamcommunity.com" in seen[0]
assert len(seen) == 1
def test_store_backend_is_used_when_the_community_one_fails(monkeypatch):
def handler(url):
if "steamcommunity.com" in url:
raise urllib.error.URLError("dns")
return _FakeResponse(json.dumps(STORE_PAYLOAD).encode())
seen = _responder(monkeypatch, handler)
assert resolve.search("kingdom come")[0].appid == 1771300
assert "store.steampowered.com" in seen[-1]
def test_a_transient_failure_is_retried_rather_than_given_up_on(monkeypatch):
"""DNS here fails intermittently; one blip must not send the user off to
look up an AppID by hand."""
attempts = []
def handler(url):
attempts.append(url)
if len(attempts) == 1:
raise urllib.error.URLError("temporary failure in name resolution")
return _FakeResponse(json.dumps(COMMUNITY_PAYLOAD).encode())
_responder(monkeypatch, handler)
assert resolve.search("kingdom come")[0].appid == 1771300
assert len(attempts) == 2
def test_search_quotes_the_term(monkeypatch):
seen = {}
def fake_urlopen(url, timeout):
seen["url"] = url
return _FakeResponse(b'{"items": []}')
monkeypatch.setattr(resolve.urllib.request, "urlopen", fake_urlopen)
seen = _responder(monkeypatch, lambda url: _FakeResponse(b"[]"))
resolve.search("kingdom come/2")
assert "kingdom%20come/2" in seen["url"] or "kingdom%20come%2F2" in seen["url"]
assert "kingdom%20come/2" in seen[0] or "kingdom%20come%2F2" in seen[0]
def test_search_missing_items_key_returns_empty(monkeypatch):
monkeypatch.setattr(
resolve.urllib.request, "urlopen", lambda url, timeout: _FakeResponse(b"{}")
)
def test_search_sends_an_explicit_user_agent(monkeypatch):
"""urllib's default UA gets refused outright by Steam's edge."""
captured = {}
def fake_urlopen(request, timeout):
captured["ua"] = request.get_header("User-agent")
return _FakeResponse(b"[]")
monkeypatch.setattr(resolve.urllib.request, "urlopen", fake_urlopen)
resolve.search("anything")
assert captured["ua"] == resolve.USER_AGENT
def test_rows_with_a_non_numeric_appid_are_skipped(monkeypatch):
payload = [{"appid": "nope", "name": "Broken"}, *COMMUNITY_PAYLOAD]
_responder(monkeypatch, lambda url: _FakeResponse(json.dumps(payload).encode()))
assert [r.appid for r in resolve.search("x")] == [1771300]
def test_store_missing_items_key_returns_empty(monkeypatch):
def handler(url):
if "steamcommunity.com" in url:
raise urllib.error.URLError("dns")
return _FakeResponse(b"{}")
_responder(monkeypatch, handler)
assert resolve.search("nothing") == []
def test_an_html_error_page_is_a_search_failure_not_a_crash(monkeypatch):
"""A captive portal or block page returns HTML with a 200; that must not
surface as a JSONDecodeError traceback."""
_responder(monkeypatch, lambda url: _FakeResponse(b"<html>nope</html>"))
with pytest.raises(resolve.SearchUnavailable):
resolve.search("kingdom come")
def test_a_dict_payload_falls_through_to_the_store_parser(monkeypatch):
"""The community endpoint returns a list. A dict is the store's shape, so
it is not a crash -- the store parser handles it and finds no items."""
_responder(monkeypatch, lambda url: _FakeResponse(b'{"not": "a list"}'))
assert resolve.search("kingdom come") == []
def test_a_payload_neither_backend_understands_is_a_search_failure(monkeypatch):
_responder(monkeypatch, lambda url: _FakeResponse(b'"just a string"'))
with pytest.raises(resolve.SearchUnavailable):
resolve.search("kingdom come")
@pytest.mark.parametrize(
"exc", [urllib.error.URLError("tls blocked"), TimeoutError("timed out")]
)
def test_search_network_failure_becomes_search_unavailable(monkeypatch, exc):
"""store.steampowered.com is known to reject scripted clients on some
networks -- that is not a code bug, so it gets its own exception type."""
"""Neither endpoint reachable is not a code bug, so it gets its own type."""
def boom(url, timeout):
def boom(url):
raise exc
monkeypatch.setattr(resolve.urllib.request, "urlopen", boom)
_responder(monkeypatch, boom)
with pytest.raises(resolve.SearchUnavailable):
with pytest.raises(resolve.SearchUnavailable, match="steamcommunity"):
resolve.search("kingdom come")
def test_exact_match_beats_steams_own_ranking():
"""Steam ranks Portal 2 above Portal; typing the full name must still win."""
results = [
resolve.SearchResult(620, "Portal 2"),
resolve.SearchResult(400, "Portal"),
]
assert resolve.exact_match(results, "portal").appid == 400
assert resolve.exact_match(results, " PORTAL ").appid == 400
def test_exact_match_returns_none_without_one():
results = [resolve.SearchResult(620, "Portal 2")]
assert resolve.exact_match(results, "Portal") is None
def test_exact_match_refuses_to_pick_between_duplicate_titles():
"""Two apps with the same title is a genuine ambiguity, not a coin flip."""
results = [resolve.SearchResult(1, "Same"), resolve.SearchResult(2, "Same")]
assert resolve.exact_match(results, "Same") is None
def _results():
return [
resolve.SearchResult(appid=1, name="One"),

View File

@ -0,0 +1,58 @@
"""Closing and reopening the Steam client.
Steam is only ever asked to leave politely. A hung client is a reason to stop
and say so, never to escalate to a signal: SIGKILL mid-write is how a manifest
ends up truncated.
"""
import logging
import pytest
from steam_installer import recognize, steamctl
LOGGER = logging.getLogger("test-steamctl")
def test_stop_is_a_no_op_when_steam_is_not_running(monkeypatch):
monkeypatch.setattr(recognize, "steam_client_pids", list)
called = []
monkeypatch.setattr(steamctl.subprocess, "run", lambda *a, **k: called.append(a))
assert steamctl.stop(LOGGER) is False
assert called == []
def test_stop_asks_steam_to_shut_down_and_waits_for_it(monkeypatch):
pids = iter([[42], [42], [], []])
monkeypatch.setattr(recognize, "steam_client_pids", lambda: next(pids))
seen = {}
monkeypatch.setattr(
steamctl.subprocess, "run", lambda cmd, **k: seen.setdefault("cmd", cmd)
)
assert steamctl.stop(LOGGER, sleep=lambda _: None) is True
assert seen["cmd"] == ["steam", "-shutdown"]
def test_stop_gives_up_rather_than_killing_a_client_that_will_not_exit(monkeypatch):
monkeypatch.setattr(recognize, "steam_client_pids", lambda: [42])
monkeypatch.setattr(steamctl.subprocess, "run", lambda *a, **k: None)
with pytest.raises(steamctl.SteamStillRunning, match="42"):
steamctl.stop(LOGGER, timeout=1.0, sleep=lambda _: None)
def test_start_launches_steam_detached(monkeypatch):
seen = {}
def fake_popen(cmd, **kwargs):
seen["cmd"] = cmd
seen["kwargs"] = kwargs
monkeypatch.setattr(steamctl.subprocess, "Popen", fake_popen)
steamctl.start(LOGGER)
assert seen["cmd"] == ["steam"]
assert seen["kwargs"]["start_new_session"] is True

View File

@ -0,0 +1,134 @@
"""Adopting content the Steam client already downloaded.
The bytes in `steamapps/downloading/<appid>/` are a real partial download the
user waited for. A tool whose purpose is speed must reuse them, and must not
destroy them before the install it feeds has actually succeeded.
"""
import logging
import pytest
from steam_installer import takeover
from steam_installer.library import SteamLibrary
LOGGER = logging.getLogger("test-takeover")
@pytest.fixture
def library(tmp_path):
lib = SteamLibrary(tmp_path / "Steam")
lib.steamapps.mkdir(parents=True)
lib.common.mkdir(parents=True)
return lib
def _stage(library, appid, files):
staged = library.steamapps / "downloading" / str(appid)
for name, payload in files.items():
path = staged / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(payload)
return staged
def test_no_staging_directory_means_nothing_to_adopt(library):
assert takeover.find_staged(library, 284160, library.common / "Game") is None
def test_an_empty_staging_directory_means_nothing_to_adopt(library):
(library.steamapps / "downloading" / "284160").mkdir(parents=True)
assert takeover.find_staged(library, 284160, library.common / "Game") is None
def test_find_staged_measures_the_whole_tree(library):
_stage(library, 284160, {"Bin64/game.exe": b"x" * 100, "content/a.zip": b"y" * 50})
staged = takeover.find_staged(library, 284160, library.common / "Game")
assert staged.file_count == 2
assert staged.bytes_staged == 150
def test_adoption_hardlinks_rather_than_moving_or_copying(library):
"""Nothing is destroyed before the install is proven, and a 47 GB tree costs
no extra disk."""
source = _stage(library, 284160, {"Bin64/game.exe": b"x" * 100})
install_dir = library.common / "Game"
install_dir.mkdir()
staged = takeover.find_staged(library, 284160, install_dir)
result = takeover.adopt(staged, LOGGER)
adopted = install_dir / "Bin64" / "game.exe"
assert adopted.read_bytes() == b"x" * 100
assert (source / "Bin64" / "game.exe").exists()
# One inode, two names -- so it cost no extra disk.
assert adopted.stat().st_ino == (source / "Bin64" / "game.exe").stat().st_ino
assert result.linked == 1
assert result.bytes_adopted == 100
assert result.failed == 0
def test_a_patched_file_is_corrected_in_both_trees(library):
"""depotdownloader seeks and writes into an existing file rather than
replacing it. Through a shared inode that also repairs Steam's staged copy,
so whichever downloader finishes, the other one's view is already right."""
source = _stage(library, 284160, {"part.pak": b"old-content"})
install_dir = library.common / "Game"
install_dir.mkdir()
takeover.adopt(takeover.find_staged(library, 284160, install_dir), LOGGER)
# Stand in for depotdownloader: open the adopted file and patch it in place.
with open(install_dir / "part.pak", "r+b") as handle:
handle.seek(0)
handle.write(b"new")
assert (source / "part.pak").read_bytes() == b"new-content"
def test_adoption_never_overwrites_a_file_already_in_place(library):
_stage(library, 284160, {"game.pak": b"staged"})
install_dir = library.common / "Game"
install_dir.mkdir()
(install_dir / "game.pak").write_bytes(b"already here")
staged = takeover.find_staged(library, 284160, install_dir)
result = takeover.adopt(staged, LOGGER)
assert (install_dir / "game.pak").read_bytes() == b"already here"
assert result.skipped == 1
assert result.linked == 0
def test_a_link_failure_is_survivable(library, monkeypatch, caplog):
"""depotdownloader simply fetches whatever could not be adopted, so a failed
link is slower, never wrong."""
_stage(library, 284160, {"a.pak": b"x", "b.pak": b"y"})
install_dir = library.common / "Game"
install_dir.mkdir()
staged = takeover.find_staged(library, 284160, install_dir)
def refuse(src, dst):
raise OSError("cross-device link")
monkeypatch.setattr(takeover.os, "link", refuse)
with caplog.at_level(logging.WARNING):
result = takeover.adopt(staged, LOGGER)
assert result.failed == 2
assert result.linked == 0
def test_symlinks_in_the_staging_tree_are_ignored(library):
staged_dir = _stage(library, 284160, {"real.pak": b"x" * 10})
(staged_dir / "link.pak").symlink_to(staged_dir / "real.pak")
install_dir = library.common / "Game"
install_dir.mkdir()
staged = takeover.find_staged(library, 284160, install_dir)
result = takeover.adopt(staged, LOGGER)
assert staged.file_count == 1
assert result.linked == 1

View File

@ -0,0 +1,178 @@
"""Turning one free-form argument into a confirmed Steam app.
Four shapes have to work -- an AppID, a Steam URL, an exact title and a
partial title -- and the ambiguous cases have to fail rather than guess.
"""
import pytest
from steam_installer import appinfo, resolve, target
def _metadata(appid):
return appinfo.AppMetadata(appid, "BeamNG.drive", "BeamNG.drive")
@pytest.fixture
def steam_knows_the_app(monkeypatch):
monkeypatch.setattr(appinfo, "get_metadata", _metadata)
@pytest.mark.parametrize(
("text", "expected"),
[
("284160", (284160, "appid")),
(" 284160 ", (284160, "appid")),
("https://steamcommunity.com/app/284160/guides/", (284160, "url")),
("https://store.steampowered.com/app/284160/BeamNGdrive/", (284160, "url")),
("https://store.steampowered.com/app/284160", (284160, "url")),
("https://store.steampowered.com/app/284160/?snr=1_7", (284160, "url")),
("steamcommunity.com/app/284160/", (284160, "url")),
("BeamNG.drive", None),
("BeamNG", None),
("0", None),
("https://steamcommunity.com/id/someone/", None),
],
)
def test_parse_literal_recognises_appids_and_urls(text, expected):
assert target.parse_literal(text) == expected
def test_an_appid_is_confirmed_through_steamcmd(steam_knows_the_app):
resolved = target.resolve_target("284160", None, interactive=False)
assert resolved.metadata.appid == 284160
assert resolved.source == "appid"
def test_the_appid_flag_skips_detection_entirely(steam_knows_the_app):
resolved = target.resolve_target("ignored name", 284160, interactive=False)
assert resolved.metadata.appid == 284160
assert resolved.source == "flag"
def test_a_url_resolves_without_searching(monkeypatch, steam_knows_the_app):
def no_search(name):
raise AssertionError("a URL must not trigger a search")
monkeypatch.setattr(resolve, "search", no_search)
resolved = target.resolve_target(
"https://steamcommunity.com/app/284160/guides/", None, interactive=False
)
assert resolved.source == "url"
def test_a_single_search_hit_is_taken(monkeypatch, steam_knows_the_app):
monkeypatch.setattr(
resolve, "search", lambda name: [resolve.SearchResult(284160, "BeamNG.drive")]
)
resolved = target.resolve_target("BeamNG", None, interactive=False)
assert resolved.metadata.appid == 284160
assert resolved.source == "only match"
def test_an_exact_title_wins_over_a_higher_ranked_sequel(monkeypatch):
"""Steam ranks Portal 2 first for "Portal"; typing the full name must not
install the sequel."""
monkeypatch.setattr(
resolve,
"search",
lambda name: [
resolve.SearchResult(620, "Portal 2"),
resolve.SearchResult(400, "Portal"),
],
)
monkeypatch.setattr(
appinfo, "get_metadata", lambda appid: appinfo.AppMetadata(appid, "Portal", "P")
)
resolved = target.resolve_target("Portal", None, interactive=False)
assert resolved.metadata.appid == 400
assert resolved.source == "exact"
def test_an_ambiguous_name_prompts_when_interactive(monkeypatch, steam_knows_the_app):
results = [resolve.SearchResult(1, "Witcher 3"), resolve.SearchResult(2, "Witcher")]
monkeypatch.setattr(resolve, "search", lambda name: results)
monkeypatch.setattr(resolve, "prompt_confirm", lambda r: r[1])
resolved = target.resolve_target("witch", None, interactive=True)
assert resolved.source == "picked"
def test_an_ambiguous_name_fails_closed_when_not_interactive(
monkeypatch, steam_knows_the_app, capsys
):
"""Guessing here is how the wrong 90 GB gets downloaded."""
monkeypatch.setattr(
resolve,
"search",
lambda name: [
resolve.SearchResult(1, "Witcher 3"),
resolve.SearchResult(2, "Witcher 2"),
],
)
with pytest.raises(target.TargetError, match="Ambiguous"):
target.resolve_target("witch", None, interactive=False)
err = capsys.readouterr().err
assert "Witcher 3" in err
assert "Witcher 2" in err
def test_no_matches_is_an_error_not_a_default_pick(monkeypatch):
monkeypatch.setattr(resolve, "search", lambda name: [])
with pytest.raises(target.TargetError, match="No Steam app matches"):
target.resolve_target("kwyjibo", None, interactive=False)
def test_search_being_unavailable_points_at_the_appid_workaround(monkeypatch):
def boom(name):
raise resolve.SearchUnavailable("tls blocked")
monkeypatch.setattr(resolve, "search", boom)
with pytest.raises(target.TargetError, match="numeric AppID"):
target.resolve_target("BeamNG", None, interactive=False)
def test_digits_that_are_not_an_appid_fall_through_to_a_name_search(monkeypatch):
"""A game literally called "2048" exists, so digits are not unambiguous."""
tried = []
def metadata(appid):
tried.append(appid)
if appid == 2048:
raise appinfo.AppInfoError("no such app")
return appinfo.AppMetadata(appid, "2048", "2048")
monkeypatch.setattr(appinfo, "get_metadata", metadata)
monkeypatch.setattr(
resolve, "search", lambda name: [resolve.SearchResult(999, "2048")]
)
resolved = target.resolve_target("2048", None, interactive=False)
assert resolved.metadata.appid == 999
assert tried == [2048, 999]
def test_an_unknown_appid_from_a_url_does_not_fall_through(monkeypatch):
"""A URL cannot also be a game's name, so there is nothing to fall back to."""
def boom(appid):
raise appinfo.AppInfoError("no such app")
monkeypatch.setattr(appinfo, "get_metadata", boom)
with pytest.raises(target.TargetError, match="not a known Steam app"):
target.resolve_target(
"https://store.steampowered.com/app/1/x/", None, interactive=False
)
def test_no_target_at_all_is_an_error():
with pytest.raises(target.TargetError, match="No target given"):
target.resolve_target(None, None, interactive=False)