Compare commits

..

No commits in common. "a32ab66c5aa305997fcb83c1c8fb3d1f670d54b1" and "9b8dc5cb261e83017c4329059e26764493965661" have entirely different histories.

171 changed files with 202 additions and 14446 deletions

View File

@ -32,11 +32,10 @@ jobs:
# requirements.txt); pytest-cov merges the workers' coverage.
- name: Run tests with coverage
run: |
python -m pytest steam_backlog_enforcer/tests/ steam_installer/tests/ \
python -m pytest steam_backlog_enforcer/tests/ \
-n auto \
-p no:sugar \
--cov=steam_backlog_enforcer \
--cov=steam_installer \
--cov-branch \
--cov-fail-under=100 \
-q

View File

@ -1,4 +0,0 @@
c1b6fdd16f07e91313dc3c2ec821965a1aef15c4:_installer_import/steam_installer/proton_pkg.py:generic-api-key:10
cef9fccab8b6ef12f9a97966ab550cd6814c08eb:web/src/sections/setup.test.ts:generic-api-key:8
341bc784acb3922f6c7813a331cf77307ed5af71:steam_backlog_enforcer/tests/test_web_setup.py:generic-api-key:20
341bc784acb3922f6c7813a331cf77307ed5af71:web/src/screens/Setup.test.tsx:generic-api-key:8

View File

@ -18,8 +18,6 @@ repos:
hooks:
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
# The pinned signing key is byte-for-byte what its source served.
exclude: ^steam_installer/data/
- id: end-of-file-fixer
- id: check-yaml
# pnpm 12 writes pnpm-lock.yaml as two YAML documents (the pinned
@ -35,7 +33,7 @@ repos:
- id: debug-statements
- id: name-tests-test
args: [--pytest-test-first]
exclude: ^steam_(backlog_enforcer|installer)/tests/_[a-z_]+\.py$
exclude: ^steam_backlog_enforcer/tests/_[a-z_]+\.py$
- id: check-ast
- id: check-builtin-literals
- id: check-docstring-first
@ -65,16 +63,10 @@ repos:
types: [text]
- id: requirements-sync
name: requirements.txt covers all package imports
entry: python3 scripts/check_requirements_sync.py --package steam_backlog_enforcer
entry: python3 scripts/check_requirements_sync.py
language: system
pass_filenames: false
files: ^(steam_backlog_enforcer/.*\.py|requirements\.txt)$
- id: requirements-sync-installer
name: requirements.txt covers the installer's imports
entry: python3 scripts/check_requirements_sync.py --package steam_installer
language: system
pass_filenames: false
files: ^(steam_installer/.*\.py|requirements\.txt)$
# ===========================================================================
# RUFF - Linter + formatter
@ -122,7 +114,6 @@ repos:
- --disable-error-code=list-item
additional_dependencies:
- types-requests
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time
- leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.9
@ -154,7 +145,6 @@ repos:
# Python 3.15 (removed co_lnotab). Same reason as jobs = 1 in pyproject.
- --jobs=1
- steam_backlog_enforcer
- steam_installer
- scripts/check_requirements_sync.py
- scripts/pylint_symilar_cache.py
# pylint resolves imports in its OWN isolated env, so anything the
@ -167,7 +157,6 @@ repos:
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time
- leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.9
- howlongtobeatpy==1.0.24
- kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
- mcp==2.3.0
- pytest
- requests
@ -230,7 +219,7 @@ repos:
types: [python]
require_serial: true
stages: [manual]
files: ^((steam_backlog_enforcer|steam_installer)/(?!tests/).*|scripts/(check_requirements_sync|pylint_symilar_cache))\.py$
files: ^(steam_backlog_enforcer/(?!tests/).*|scripts/(check_requirements_sync|pylint_symilar_cache))\.py$
args: &pylint_per_file
- --rcfile=pyproject.toml
- --fail-under=10.0
@ -239,15 +228,15 @@ repos:
- <<: *pylint_shard
id: ci-mirror-pylint-tests-1
name: CI mirror pylint (tests helpers + test_[a-h], per-file checks)
files: ^steam_(backlog_enforcer|installer)/tests/(?!test_[i-z]).*\.py$
files: ^steam_backlog_enforcer/tests/(?!test_[i-z]).*\.py$
- <<: *pylint_shard
id: ci-mirror-pylint-tests-2
name: CI mirror pylint (test_[i-r], per-file checks)
files: ^steam_(backlog_enforcer|installer)/tests/test_[i-r][^/]*\.py$
files: ^steam_backlog_enforcer/tests/test_[i-r][^/]*\.py$
- <<: *pylint_shard
id: ci-mirror-pylint-tests-3
name: CI mirror pylint (test_[s-z], per-file checks)
files: ^steam_(backlog_enforcer|installer)/tests/test_[s-z][^/]*\.py$
files: ^steam_backlog_enforcer/tests/test_[s-z][^/]*\.py$
- &pylint_whole_tree
<<: *pylint_shard
id: ci-mirror-pylint-dup
@ -264,7 +253,6 @@ repos:
# duplicate-code speed-up) loud instead of silently slow.
- --enable=duplicate-code,bad-plugin-value
- steam_backlog_enforcer
- steam_installer
- scripts/check_requirements_sync.py
- scripts/pylint_symilar_cache.py
- <<: *pylint_whole_tree
@ -277,12 +265,11 @@ repos:
- --disable=all
- --enable=cyclic-import
- steam_backlog_enforcer
- steam_installer
- scripts/check_requirements_sync.py
- scripts/pylint_symilar_cache.py
- id: ci-mirror-pytest
name: CI mirror (clean-venv pytest, xdist, 100% coverage)
entry: bash scripts/ci_mirror.sh pytest steam_backlog_enforcer/tests/ steam_installer/tests/
entry: bash scripts/ci_mirror.sh pytest steam_backlog_enforcer/tests/
language: system
pass_filenames: false
always_run: true
@ -315,7 +302,7 @@ repos:
# sha512 read as a misspelling of "view".
- --skip=*.json,*.lock,*-lock.yaml,.git,__pycache__,.venv,node_modules
# `lazer` is osu!lazer's own name, not a misspelling of laser.
- --ignore-words-list=fpr,lazer,als,ans,ect,nd,som,sur,te,nam,numer,lew,sie,wil,postion,clen,ther,folow,derrive,ony,tje,noe,theses,crate,doubleclick,wile,tabel,pary,blok,bloc,proces,serwer,parametr,adres,hart,dout,metod,tekst,synonim,grup,mosty,lokal,skalar,milion,nowe,tre,hel,alph
- --ignore-words-list=lazer,als,ans,ect,nd,som,sur,te,nam,numer,lew,sie,wil,postion,clen,ther,folow,derrive,ony,tje,noe,theses,crate,doubleclick,wile,tabel,pary,blok,bloc,proces,serwer,parametr,adres,hart,dout,metod,tekst,synonim,grup,mosty,lokal,skalar,milion,nowe,tre,hel,alph
# ===========================================================================
# SHELLCHECK - Shell script linting
@ -383,8 +370,7 @@ repos:
|package\.json|package-lock\.json|pnpm-lock\.yaml
|Cargo\.(toml|lock)|go\.(mod|sum)
|\.fvmrc|\.nvmrc|\.python-version
|\.github/workflows/.*\.ya?ml
|steam_installer/data/proton-native\.lock)$
|\.github/workflows/.*\.ya?ml)$
- repo: local
hooks:

View File

@ -24,5 +24,4 @@ After running tests fix all coverage gaps and issues, do not ignore unless speci
- coverage: `python3 -m pytest -q`
- coverage-gaps: `coverage-gaps coverage.lcov`
- deploy: `scripts/deploy.sh`
- install-game: `steam_installer/run.sh <appid|url|name>` (the daemon itself runs `python3 -m steam_installer.cli`; docs in `DOCS-steam-installer.md`)
- push: `scripts/check_gate_stamp.sh full && git push` (every manual-stage gate hook, ~3 min, then push). Agents (60 s cap): one call per id of `scripts/check_gate_stamp.sh full --list`: `CAP_MEM=4G CAP_CPU_PCT=20 ~/.claude/scripts/capped.sh timeout 55 scripts/check_gate_stamp.sh step <id>` (each < 55 s; the last stamps the tree), then `git push`.

View File

@ -1,232 +0,0 @@
# Steam game installer
Download an owned Steam game with `depotdownloader` (which saturates a link far
better than the Steam client), then make the Steam client accept the result as
a real install so **Play** works.
```bash
steam_installer/run.sh BeamNG.drive
```
That is the whole thing. `steam_installer/run.sh` installs its own dependencies (`libibus` via
pacman, DepotDownloader from the SteamRE release and the native
Proton described below) on first use, then works out what you meant. It never
runs `steamcmd`: app info comes from Steam's own cache and the tool writes the
manifest itself. All four of these install the same game:
```bash
steam_installer/run.sh 284160 # an AppID
steam_installer/run.sh https://steamcommunity.com/app/284160/guides/ # any Steam URL
steam_installer/run.sh BeamNG.drive # the exact name
steam_installer/run.sh BeamNG # part of the name
```
An exact title always wins, so `steam_installer/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), `--valve-proton` (keep this game on
Valve's Proton for this run), `--map-installed` (see below), `--username`
(remembered after the first run, in `~/.config/steam-game-installer/config`;
never a password).
## Games run on a FOSS Proton
A plain Windows game is mapped to `proton-cachyos-native`, a Proton that
CachyOS builds from source against the host's own libraries. Steam then runs
it with no Steam Linux Runtime container, and Proton Experimental, Steam Linux
Runtime 4.0 and the Steamworks Redistributables are not needed while only such
games are installed (steam-backlog-enforcer removes them then).
- **The tool.** `steam_installer/install_deps.sh` downloads the exact build pinned in
`steam_installer/data/proton-native.lock` from the CachyOS mirror. It checks
the package's `.sig` against the CachyOS key pinned in
`steam_installer/data/cachyos_signing_key.asc` (fingerprint and sources in
`proton_pkg.py`), and its sha256 against the lock. Then it extracts only the
tool folder into `compatibilitytools.d/` and writes a `VERSION` stamp; the
package's `.INSTALL` is never run. A copy already on disk is adopted when
every file matches the package's `.MTREE`. An update is swapped in by rename,
only while Steam and every game are closed. The dependency-freshness gate
checks the lock against `cachyos.db`.
- **Which games.** Only a game proven safe: Windows-only (the app, every depot,
every launch option), no shared depots, no owned DLC depot, not in
AreWeAntiCheatYet's `games.json` (fetched every run, last good copy cached;
no list means nothing is mapped), and not in
`steam_installer/data/compat_overrides.json` (`{"<appid>": "<reason>"}` for a
game that breaks on the native build). Anything else keeps Valve's default,
so it runs exactly as before. The run prints every reason.
- **The mapping.** With Steam closed, the game gets a `CompatToolMapping`
entry in `config/config.vdf` (`"name" "proton-cachyos-native"`, priority
250). The file is edited as text, and none of its other lines is ever logged.
An entry Valve chose (priority 100) is replaced; one you picked is kept.
- **Games already installed.** `steam_installer/run.sh --map-installed` prints the decision
for every installed game and writes nothing; add `--apply` to close Steam and
write the safe ones. `--appids 730,1201270` decides any cached app instead.
Proven live on 2026-11-22 with A Space for the Unbound (1201270). Not tested
yet, so they stay on Valve's default or are fixture-tested only: a game with
shared depots (its from-scratch manifest records `SharedDepots`), an owned DLC
depot, a native Linux game, an anti-cheat game, a global default mapping and a
package update.
**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 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.
## Owned DLC comes down fast too
Some DLC keeps its content under an app id of its own rather than in the
game's depot list -- Cyberpunk 2077's Phantom Liberty is app 2138330, about
25 GB. A depotdownloader run for the game never sees it, and Steam, restarted
onto a manifest without it, downloads all of it at its own pace.
So every DLC in the game's `listofdlc` that has depots of its own gets its own
depotdownloader run into the same install dir. Depotdownloader's licence check
decides ownership: its "not available from this account" is skipped as
expected, any other failure aborts before the manifest is touched. Each DLC
depot is then written into `InstalledDepots` with its `dlcappid`, exactly as
Steam records it.
## Which depotdownloader
Always `~/.local/bin/depotdownloader` (the copy `steam_installer/install_deps.sh` manages) when it
exists, never "whatever is first on PATH". Each depotdownloader binary keeps
its remembered login in its own storage slot, keyed by its path; with an AUR
copy in `/usr/bin` too, a terminal run and a `sudo`'d run (whose PATH lacks
`~/.local/bin`) used different binaries -- one logged in, one prompting for a
password nobody was there to type.
## Ghost installs
Older versions of this tool ran steamcmd. `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
steam_installer/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
Every run writes a full log:
```
~/.local/state/steam-game-installer/run-<timestamp>-<appid>.log
~/.local/state/steam-game-installer/latest.log -> most recent
```
The path is printed at the start and end of every run, and on every error path.
It contains the full argv, exit code and complete output of each subprocess, the
manifest verbatim before and after every write, the depot cache listing,
expected-vs-actual depots, and whether Steam was running. Send `latest.log` when
something goes wrong. `--verbose` mirrors all of it to the console.
Subprocess output is teed through a pty rather than captured, because
depotdownloader only prompts for a password / Steam Guard code when it believes
it is on a terminal — with a plain pipe the prompt never appears and the run looks hung.
## How it works
1. App info (name, installdir, depots, build) is read from Steam's own cache,
`appcache/appinfo.vdf`. An app missing from it fails with the fix: start
Steam once, let it sync, rerun. A DLC missing from it counts as not owned.
2. `depotdownloader` pulls the content (fast path).
Then each owned DLC with depots of its own gets a run of its own.
3. The manifest is finished by hand, or written from scratch with the 15 keys
Steam accepted when none exists, but only when every precondition below
holds. Steam adds `LastOwner`, `UserConfig` and the rest itself.
4. The game is mapped to the native Proton when it is safe (see above).
## Fail-closed preconditions
The tool refuses to mark an app installed, and exits non-zero, unless:
- `depotdownloader` exited 0;
- every required depot has a cached manifest under `.DepotDownloader/`
(required = this app's depots for the chosen language and OS, excluding DLC,
optional and shared depots — KCD2 lists 12 depots but an english/windows
install only ever fetches 3);
- every required depot holds the public gid from Steam's cache, which proves
the build (a differing gid means the cache is stale: start Steam, let it
sync, rerun), or else the manifest carries a matching real `buildid`;
- 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
a steamcmd run that had done nothing at all. A from-scratch manifest is built in
memory and only written once every check has passed.
## Failure modes this encodes
Each of these cost a real debugging session; the tests pin them.
**A wrong `installdir` makes Steam wipe the game.** Steam treated the correctly
downloaded folder as orphaned, deleted it and started a fresh download into the
folder its manifest named. The field is fixed first, as soon as Steam is closed.
**Steam rejects an internally inconsistent manifest.** A file that says
`StateFlags=4` while `BytesDownloaded` (22 GB) still differs from
`BytesToDownload` (92 GB) is self-contradictory; Steam discards the "installed"
claim and resumes downloading. Across every genuinely installed manifest the
counters are equal in pairs and `StagingSize` is `0`. `DownloadType` is *kept* —
it is present on every real install, so removing it is not the fix.
**Staging must be cleared too.** Steam stages chunks in
`steamapps/downloading/<appid>/`. Declaring the app installed while tens of GB
sit there pending makes Steam resume the update. Installed apps have an empty
(4 KB) staging dir.
**Shared depots are not installed depots.** `228989` belongs to app 228980
(Steamworks Common Redistributables); listing it in `InstalledDepots`
contradicts `SharedDepots`.
**`SizeOnDisk` excludes `.DepotDownloader/`** — its cache and staging tree are
not game content and overstate the total by gigabytes.
## Development
The installer shares this repo's gate (ruff, mypy, pylint, bandit, 250-line cap)
and its test run, which enforces **100% of statements and branches** for both
packages (`fail_under = 100`):
```bash
python3 -m pytest -q # both suites, coverage gated
scripts/test_changed.sh # only the tests of changed files
```
The steam-backlog-enforcer daemon runs the installer from this checkout as
`python3 -m steam_installer.cli`; it needs no virtualenv.

View File

@ -186,9 +186,6 @@ with explicit params, a `Progress` reporter and a `Prompter`.
its text search for the same step.
- `result` — `{ok, summary, data?}` exactly once at the end.
`install`'s target, dry run, Valve Proton and result; `repair-ghosts` and its
`game_running` refusal: see [DOCS-web-install.md](DOCS-web-install.md).
## Friction (server/daemon-enforced)
| Command | Phrase (exact) | Extra |

View File

@ -1,106 +0,0 @@
# `install`, `repair-ghosts` and `map-installed` jobs
Part of the web control API ([DOCS-web-control-api.md](DOCS-web-control-api.md));
the TS mirror of the result is `InstallResultData` in `web/src/api/contract.ts`.
All three params are optional (`_command_params.PARAMS["install"]`):
- `target` (string): an AppID, a Steam URL (`…/app/<id>/…`) or a name, as
the installer's own `TARGET` argument. The job resolves it, never the
installer: inside the games allowed today, which are `allowed_games(state)`
plus the approved exceptions (named from the owned records). AppIDs and URLs
are parsed locally; names match exact title first, then substring (case
ignored), with no Steam search. Several matches → a `choice` prompt; no
match, or an id outside that set → the job fails (`locked`) and no
installer runs. The installer only ever gets the checked `--appid`.
Without `target`, the job offers every allowed game not yet fully
installed, approved exceptions included (`choice` when more than one).
- `dry_run` (bool): runs only `steam_installer.cli --appid <id> --dry-run`
and relays its report as `log` lines. No manifest is queued, Steam is not
closed, there is no `steam://` fallback, so it is allowed while a game runs.
An installer failure fails the job (`op_failed`).
- `valve_proton` (bool): passes `--valve-proton` to the installer.
The result `data` is `InstallResultData` `{app_id, dry_run,
fast_install_skipped}` once a game was chosen (else the assignment). The
installer closes Steam, so a real install while a game runs skips the fast
path (`_fast_install._refusal`) and Steam's own download starts:
`fast_install_skipped` is then `"game_running"`, and the UI paints the
`result.game-running` mark on the result (`result.dry-run` for a dry run).
## `repair-ghosts`
`./run.sh repair-ghosts` and the `repair-ghosts` job (Library page, icon
`cmd.repair-ghosts`) run the installer's `--repair-ghosts`
(`main/repair_ghosts.py`): every cold ghost manifest is renamed to
`*.ghost-<unix>` and its empty folder removed; a ghost with staged bytes is
only reported (`DOCS-steam-installer.md`, "Ghost installs"). No params, result
`data` = the assignment, an installer failure is `op_failed`.
The installer does not close Steam here, but it rewrites the library under a
client that may be reading it, so it gets `install`'s guard
(`_steam_restart_guard.game_is_running`).
| Command | Phrase (exact) | Checked |
|---|---|---|
| `repair-ghosts` | `delete ghost manifests` | at `POST /api/jobs` (`_web_jobs._PRECHECKED`), then again in the job |
At `POST /api/jobs` the phrase is checked first (`400 wrong_phrase`), then the
guard (`409 game_running`). Either refusal creates no job. The job re-checks
both, because a game can start in between. The UI paints the
`result.game-running` mark on a `game_running` refusal.
## Proton map: `GET /api/compat` and `map-installed`
`GET /api/compat` (`_compat_view.compat_view`) returns
`{tool, tool_ready, rows}`: one row per installed game, built by
`steam_installer.compat_rows.rows` (the same rows `--map-installed` logs, so
the view cannot disagree with the apply). A row is
`{app_id, name, current, priority, decided, reasons, note, map, changes,
cached}` (`CompatRow` in `web/src/api/contract.ts`); `null` in `current` or
`decided` means Valve's default. Steam's own tools are not rows. An unreadable
Steam, app cache or overrides file is `502 op_failed`.
Deciding parses the ~10 MB app cache, so the payload is kept in memory and
rebuilt only when a file it was decided from changes (`cache_key`: app cache,
`config.vdf`, `libraryfolders.vdf`, every `appmanifest_*.acf`, the overrides,
the tool's `VERSION`, the anti-cheat cache and its 6 h age window). A GET
never waits on the network unless that anti-cheat cache is older.
`./run.sh map-installed` and the `map-installed` job (Library page, view
`#view=compat`, icon `cmd.map-installed`) run the installer's
`--map-installed --apply --yes --appids <ids>` (`main/map_installed.py`). The
apply closes Steam (Steam rewrites `config.vdf` on exit), maps each game the
decision proves safe to the native Proton and starts Steam again, so it refuses
while a game runs (`409 game_running`). The job streams the installer's
output as `log` lines and has a 180 s timer.
Param `appids` (string, optional): comma-separated installed app ids. Absent,
the job maps every game whose row has `changes: true`. Ids that are not
installed, not digits, or an empty list are `400 invalid_params`
(`_compat_view.checked_appids`). The installer gets exactly the ids the phrase
counted, never "everything". The result `data` is `{app_ids: [...]}`.
| Command | Phrase (exact) | Checked |
|---|---|---|
| `map-installed` | `map {appid_count} games`, e.g. `map 3 games` | at `POST /api/jobs` (`_web_jobs._PRECHECKED`), then again in the job |
The count is part of the phrase, so a stale count is a wrong phrase. At
`POST /api/jobs` the ids are checked first (`400 invalid_params`, `502
op_failed` when Steam is unreadable), then the phrase (`400 wrong_phrase`),
then the guard (`409 game_running`). Each refusal creates no job. The UI fills
`{appid_count}` from the same ids (`fillPhrase` in `web/src/commands/catalog.ts`).
The view (`web/src/library/compatTable.ts`, state in `compatState.ts`) has
sortable columns, per-column filters, fuzzy search, a 30 s poll and row
checkboxes for games that change; with none ticked, Map applies to every
visible changing game. Its state lives in the URL hash, keys prefixed `c.`
because the cover grid owns `q` and `sort` in the same hash:
| Key | Meaning |
|---|---|
| `view=compat` | show the Proton map |
| `c.sort=<col>`, `c.dir=asc\|desc` | sort column (`name`, `app_id`, `current`, `decided`, `why`, `changes`) and direction; default `changes` ascending |
| `c.q=<text>` | fuzzy search |
| `c.f.<col>=<text>` | filter: substring for `name` and `why`, exact option for `current`, `decided`, `changes` (`changes` or `same`) |
| `c.f.app_id=<min>..<max>` | app id range, either side optional |

View File

@ -1,8 +1,5 @@
# Steam Backlog Enforcer
This repo is also an alternative Steam frontend: it installs games faster than the
Steam client (`steam_installer`, see [DOCS-steam-installer.md](DOCS-steam-installer.md)).
Forces you to play one Steam game at a time: earn at least one new
achievement in the assigned game before moving on to the next.
@ -87,11 +84,3 @@ Claude Code spawns:
Registration lives in the checked-in [`.mcp.json`](./.mcp.json) (project scope).
Restart Claude Code in this repo and approve the project MCP-server prompt for it
to load. Verify with `claude mcp list`.
## Steam game installer
`steam_installer` (merged in from steam-game-installer) downloads an owned game
with depotdownloader and makes Steam accept it as installed. The daemon runs it
as `python3 -m steam_installer.cli`; by hand use `steam_installer/run.sh <appid|url|name>`.
Dependencies: `steam_installer/install_deps.sh` (run by `install.sh`). Details in
[DOCS-steam-installer.md](DOCS-steam-installer.md).

View File

@ -32,21 +32,6 @@ else
echo "(The rest of this tool is unaffected.)"
fi
# The Steam game installer (steam_installer, in this repo) fast-installs the
# games the daemon assigns: depotdownloader, kuhy-credit and the native Proton.
# Runs as the desktop user (it writes ~/.local and Steam's compatibilitytools.d)
# and is not fatal: without it the daemon falls back to Steam's own download.
echo
echo "Installing the Steam game installer's dependencies..."
INSTALLER_DEPS="$SCRIPT_DIR/steam_installer/install_deps.sh"
if [[ $EUID -eq 0 && -n ${SUDO_USER:-} ]]; then
sudo -u "$SUDO_USER" bash "$INSTALLER_DEPS" \
|| echo "Warning: installer dependencies incomplete (Steam's own download is used)."
else
bash "$INSTALLER_DEPS" \
|| echo "Warning: installer dependencies incomplete (Steam's own download is used)."
fi
# Install the web-UI user unit. No root needed: it serves read-only views and
# needs no privilege. Automated rather than documented, because the whole
# reason this unit exists is that a hand-started server outlived its own code.

View File

@ -1,7 +1,7 @@
[project]
name = "steam-backlog-enforcer"
version = "1.0.0"
description = "Enforce your Steam backlog: one game at a time, tracked with HowLongToBeat data. Also ships steam_installer, a fast Steam game installer."
description = "Enforce your Steam backlog: one game at a time, tracked with HowLongToBeat data"
# 3.11 floor: websockets 17 (and its successors) drop 3.10, and this repo
# tracks newest stable rather than the oldest interpreter still alive.
requires-python = ">=3.14"
@ -21,16 +21,8 @@ dependencies = [
# contract C4); stdlib-only, imported by root from the user site like
# earned-time.
"leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.9",
# kuhy's shared "Created by kuhy" credit, shown at the end of the
# installer's --help (steam_installer).
"kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit",
]
# The installer's console script; the daemon itself runs
# `python3 -m steam_installer.cli` from the checkout.
[project.scripts]
steam-game-installer = "steam_installer.cli:main"
# Optional extras. The `mcp` group is ONLY needed by the MCP server
# (steam_backlog_enforcer._mcp), which Claude Code spawns via a dedicated
# venv (see scripts/setup_mcp.sh / .mcp.json). It is deliberately NOT a core
@ -45,12 +37,7 @@ mcp = ["mcp==2.3.0"]
# to guess. Scoping discovery to the Python package fixes `pip install -e .`
# for the CLI, systemd, AND the dedicated MCP venv.
[tool.setuptools.packages.find]
include = ["steam_backlog_enforcer*", "steam_installer*"]
[tool.setuptools.package-data]
# The pinned Proton lock, its signing key and the compat overrides are read
# at run time through `Path(__file__).parent / "data"`.
steam_installer = ["data/*"]
include = ["steam_backlog_enforcer*"]
# ============================================================================
# RUFF - Fast Python linter and formatter
@ -92,13 +79,6 @@ unfixable = []
# libX11 puts local display sockets in /tmp/.X11-unix; the path is not ours to
# move to a private temp dir (and `# noqa` is banned by pre-commit).
"steam_backlog_enforcer/_desktop_env.py" = ["S108"]
# open_https() allows only https URLs: the scheme is checked just above the
# urlopen call, so the S310 "file:/custom scheme" worry cannot occur there.
"steam_installer/_http.py" = ["S310"]
# The pinned Proton package is fetched from lock.repo or SGI_PROTON_REPO (an
# operator-set local mirror, file:// or http://); the db is sha256-pinned and
# the package sha256- and gpg-verified, so the transport needs no restriction.
"steam_installer/proton_native.py" = ["S310"]
[tool.ruff.lint.pydocstyle]
convention = "google"
@ -106,7 +86,7 @@ convention = "google"
[tool.ruff.lint.isort]
force-single-line = false
force-sort-within-sections = true
known-first-party = ["steam_backlog_enforcer", "steam_installer"]
known-first-party = ["steam_backlog_enforcer"]
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
@ -225,7 +205,7 @@ exclude_dirs = ["tests", ".venv"]
# PYTEST
# ============================================================================
[tool.pytest.ini_options]
testpaths = ["steam_backlog_enforcer/tests", "steam_installer/tests"]
testpaths = ["steam_backlog_enforcer/tests"]
python_files = ["test_*.py", "*_test.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
@ -235,7 +215,6 @@ addopts = [
"--strict-config",
"-ra",
"--cov=steam_backlog_enforcer",
"--cov=steam_installer",
"--cov-branch",
"--cov-report=term-missing",
"--cov-report=lcov",
@ -250,7 +229,7 @@ filterwarnings = [
# COVERAGE
# ============================================================================
[tool.coverage.run]
source = ["steam_backlog_enforcer", "steam_installer"]
source = ["steam_backlog_enforcer"]
branch = true
omit = ["*/__pycache__/*", "*/tests/*", "*/.venv/*"]

View File

@ -1,4 +1,4 @@
# Steam Backlog Enforcer (and steam_installer) — runtime + development dependencies
# Steam Backlog Enforcer — runtime + development dependencies
# Install with: pip install -r requirements.txt
aiohttp==3.14.5
@ -7,7 +7,6 @@ codespell==2.4.3
coverage==7.17.4
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time
howlongtobeatpy==1.0.24
kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit
leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.9
mcp==2.3.0
mypy==2.4.1

View File

@ -18,57 +18,7 @@
set -euo pipefail
readonly UTILS="${UTILS_ROOT:-$HOME/src/utils}"
readonly SHARED_GATE="$UTILS/scripts/check_dependency_freshness.sh"
readonly PACMAN_PARSER="$UTILS/dep_freshness/parsers/pacman_lock.py"
# True when this run must judge the native-Proton lock (a full run, or the lock staged).
needs_pacman_adapter() {
local arg
for arg in "$@"; do
[[ "$arg" == "--all" || "$arg" == *proton-native.lock ]] && return 0
done
return 1
}
# git against the utils checkout. A pre-commit run inherits the committing
# repo's git location variables, which would point these commands at the wrong
# repository, so they are cleared first.
utils_git() {
env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE -u GIT_COMMON_DIR \
-u GIT_PREFIX git -C "$UTILS" "$@"
}
# Print a gate directory that can read the Proton lock, or nothing.
#
# kuhy's ~/src/utils can lag origin/main (local commits not yet pushed, so it
# cannot fast-forward). Then the gate runs a read-only snapshot of utils'
# origin/main from the cache instead: the checkout itself is never touched.
gate_root_for_lock() {
if [[ -f "$PACMAN_PARSER" ]]; then
echo "$UTILS"
return
fi
local sha snapshot
local -a paths=(scripts/check_dependency_freshness.sh dep_freshness)
utils_git cat-file -e origin/main:dep_freshness/parsers/pacman_lock.py 2>/dev/null ||
return 0
sha="$(utils_git rev-parse origin/main)"
snapshot="${XDG_CACHE_HOME:-$HOME/.cache}/steam-game-installer/utils-gate/$sha"
if [[ ! -f "$snapshot/dep_freshness/parsers/pacman_lock.py" ]]; then
rm -rf "$snapshot.tmp"
mkdir -p "$snapshot.tmp"
# The fleet allowlist lives beside the gate, when utils has one.
if utils_git cat-file -e origin/main:dependency-freshness.allowlist.yaml 2>/dev/null; then
paths+=(dependency-freshness.allowlist.yaml)
fi
utils_git archive origin/main "${paths[@]}" | tar -x -C "$snapshot.tmp"
rm -rf "$snapshot"
mv "$snapshot.tmp" "$snapshot"
fi
echo "dependency-freshness: $UTILS lacks the pacman adapter; using its origin/main ${sha:0:12}" >&2
echo "$snapshot"
}
readonly SHARED_GATE="${UTILS_ROOT:-$HOME/src/utils}/scripts/check_dependency_freshness.sh"
main() {
if [[ ! -x "$SHARED_GATE" ]]; then
@ -78,20 +28,7 @@ main() {
exit 1
fi
local root="$UTILS"
# An older utils checkout skips a manifest it has no parser for and exits
# 0, which would wave any Proton pin through. Fail closed instead.
if needs_pacman_adapter "$@"; then
root="$(gate_root_for_lock)"
if [[ -z "$root" ]]; then
echo "Error: $UTILS has no dep_freshness/parsers/pacman_lock.py, so it" >&2
echo " cannot check steam_installer/data/proton-native.lock." >&2
echo " Update it: git -C $UTILS pull --ff-only" >&2
exit 1
fi
fi
exec bash "$root/scripts/check_dependency_freshness.sh" "$@"
exec bash "$SHARED_GATE" "$@"
}
main "$@"

View File

@ -96,21 +96,14 @@ def _top_level_imports(module: Path) -> set[str]:
def _third_party_imports(package_dir: Path, package_name: str) -> set[str]:
"""Return third-party top-level imports across the whole package.
Standard-library modules (via ``sys.stdlib_module_names``), the package's own
name and the repo's sibling packages (``steam_backlog_enforcer`` imports
``steam_installer`` from the same checkout) are filtered out, leaving only
external dependencies.
Standard-library modules (via ``sys.stdlib_module_names``) and the package's
own name are filtered out, leaving only external dependencies.
"""
stdlib = sys.stdlib_module_names
first_party = {
sibling.name
for sibling in package_dir.parent.iterdir()
if (sibling / "__init__.py").is_file()
} | {package_name}
external: set[str] = set()
for module in _iter_package_modules(package_dir):
for name in _top_level_imports(module):
if name not in first_party and name not in stdlib:
if name != package_name and name not in stdlib:
external.add(name)
return external

View File

@ -16,17 +16,23 @@ from __future__ import annotations
import struct
from typing import TYPE_CHECKING, Final
from steam_installer.appinfo_kv import HEADER, MAGIC, read_block, string_table
if TYPE_CHECKING:
from collections.abc import Iterable
from pathlib import Path
from steam_backlog_enforcer._vdf_text import VdfNode
MAGIC: Final = 0x07564429
# "SteamPlay 2.0 Manifests": its extended/app_mappings is Valve's per-game
# tool pick (e.g. a broken native port sent to Proton).
STEAM_PLAY_APP: Final = 891390
_HEADER: Final = 60
# KV type bytes: a nested block, a NUL-terminated string, end of block.
_BLOCK: Final = 0
_STRING: Final = 1
_END: Final = 8
# Fixed-width value types: KV type byte -> struct format.
_SCALARS: Final = {2: "<i", 3: "<f", 4: "<i", 6: "<i", 7: "<Q", 10: "<q"}
def default_path(steam_root: Path) -> Path:
@ -54,7 +60,7 @@ def _parse(buf: bytes, wanted: set[int]) -> dict[int, dict[str, VdfNode]]:
if magic != MAGIC:
msg = f"unsupported appinfo.vdf format {magic:#010x}"
raise ValueError(msg)
strings = string_table(buf, table_offset)
strings = _string_table(buf, table_offset)
apps: dict[int, dict[str, VdfNode]] = {}
pos = 16
while True:
@ -62,7 +68,44 @@ def _parse(buf: bytes, wanted: set[int]) -> dict[int, dict[str, VdfNode]]:
if app_id == 0:
return apps
if app_id in wanted:
data, _ = read_block(buf, pos + 8 + HEADER, strings)
data, _ = _kv(buf, pos + 8 + _HEADER, strings)
inner = data.get("appinfo")
apps[app_id] = inner if isinstance(inner, dict) else data
pos += 8 + size
def _string_table(buf: bytes, offset: int) -> list[str]:
(count,) = struct.unpack_from("<I", buf, offset)
pos = offset + 4
out: list[str] = []
for _ in range(count):
end = buf.index(b"\0", pos)
out.append(buf[pos:end].decode("utf-8", "replace"))
pos = end + 1
return out
def _kv(buf: bytes, pos: int, strings: list[str]) -> tuple[dict[str, VdfNode], int]:
out: dict[str, VdfNode] = {}
while True:
kind = buf[pos]
pos += 1
if kind == _END:
return out, pos
(index,) = struct.unpack_from("<I", buf, pos)
pos += 4
key = strings[index]
if kind == _BLOCK:
out[key], pos = _kv(buf, pos, strings)
elif kind == _STRING:
end = buf.index(b"\0", pos)
out[key] = buf[pos:end].decode("utf-8", "replace")
pos = end + 1
elif kind in _SCALARS:
fmt = _SCALARS[kind]
(value,) = struct.unpack_from(fmt, buf, pos)
out[key] = str(value)
pos += struct.calcsize(fmt)
else:
msg = f"unsupported value type {kind} in appinfo.vdf"
raise ValueError(msg)

View File

@ -72,8 +72,6 @@ CATALOG: Final[dict[str, _Entry]] = {
"hide": _job("library"),
"unhide": _job("library"),
"add-exception": _job("library"),
"repair-ghosts": _job("library"),
"map-installed": _job("library"),
"gaming-status": _view("gaming", "/api/budget"),
"gaming-reset": _job("gaming"),
"gaming-unblock": _job("gaming"),

View File

@ -31,8 +31,6 @@ COMMAND_DESCRIPTIONS: Final[dict[str, str]] = {
"stats": "Show backlog completion-time estimates",
"gaming-status": "Show today's gaming time and block state",
"gaming-reset": "Reset today's gaming counter (root + phrase)",
"repair-ghosts": "Delete the fake 'installed' manifests anonymous steamcmd left",
"map-installed": "Map every safe installed game to the native Proton",
}
# Commands with non-standard arg handling (shown in help but not in COMMANDS).

View File

@ -65,32 +65,6 @@ PARAMS: Final[dict[str, tuple[ParamSpec, ...]]] = {
help="Leave unchecked to keep playing them alongside the new pick.",
),
),
# No target: the picker over every allowed game not yet installed.
"install": (
ParamSpec(
"target",
"AppID, Steam URL or name",
"string",
required=False,
help="Only games allowed today; an ambiguous name asks.",
),
ParamSpec(
"dry_run",
"Dry run",
"bool",
required=False,
default=0,
help="Shows what the installer would do and changes nothing.",
),
ParamSpec(
"valve_proton",
"Valve Proton",
"bool",
required=False,
default=0,
help="Keep the game on Valve's default Proton.",
),
),
"pick-manual": (_APP_ID,),
"abandon-pick": (_APP_ID,),
"add-exception": (
@ -127,16 +101,6 @@ PARAMS: Final[dict[str, tuple[ParamSpec, ...]]] = {
default=0,
),
),
# The rows the UI selected; absent = every installed game that would change.
"map-installed": (
ParamSpec(
"appids",
"App ids",
"string",
required=False,
help="Comma-separated installed app ids.",
),
),
# Not a CLI command: POST /api/backups/{id}/restore runs it as a job.
"restore-backup": (ParamSpec("backup_id", "Backup id", "string"),),
}

View File

@ -1,141 +0,0 @@
"""``GET /api/compat``: every installed game's compat-tool (Proton) decision.
The rows come from the merged installer's own decision code
(``steam_installer.compat_rows``, the same rows ``--map-installed`` logs), so
the view can never disagree with what the apply job does. Deciding parses
Steam's ~10 MB app cache and reads the anti-cheat list, so the answer is kept
in memory and rebuilt only when one of the files it was decided from changes
(apply rewrites config.vdf, an install adds a manifest). The anti-cheat list
is reused from its on-disk cache for :data:`ANTICHEAT_MAX_AGE`: a GET never
waits on the network unless that cache is older.
The apply job (``map-installed``) checks its ids here too: :func:`checked_appids`.
"""
from __future__ import annotations
import threading
import time
from typing import TYPE_CHECKING, Final, cast
from steam_backlog_enforcer._command_params import InvalidParamsError
from steam_backlog_enforcer._web_errors import ApiError
from steam_backlog_enforcer._web_io import Reply, ok
from steam_installer import anticheat, appinfo_cache, compat_decide, compat_map
from steam_installer.compat_apply import TOOL_DIR, Context
from steam_installer.compat_rows import rows
from steam_installer.errors import InstallerError
from steam_installer.library import find_steam_root, list_libraries
if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
from steam_backlog_enforcer._web_io import Request
ANTICHEAT_MAX_AGE: Final = 6 * 3600.0
_lock = threading.Lock()
_memo: dict[str, tuple[tuple[object, ...], dict[str, object]]] = {}
def clear_cache() -> None:
"""Forget the memoised payload (tests)."""
with _lock:
_memo.clear()
def _stat(path: Path) -> tuple[str, int, int] | None:
try:
st = path.stat()
except OSError:
return None
return str(path), st.st_mtime_ns, st.st_size
def cache_key(root: Path) -> tuple[object, ...]:
"""Stats of every file a decision reads, plus the anti-cheat age window."""
paths = [
appinfo_cache.default_path(),
compat_map.config_path(root),
root / "steamapps" / "libraryfolders.vdf",
anticheat.CACHE,
compat_decide.OVERRIDES,
root / TOOL_DIR / "VERSION",
]
for library in list_libraries(root):
paths += sorted(library.steamapps.glob("appmanifest_*.acf"))
return (int(time.time() // ANTICHEAT_MAX_AGE), *(_stat(p) for p in paths))
def compat_payload() -> dict[str, object]:
"""``{tool, tool_ready, rows}``, from memory while no input file changed.
Raises:
InstallerError: Steam's app cache or config.vdf cannot be read.
OSError: No Steam installation.
ValueError: The overrides file is malformed.
"""
root = find_steam_root()
key = cache_key(root)
with _lock:
hit = _memo.get("payload")
if hit is not None and hit[0] == key:
return hit[1]
context = Context(root, anticheat_max_age=ANTICHEAT_MAX_AGE)
payload: dict[str, object] = {
"tool": compat_map.TOOL,
"tool_ready": context.tool_ready,
"rows": [row.to_json() for row in rows(root, context=context)],
}
_memo["payload"] = (key, payload)
return payload
def compat_view(_request: Request) -> Reply:
"""``GET /api/compat``.
Raises:
ApiError: ``op_failed`` when the decision inputs cannot be read.
"""
try:
return ok(compat_payload())
except (InstallerError, OSError, ValueError) as exc:
raise ApiError(str(exc), code="op_failed") from None
def _rows() -> list[dict[str, object]]:
return cast("list[dict[str, object]]", compat_payload()["rows"])
def checked_appids(raw: str | None) -> list[int]:
"""The ids an apply maps: *raw* checked, or every game that would change.
Raises:
InvalidParamsError: *raw* is not comma-separated digits, names a game
that is not installed, or there is nothing to map.
"""
table = _rows()
if raw is None:
ids = [int(str(r["app_id"])) for r in table if r["changes"]]
else:
parts = [part.strip() for part in raw.split(",")]
if not all(part.isdigit() for part in parts):
msg = f"appids must be comma-separated app ids, got {raw!r}"
raise InvalidParamsError(msg)
ids = list(dict.fromkeys(int(part) for part in parts))
known = {r["app_id"] for r in table}
missing = [str(i) for i in ids if i not in known]
if missing:
msg = f"Not installed: {', '.join(missing)}"
raise InvalidParamsError(msg)
if not ids:
msg = "Nothing to map: no installed game would change."
raise InvalidParamsError(msg)
return ids
def phrase_fields(params: Mapping[str, object]) -> dict[str, object]:
"""The ``map-installed`` phrase's slots: how many games the job is given."""
raw = params.get("appids")
return {"appid_count": len(checked_appids(None if raw is None else str(raw)))}

View File

@ -1,7 +1,7 @@
"""Installing games through steam-game-installer, for download speed.
depotdownloader saturates the link far better than the Steam client, and
steam-game-installer (``steam_installer``, in this repo) wraps it so Steam accepts
steam-game-installer (``~/src/steam-game-installer``) wraps it so Steam accepts
the result as a real install. It also adopts whatever Steam already staged, so
taking over a slow client download loses nothing.
@ -189,11 +189,7 @@ def _wait_detached(app_id: int, label: str) -> bool:
def fast_install(
app_id: int,
label: str,
prepare: Callable[[], object] = lambda: None,
*,
valve_proton: bool = False,
app_id: int, label: str, prepare: Callable[[], object] = lambda: None
) -> bool:
"""Install *app_id* with steam-game-installer.
@ -208,7 +204,7 @@ def fast_install(
if app_id in _FAILED:
return False
user = resolve_desktop_user()
installer = installer_path()
installer = installer_path(user)
if installer is None:
logger.warning("steam-game-installer not found; using Steam's download.")
return False
@ -217,7 +213,7 @@ def fast_install(
_echo(f" Fast install of {label} skipped: {reason}.")
return False
cmd = build_cmd(installer, app_id, user, valve_proton=valve_proton)
cmd = build_cmd(installer, app_id, user)
prepare()
if not sys.stdin.isatty():
_spawn_detached(cmd, app_id, label)

View File

@ -1,4 +1,4 @@
"""How the installer (``steam_installer``) is invoked: where, as whom, what argv.
"""How steam-game-installer is invoked: where it lives, as whom, with what argv.
Split out of :mod:`_fast_install`, which runs and reaps the installer; this
half only decides the command line, every choice it would otherwise prompt for
@ -8,32 +8,31 @@ pinned in advance.
from __future__ import annotations
from pathlib import Path
import pwd
import re
from steam_backlog_enforcer._desktop_env import desktop_user_cmd
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH
# The installer ships in this repo (``steam_installer``, a sibling package).
# Tests repoint this at a missing file: it always exists here, and a real run
# closes the user's Steam.
_INSTALLER = Path(__file__).resolve().parents[1] / "steam_installer" / "cli.py"
# The interpreter the daemon itself runs under (see the unit's ExecStart). The
# installer needs ``kuhy_credit``, which lives in the desktop user's site.
_PYTHON = "/usr/bin/python3"
_INSTALLER = Path("src", "steam-game-installer", "run.sh")
# Depot content only: the app itself is ours to choose, the language is not
# worth a prompt nobody is there to answer.
_LANGUAGE = "english"
def installer_path() -> Path | None:
"""The installer's ``cli.py`` inside this checkout, if present.
def installer_path(user: str | None) -> Path | None:
"""steam-game-installer's ``run.sh`` in the desktop user's home, if present.
A checkout is the same for every user, so unlike the old external clone
there is no per-user lookup.
Resolved from the passwd entry rather than ``Path.home()``: the daemon runs
as root, and the installer, its venv and its credentials are per-user.
"""
return _INSTALLER if _INSTALLER.is_file() else None
try:
home = Path(pwd.getpwnam(user).pw_dir) if user else Path.home()
except KeyError:
return None
path = home / _INSTALLER
return path if path.is_file() else None
def steam_account_name() -> str | None:
@ -51,74 +50,19 @@ def steam_account_name() -> str | None:
return match.group(1) if match else None
def build_cmd(
installer: Path,
app_id: int,
user: str | None,
*,
valve_proton: bool = False,
dry_run: bool = False,
) -> list[str]:
"""The installer invocation, dropped to the desktop user when root.
Launched as ``python3 -m steam_installer.cli`` with the checkout on
``PYTHONPATH``: ``sudo`` resets the environment, so it is named in the argv.
*valve_proton* keeps the game on Valve's default Proton; *dry_run* only
reports what the installer would do.
"""
def build_cmd(installer: Path, app_id: int, user: str | None) -> list[str]:
"""The installer invocation, dropped to the desktop user when root."""
cmd = [
"env",
f"PYTHONPATH={installer.parents[1]}",
_PYTHON,
"-m",
"steam_installer.cli",
str(installer),
# install.sh reaches for yay; dependencies are installed once, by hand.
"--no-deps",
"--appid",
str(app_id),
"--yes",
"--language",
_LANGUAGE,
]
if valve_proton:
cmd.append("--valve-proton")
if dry_run:
cmd.append("--dry-run")
account = steam_account_name()
if account:
cmd += ["--username", account]
return desktop_user_cmd(cmd, user)
def _installer_cmd(installer: Path, user: str | None, *flags: str) -> list[str]:
"""``python3 -m steam_installer.cli <flags>``, dropped to the desktop user."""
cmd = [
"env",
f"PYTHONPATH={installer.parents[1]}",
_PYTHON,
"-m",
"steam_installer.cli",
*flags,
]
return desktop_user_cmd(cmd, user)
def build_repair_ghosts_cmd(installer: Path, user: str | None) -> list[str]:
"""The installer's ``--repair-ghosts`` run, dropped to the desktop user.
No AppID: it scans every library for the fake manifests anonymous
steamcmd left and clears only the cold ones (``DOCS-steam-installer.md``).
"""
return _installer_cmd(installer, user, "--repair-ghosts")
def build_map_installed_cmd(
installer: Path, user: str | None, appids: list[int]
) -> list[str]:
"""``--map-installed --apply`` for exactly *appids* (the phrase counted them).
``--yes`` because a job has no tty: the typed phrase was the confirmation,
and the installer would otherwise cancel at its "close Steam?" prompt.
"""
ids = ",".join(str(appid) for appid in appids)
return _installer_cmd(
installer, user, "--map-installed", "--apply", "--yes", "--appids", ids
)

View File

@ -52,10 +52,6 @@ FRICTION: Final[dict[str, Friction]] = {
"uninstall": Friction("uninstall {count} games"),
"reset": Friction("wipe all enforcer state"),
"restore-backup": Friction("restore backup {backup_id}"),
# Checked at POST /api/jobs too (_web_jobs._PRECHECKED), then again by the job.
"repair-ghosts": Friction("delete ghost manifests"),
# appid_count, not count: the UI fills ``count`` with the uninstall count.
"map-installed": Friction("map {appid_count} games"),
}

View File

@ -25,9 +25,6 @@ from steam_backlog_enforcer._steam_state import steam_update_in_progress
logger = logging.getLogger(__name__)
# The refusal of a web job that waits for the game to exit (``game_running``).
GAME_RUNNING_JOB_MSG = "A game is running: this waits until it exits."
def game_is_running() -> bool:
"""Whether a Steam game is currently running.
@ -73,11 +70,10 @@ def assert_safe_to_restart() -> None:
# Matched against /proc cmdlines, so a run started by hand counts exactly like
# one the enforcer spawned. The module name is in the argv of every wrapper
# too (``sudo``, ``env``), which exist the moment Popen returns while the
# Python process follows a moment later, so a Steam launch cannot slip into
# that gap. ``run.sh`` is the by-hand launcher that execs the same module.
_INSTALLER_MARKERS = (b"steam_installer/run.sh", b"steam_installer.cli")
# one the enforcer spawned. run.sh as well as the module it execs: the sudo
# and bash wrappers exist the moment Popen returns, the Python process only a
# moment later, and a Steam launch in that gap would race the shutdown.
_INSTALLER_MARKERS = (b"steam-game-installer/run.sh", b"steam_installer.cli")
def fast_install_running() -> bool:

View File

@ -30,7 +30,6 @@ STATUS_BY_CODE: Final[dict[str, HTTPStatus]] = {
"busy": HTTPStatus.CONFLICT,
"countdown_running": HTTPStatus.CONFLICT,
"not_cancellable": HTTPStatus.CONFLICT,
"game_running": HTTPStatus.CONFLICT,
"pending_lapsed": HTTPStatus.GONE,
"rate_limited": HTTPStatus.TOO_MANY_REQUESTS,
"daemon_unreachable": HTTPStatus.SERVICE_UNAVAILABLE,

View File

@ -11,16 +11,11 @@ refused as ``busy`` because a scan is running.
from __future__ import annotations
from http import HTTPStatus
from typing import TYPE_CHECKING, Any, Final
from typing import TYPE_CHECKING, Any
from steam_backlog_enforcer._backups import list_backups
from steam_backlog_enforcer._command_params import InvalidParamsError, validate_params
from steam_backlog_enforcer._compat_view import phrase_fields
from steam_backlog_enforcer._friction import expected_phrase, phrase_matches
from steam_backlog_enforcer._steam_restart_guard import (
GAME_RUNNING_JOB_MSG,
game_is_running,
)
from steam_backlog_enforcer._web_daemon import confirm_phrase_of
from steam_backlog_enforcer._web_errors import ApiError, from_job_error, not_found
from steam_backlog_enforcer._web_io import Reply, no_content, ok
@ -30,26 +25,14 @@ from steam_backlog_enforcer.jobs._errors import JobError
from steam_backlog_enforcer.jobs._specs import JOB_FLAGS, is_privileged
from steam_backlog_enforcer.jobs._store import create_job
from steam_backlog_enforcer.jobs._view import list_jobs, read_job
from steam_installer.errors import InstallerError
if TYPE_CHECKING:
from collections.abc import Callable, Mapping
from steam_backlog_enforcer._web_io import Request
# The UI's enforce modes onto the job registry's ``demo`` flag; ``restart``
# (demo 0) is the daemon's.
_ENFORCE_MODES = {"demo": 1, "restart": 0}
# Jobs whose phrase and game-running guard are checked here, before a job
# exists, so a refusal never leaves a job behind; the job re-checks both.
_PRECHECKED: Final = frozenset({"repair-ghosts", "map-installed"})
# The phrase slots a prechecked job's template names, from its clean params.
_PHRASE_FIELDS: Final[
dict[str, Callable[[Mapping[str, object]], dict[str, object]]]
] = {"map-installed": phrase_fields}
def _invalid(message: str) -> ApiError:
"""An ``invalid_params`` 400."""
@ -90,44 +73,6 @@ def _job_request(request: Request) -> tuple[str, dict[str, Any], str | None]:
return command, params, phrase
def _phrase_fields(command: str, params: Mapping[str, object]) -> dict[str, object]:
"""The phrase slots for *command*; bad params are a 400, unreadable Steam a 502.
Raises:
ApiError: ``invalid_params`` or ``op_failed``.
"""
fields = _PHRASE_FIELDS.get(command)
if fields is None:
return {}
try:
return fields(params)
except InvalidParamsError as exc:
raise _invalid(str(exc)) from None
except (InstallerError, OSError, ValueError) as exc:
raise ApiError(str(exc), code="op_failed") from None
def _precheck(command: str, params: Mapping[str, object], phrase: str | None) -> None:
"""Refuse a :data:`_PRECHECKED` job before it is created.
The phrase goes first: it is what the user can fix, and it stays
provable while a game runs. Its slots (``map-installed``'s count) come
from the params, so a bad id list is refused before either.
Raises:
ApiError: ``invalid_params``, ``wrong_phrase``, or ``game_running``
while a game runs.
"""
if command not in _PRECHECKED:
return
expected = expected_phrase(command, **_phrase_fields(command, params)) or ""
if not phrase_matches(expected, phrase or ""):
msg = f'Type "{expected}" to run {command}.'
raise ApiError(msg, code="wrong_phrase")
if game_is_running():
raise ApiError(GAME_RUNNING_JOB_MSG, code="game_running")
def jobs_view(_request: Request) -> Reply:
"""``GET /api/jobs`` — newest first, at most 50."""
return ok(list_jobs())
@ -153,7 +98,6 @@ def create_job_view(request: Request) -> Reply:
raise _invalid(str(exc)) from None
if is_privileged(command, clean):
return run_privileged(command, clean, phrase)
_precheck(command, clean, phrase)
try:
job_id = create_job(command, clean, confirm_phrase=phrase)
except JobError as exc:

View File

@ -12,7 +12,6 @@ import re
from typing import TYPE_CHECKING, Final
from steam_backlog_enforcer import (
_compat_view,
_web_art,
_web_daemon,
_web_icon_words,
@ -58,7 +57,6 @@ ROUTES: Final[tuple[_Entry, ...]] = (
_r("GET", "/api/status", _web_views.status_view),
_r("GET", "/api/stats", _web_views.stats_view),
_r("GET", "/api/installed", _web_views.installed_view),
_r("GET", "/api/compat", _compat_view.compat_view),
_r("GET", "/api/library", _web_library.library_view),
_r("GET", "/api/art/{id}", _web_art.art_view),
_r("GET", "/api/commands", _web_views.commands_view),

View File

@ -138,7 +138,6 @@ def install_game(
steam_id: str,
*,
use_steam_protocol: bool = False,
valve_proton: bool = False,
) -> bool:
"""Install a game, through steam-game-installer when it can be used.
@ -146,19 +145,22 @@ def install_game(
below it is the fallback for when it is refused or fails.
When *use_steam_protocol* is True the ``steam://install`` URI handler
is used, so Steam picks the canonical ``installdir`` from its own
metadata (a display-name mismatch causes "Missing game executable").
Falls back to a fabricated appmanifest if the handler is unavailable.
is used, which lets Steam determine the correct install directory from
its own metadata. This avoids mismatches between the display name and
the canonical ``installdir`` that can cause "Missing game executable"
errors. Falls back to writing a fabricated appmanifest if the URI
handler is unavailable.
When False (the default) a minimal appmanifest with StateFlags=1026 is
written directly: no Steam dialog, for non-interactive / daemon use.
When *use_steam_protocol* is False (the default) a minimal
appmanifest with StateFlags=1026 is written directly. This is
suitable for non-interactive / daemon contexts where opening a Steam
dialog is undesirable.
Args:
app_id: Steam application ID.
game_name: Human-readable game name.
steam_id: Steam64 ID of the account that owns the game.
use_steam_protocol: Prefer the ``steam://install`` URI handler.
valve_proton: Keep the game on Valve's default Proton (fast path).
Returns True if the install was triggered successfully.
"""
@ -168,8 +170,9 @@ def install_game(
return ready
# The installer only finishes a manifest it finds: queue a fresh install first.
prepare = partial(_queue_download, app_id, game_name, steam_id)
if fast_install(app_id, label, prepare, valve_proton=valve_proton):
if fast_install(
app_id, label, partial(_queue_download, app_id, game_name, steam_id)
):
return True
# Steam already has a download of its own going: let it carry on, rather
# than overwrite its manifest with the fabricated one below.

View File

@ -13,7 +13,6 @@ JobErrorCode = Literal[
"busy",
"not_cancellable",
"op_failed",
"game_running",
]

View File

@ -33,13 +33,11 @@ from steam_backlog_enforcer.main import (
cmd_list,
cmd_pick,
cmd_pick_manual,
cmd_repair_ghosts,
cmd_reset,
cmd_stats,
cmd_unhide,
cmd_uninstall,
)
from steam_backlog_enforcer.main.map_installed import run_map_installed
from steam_backlog_enforcer.scanning import do_check, do_scan
if TYPE_CHECKING:
@ -106,22 +104,6 @@ def _pick(
return _assignment(state)
def _install(
params: Mapping[str, ParamValue], _progress: Progress, _prompter: Prompter
) -> JobResult:
"""``install``: optional target, dry run and Valve-Proton switch."""
state = State.load()
target = params.get("target")
data = cmd_install(
Config.load(),
state,
target=str(target) if target else None,
dry_run=bool(params.get("dry_run")),
valve_proton=bool(params.get("valve_proton")),
)
return data if data is not None else _assignment(state)
def _enforce_demo(
params: Mapping[str, ParamValue], _progress: Progress, _prompter: Prompter
) -> JobResult:
@ -155,14 +137,6 @@ def _restore_backup(
return {"restored": backup_id, "previous_backup": previous and previous.id}
def _map_installed(
params: Mapping[str, ParamValue], _progress: Progress, _prompter: Prompter
) -> JobResult:
"""``map-installed``: the selected ids, or every game that would change."""
raw = params.get("appids")
return {"app_ids": run_map_installed(None if raw is None else str(raw))}
def _via_daemon(command: str) -> JobHandler:
"""A placeholder for a privileged command: it always refuses."""
@ -183,15 +157,13 @@ HANDLERS: dict[str, JobHandler] = {
"pick": _pick,
"pick-manual": _with_args(cmd_pick_manual, "app_id"),
"abandon-pick": _with_args(cmd_abandon_pick, "app_id"),
"install": _install,
"install": _cli(cmd_install),
"uninstall": _cli(cmd_uninstall),
"hide": _cli(cmd_hide),
"unhide": _cli(cmd_unhide),
"add-exception": _add_exception,
"reset": _cli(cmd_reset),
"restore-backup": _restore_backup,
"repair-ghosts": _cli(cmd_repair_ghosts),
"map-installed": _map_installed,
"stats": _cli(cmd_stats),
"list": _cli(cmd_list),
"enforce": _enforce_demo,

View File

@ -56,8 +56,6 @@ JOB_FLAGS: Final[dict[str, JobFlags]] = {
"add-exception": JobFlags(),
"reset": JobFlags(),
"restore-backup": JobFlags(),
"repair-ghosts": JobFlags(),
"map-installed": JobFlags(),
"stats": JobFlags(mutating=False, cancellable=True),
"list": JobFlags(mutating=False, cancellable=True),
# Only the demo runs as a job (see is_privileged).

View File

@ -60,7 +60,6 @@ from steam_backlog_enforcer.main.install import (
cmd_unhide,
cmd_uninstall,
)
from steam_backlog_enforcer.main.map_installed import cmd_map_installed
from steam_backlog_enforcer.main.misc import (
cmd_block_gaming,
cmd_buy_dlc,
@ -74,7 +73,6 @@ from steam_backlog_enforcer.main.picks import (
cmd_pick,
cmd_pick_manual,
)
from steam_backlog_enforcer.main.repair_ghosts import cmd_repair_ghosts
from steam_backlog_enforcer.main.status import cmd_list, cmd_status
from steam_backlog_enforcer.scanning import do_check, do_scan
@ -113,10 +111,8 @@ __all__ = [
"cmd_install",
"cmd_installed",
"cmd_list",
"cmd_map_installed",
"cmd_pick",
"cmd_pick_manual",
"cmd_repair_ghosts",
"cmd_reset",
"cmd_serve",
"cmd_setup",
@ -146,8 +142,6 @@ _HANDLERS: dict[str, Callable[[Config, State], object]] = {
"stats": cmd_stats,
"gaming-status": cmd_gaming_status,
"gaming-reset": cmd_gaming_reset,
"repair-ghosts": cmd_repair_ghosts,
"map-installed": cmd_map_installed,
}
# Descriptions live in _command_help (the web catalog reads them too); the

View File

@ -1,134 +0,0 @@
"""Which game ``install`` may touch, and the installer's dry run.
The web ``install`` takes a target the way the installer does (AppID, Steam
URL or name), but the enforcer resolves it, inside the set of games allowed
today, before the installer runs. The installer then only ever gets the
checked ``--appid``: handing it the raw text would let its own Steam search
pick an app this check never saw. Names are matched locally, so a refused
game costs no network call and an ambiguous one is a choice, never a guess.
"""
from __future__ import annotations
import subprocess
from typing import TYPE_CHECKING
from steam_backlog_enforcer._actions import allowed_games
from steam_backlog_enforcer._desktop_env import resolve_desktop_user
from steam_backlog_enforcer._echo import _echo
from steam_backlog_enforcer._fast_install_cmd import build_cmd, installer_path
from steam_backlog_enforcer._owned_apps_cache import load_owned_records
from steam_backlog_enforcer._prompter import PromptOption, current_prompter
from steam_backlog_enforcer._whitelist_locking import get_approved_exception_ids
from steam_backlog_enforcer.jobs._errors import JobError
from steam_installer.target import parse_literal
if TYPE_CHECKING:
from pathlib import Path
from steam_backlog_enforcer.config import Config, State
# The dry run only reads Steam's app cache and library folders; repair-ghosts
# only scans them and renames a few manifests.
_DRY_RUN_TIMEOUT_SECONDS = 50
def install_candidates(config: Config, state: State) -> list[tuple[int, str]]:
"""Every game ``install`` may install today, as ``(app_id, name)``.
The enforcer's allowed games (assignment first, then manual picks) plus
the approved exceptions, named from the owned-games records.
"""
games = allowed_games(state)
known = {aid for aid, _ in games}
records = load_owned_records(config.steam_id) or []
names = {int(r["app_id"]): str(r.get("name") or "") for r in records}
for app_id in sorted(get_approved_exception_ids() - known):
games.append((app_id, names.get(app_id, "")))
return games
def _refuse(text: str) -> JobError:
"""The refusal for a game that is not allowed today."""
return JobError(f"{text!r} is not a game allowed today.", code="locked")
def resolve_target(text: str, candidates: list[tuple[int, str]]) -> tuple[int, str]:
"""Resolve *text* to one of *candidates*.
Raises:
JobError: ``locked`` when the target is not an allowed game.
"""
literal = parse_literal(text)
if literal is not None:
game = next((g for g in candidates if g[0] == literal[0]), None)
if game is None:
raise _refuse(text)
return game
wanted = text.strip().casefold()
exact = [g for g in candidates if g[1].casefold() == wanted]
matches = exact or [g for g in candidates if wanted in g[1].casefold()]
if not matches:
raise _refuse(text)
if len(matches) == 1:
return matches[0]
options = [PromptOption(str(aid), name) for aid, name in matches]
picked = int(current_prompter().choice("Install which game", options))
return next(g for g in matches if g[0] == picked)
def dry_run_install(app_id: int, name: str, *, valve_proton: bool) -> None:
"""Run the installer's ``--dry-run`` for *app_id* and relay its report.
Never goes through ``install_game``: no manifest is queued, Steam is not
closed and there is no ``steam://`` fallback, so it is safe while a game
is running.
Raises:
JobError: ``op_failed`` when the installer is missing or fails.
"""
installer = require_installer(installer_path())
cmd = build_cmd(
installer,
app_id,
resolve_desktop_user(),
valve_proton=valve_proton,
dry_run=True,
)
_echo(f"Dry run for {name or f'AppID={app_id}'}:")
code = relay_installer(cmd)
if code:
msg = f"Dry run failed (installer exit {code})."
raise JobError(msg, code="op_failed")
def require_installer(installer: Path | None) -> Path:
"""*installer* itself, or the ``op_failed`` refusal when it is missing.
Raises:
JobError: ``op_failed`` when the checkout has no installer.
"""
if installer is None:
msg = "steam-game-installer is missing from this checkout."
raise JobError(msg, code="op_failed")
return installer
def relay_installer(cmd: list[str]) -> int:
"""Run a short, prompt-free installer *cmd*, echo its output, return its exit.
Used for the read-only ``--dry-run`` and for ``--repair-ghosts``; neither
downloads, so both fit the same timeout.
"""
proc = subprocess.run(
cmd,
check=False,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
timeout=_DRY_RUN_TIMEOUT_SECONDS,
)
for line in proc.stdout.splitlines():
_echo(f" {line}")
return proc.returncode

View File

@ -14,7 +14,6 @@ from steam_backlog_enforcer._prompter import (
current_prompter,
)
from steam_backlog_enforcer._steam_errors import SteamUnavailableError
from steam_backlog_enforcer._steam_restart_guard import game_is_running
from steam_backlog_enforcer._steam_state import is_game_fully_installed
from steam_backlog_enforcer.game_install import (
_echo,
@ -27,11 +26,6 @@ from steam_backlog_enforcer.library_hider import (
try_hide_other_games,
unhide_all_games,
)
from steam_backlog_enforcer.main._install_target import (
dry_run_install,
install_candidates,
resolve_target,
)
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
@ -84,16 +78,16 @@ def cmd_uninstall(_config: Config, state: State) -> None:
_echo(f"\nUninstalled {count} games.")
def _pick_install_target(
candidates: list[tuple[int, str]],
) -> tuple[int, str] | None:
def _pick_install_target(state: State) -> tuple[int, str] | None:
"""The allowed game to install: the only unfinished one, or the user's pick.
Every allowed game counts, not just the assignment: a manual pick whose
fast install was skipped (a game was running at pick time) needs a way to
start it later too, and so does an approved exception.
start it later too.
"""
pending = [(aid, n) for aid, n in candidates if not is_game_fully_installed(aid)]
pending = [
(aid, n) for aid, n in allowed_games(state) if not is_game_fully_installed(aid)
]
if not pending:
_echo("All allowed games are already installed.")
return None
@ -104,71 +98,31 @@ def _pick_install_target(
return next(game for game in pending if game[0] == picked)
def cmd_install(
config: Config,
state: State,
*,
target: str | None = None,
dry_run: bool = False,
valve_proton: bool = False,
) -> dict[str, object] | None:
def cmd_install(config: Config, state: State) -> None:
"""Install an allowed game, through the fast installer when it can be used.
A download Steam already started is taken over, so this is also how a
fast install that was skipped earlier gets started. *target* (AppID, URL
or name) must be a game allowed today; *dry_run* only reports what the
installer would do.
Returns:
``{app_id, dry_run, fast_install_skipped}`` once a game was chosen,
else ``None``.
Raises:
JobError: ``locked`` for a target that is not allowed today.
fast install that was skipped earlier gets started.
"""
candidates = install_candidates(config, state)
if not candidates:
if not allowed_games(state):
_echo("No game currently assigned. Run 'scan' first.")
return None
if target:
chosen: tuple[int, str] | None = resolve_target(target, candidates)
else:
chosen = _pick_install_target(candidates)
if chosen is None:
return None
app_id, name = chosen
result: dict[str, object] = {
"app_id": app_id,
"dry_run": dry_run,
"fast_install_skipped": None,
}
if dry_run:
current_progress().phase(f"Dry run of {name or app_id}")
dry_run_install(app_id, name, valve_proton=valve_proton)
return result
# The installer closes Steam: with a game running the fast path is
# refused (Steam's own download starts instead), and the UI says why.
if game_is_running():
result["fast_install_skipped"] = "game_running"
return
target = _pick_install_target(state)
if target is None:
return
app_id, name = target
_echo(f"Installing {name} (AppID={app_id})...")
# install_game only *starts* the download (fast installer or steam://);
# there is no download-progress loop to report on yet.
current_progress().phase(f"Starting install of {name}")
if not install_game(
app_id,
name,
config.steam_id,
use_steam_protocol=True,
valve_proton=valve_proton,
):
if not install_game(app_id, name, config.steam_id, use_steam_protocol=True):
_echo("Failed to start the install.")
elif fast_install_failure(app_id) is None:
_echo("Done!")
else:
# The fast install already printed its "Failed: ..." line.
_echo("Steam's own download was started instead.")
return result
def cmd_hide(config: Config, state: State) -> None:

View File

@ -1,111 +0,0 @@
"""``map-installed``: the installer's ``--map-installed --apply``, behind friction.
The apply closes Steam (``flow.prepare_steam``: Steam rewrites config.vdf on
exit), maps each game the decision proves safe to the native Proton, and
starts Steam again. Closing Steam under a running game would kill it, so this
refuses while one runs. The web server checks the ids, the phrase (it names
how many games) and the guard before a job exists (``_web_jobs``); this
re-checks all three inside the job. The installer gets exactly the ids the
phrase counted, never "everything".
"""
from __future__ import annotations
import subprocess
import threading
from typing import TYPE_CHECKING, Final
from steam_backlog_enforcer._command_params import InvalidParamsError
from steam_backlog_enforcer._compat_view import checked_appids
from steam_backlog_enforcer._desktop_env import resolve_desktop_user
from steam_backlog_enforcer._fast_install_cmd import (
build_map_installed_cmd,
installer_path,
)
from steam_backlog_enforcer._prompter import PromptAbortedError, confirm_phrase
from steam_backlog_enforcer._steam_restart_guard import (
GAME_RUNNING_JOB_MSG,
game_is_running,
)
from steam_backlog_enforcer.game_install import _echo
from steam_backlog_enforcer.jobs._errors import JobError
from steam_backlog_enforcer.main._install_target import require_installer
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
# Closing Steam may take steamctl.SHUTDOWN_TIMEOUT (60 s), then the mapping
# and the restart: well past the dry run's 50 s.
APPLY_TIMEOUT_SECONDS: Final = 180
def stream_installer(cmd: list[str], *, timeout: float) -> int:
"""Run *cmd*, echo each output line as it comes, return its exit code.
Streamed, so the job page shows Steam closing and each game mapped live.
A timer kills it at *timeout* even while it still holds stdout open; a
killed run returns non-zero.
"""
killed = threading.Event()
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.DEVNULL,
text=True,
) as proc:
def kill() -> None:
killed.set()
proc.kill()
timer = threading.Timer(timeout, kill)
timer.daemon = True
timer.start()
try:
for line in proc.stdout or ():
_echo(f" {line.rstrip()}")
code = proc.wait()
finally:
timer.cancel()
if killed.is_set():
_echo(f" Killed after {timeout:.0f} s.")
return code or 1
return code
def run_map_installed(raw_appids: str | None) -> list[int]:
"""Map *raw_appids* (or every game that would change), after guard and phrase.
Returns:
The app ids handed to the installer.
Raises:
JobError: ``game_running`` while a game runs; ``invalid_params`` when
the ids are no longer valid; ``op_failed`` when the installer is
missing or exits non-zero.
PromptAbortedError: The phrase was not typed exactly.
"""
if game_is_running():
raise JobError(GAME_RUNNING_JOB_MSG, code="game_running")
try:
appids = checked_appids(raw_appids)
except InvalidParamsError as exc:
raise JobError(str(exc), code="invalid_params") from None
count = len(appids)
question = f"Close Steam and map {count} games to the native Proton?"
if not confirm_phrase("map-installed", question, appid_count=count):
msg = "Aborted."
raise PromptAbortedError(msg)
installer = require_installer(installer_path())
cmd = build_map_installed_cmd(installer, resolve_desktop_user(), appids)
code = stream_installer(cmd, timeout=APPLY_TIMEOUT_SECONDS)
if code:
msg = f"map-installed failed (installer exit {code})."
raise JobError(msg, code="op_failed")
return appids
def cmd_map_installed(_config: Config, _state: State) -> None:
"""``./run.sh map-installed``: every installed game that would change."""
run_map_installed(None)

View File

@ -1,52 +0,0 @@
"""``repair-ghosts``: the installer's ``--repair-ghosts``, behind friction.
The installer renames each cold ghost manifest (one that claims "installed"
with nothing on disk) and removes its empty folder; a ghost with staged bytes
is reported and kept. It does not close Steam itself, but it rewrites the
library under a client that may be reading it, so it waits like ``install``
does until no game is running. The web server checks the phrase and the guard
before a job exists (``_web_jobs``); this re-checks both inside the job.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_backlog_enforcer._desktop_env import resolve_desktop_user
from steam_backlog_enforcer._fast_install_cmd import (
build_repair_ghosts_cmd,
installer_path,
)
from steam_backlog_enforcer._prompter import PromptAbortedError, confirm_phrase
from steam_backlog_enforcer._steam_restart_guard import (
GAME_RUNNING_JOB_MSG,
game_is_running,
)
from steam_backlog_enforcer.jobs._errors import JobError
from steam_backlog_enforcer.main._install_target import (
relay_installer,
require_installer,
)
if TYPE_CHECKING:
from steam_backlog_enforcer.config import Config, State
def cmd_repair_ghosts(_config: Config, _state: State) -> None:
"""Delete the ghost manifests, after the guard and the typed phrase.
Raises:
JobError: ``game_running`` while a game runs; ``op_failed`` when the
installer is missing or exits non-zero.
PromptAbortedError: The phrase was not typed exactly.
"""
if game_is_running():
raise JobError(GAME_RUNNING_JOB_MSG, code="game_running")
if not confirm_phrase("repair-ghosts", "Delete the ghost install manifests?"):
msg = "Aborted."
raise PromptAbortedError(msg)
installer = require_installer(installer_path())
code = relay_installer(build_repair_ghosts_cmd(installer, resolve_desktop_user()))
if code:
msg = f"repair-ghosts failed (installer exit {code})."
raise JobError(msg, code="op_failed")

View File

@ -46,10 +46,9 @@ def _no_fast_install(tmp_path: Path) -> Iterator[None]:
_FAILURES.clear()
patches = [patch(name, return_value=False) for name in _RUNNING_BINDINGS]
patches += [
# The installer is in this repo now, so it always exists: point the
# constant at a file that does not, or a test could close real Steam.
# Absolute, so `home / _INSTALLER` resolves here and never under ~.
patch.object(
_fast_install_cmd, "_INSTALLER", tmp_path / "no-installer" / "cli.py"
_fast_install_cmd, "_INSTALLER", tmp_path / "no-installer" / "run.sh"
),
patch.object(_fast_install_cmd, "STEAMAPPS_PATH", fake_steamapps),
]

View File

@ -101,7 +101,7 @@ def _drives_steam(argv: Sequence[str]) -> bool:
for arg in argv:
if PurePath(arg).name in _DENIED_TOOLS:
return True
if arg.startswith("steam://") or arg in {"-shutdown", "steam_installer.cli"}:
if arg.startswith("steam://") or arg == "-shutdown":
return True
return False

View File

@ -1,60 +0,0 @@
"""Shared POST-time friction test helpers: drive ``create_job_view`` once."""
from __future__ import annotations
from contextlib import ExitStack
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from steam_backlog_enforcer import _web_jobs
from steam_backlog_enforcer._web_errors import ApiError
from steam_backlog_enforcer.tests._web_request import make_request
if TYPE_CHECKING:
from collections.abc import Iterable
from contextlib import AbstractContextManager
from http import HTTPStatus
WEB = "steam_backlog_enforcer._web_jobs"
def post_job(
command: str,
params: dict[str, object],
phrase: str | None,
*,
running: bool = False,
extra: Iterable[AbstractContextManager[object]] = (),
) -> tuple[object, MagicMock]:
"""POST *command* with the job store and the game guard patched.
Returns the reply (or the ``ApiError`` raised) and the ``create_job`` mock.
"""
body: dict[str, object] = {"command": command, "params": params}
if phrase is not None:
body["confirm_phrase"] = phrase
with ExitStack() as stack:
create = stack.enter_context(patch(f"{WEB}.create_job", return_value="j1"))
stack.enter_context(patch(f"{WEB}.read_job", return_value={"id": "j1"}))
stack.enter_context(patch(f"{WEB}.game_is_running", return_value=running))
for patcher in extra:
stack.enter_context(patcher)
try:
reply: object = _web_jobs.create_job_view(make_request(body=body))
except ApiError as exc:
reply = exc
return reply, create
def assert_refused(
reply: object,
create: MagicMock,
code: str,
status: HTTPStatus | None = None,
) -> None:
"""The POST was refused with *code* (and *status*) and no job was made."""
assert isinstance(reply, ApiError)
assert reply.code == code
if status is not None:
assert reply.status == status
create.assert_not_called()

View File

@ -155,20 +155,15 @@ class TestPhrasesAreFillable:
def test_every_template_field_has_a_source(self) -> None:
"""Every phrase field can be filled from a param or derived value."""
# Mirrors fillPhrase in web/src/commands/catalog.ts: a field is a
# param, ``game_name`` from an ``app_id`` param, ``appid_count`` from
# an ``appids`` param, or ``count`` from the installed list. Anything
# else leaves Run disabled forever.
# param, ``game_name`` from an ``app_id`` param, or ``count`` from
# the installed list. Anything else leaves Run disabled forever.
# The same two tables ``_spec`` builds each CommandSpec from.
for name in _command_catalog.CATALOG:
friction = FRICTION.get(name)
if friction is None:
continue
params = {p.name for p in PARAMS.get(name, ())}
derived = {"count"}
if "app_id" in params:
derived.add("game_name")
if "appids" in params:
derived.add("appid_count")
derived = {"count"} | ({"game_name"} if "app_id" in params else set())
template = friction.phrase_template
fields = {f for _, f, _, _ in Formatter().parse(template) if f}
assert fields <= params | derived, name

View File

@ -1,165 +0,0 @@
"""``GET /api/compat``: the map-installed decisions as rows, cached by file stats."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from steam_backlog_enforcer import _compat_view, _web_routes
from steam_backlog_enforcer._command_params import InvalidParamsError
from steam_backlog_enforcer._web_errors import ApiError
from steam_backlog_enforcer.tests._web_request import make_request
from steam_installer.appinfo import AppInfoError
from steam_installer.compat_rows import Row
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
V = "steam_backlog_enforcer._compat_view"
def _row(appid: int, *, changes: bool) -> Row:
return Row(
appid=appid,
name=f"G{appid}",
current=None,
priority=None,
decided="proton-cachyos-native" if changes else None,
reasons=() if changes else ("native",),
note=None,
map=changes,
changes=changes,
cached=True,
)
ROWS = [_row(10, changes=True), _row(20, changes=False), _row(30, changes=True)]
@pytest.fixture(name="env")
def _env() -> Iterator[dict[str, MagicMock]]:
"""A fake Steam root, a fixed stat key and the installer's rows mocked."""
_compat_view.clear_cache()
with (
patch(f"{V}.find_steam_root", return_value=MagicMock()) as root,
patch(f"{V}.cache_key", return_value=("k",)) as key,
patch(f"{V}.Context") as context,
patch(f"{V}.rows", return_value=ROWS) as rows,
):
context.return_value.tool_ready = True
yield {"root": root, "key": key, "context": context, "rows": rows}
_compat_view.clear_cache()
def test_payload_shape(env: dict[str, MagicMock]) -> None:
"""Rows as the CompatRow contract, plus the tool and whether it is ready."""
data = _compat_view.compat_payload()
assert data["tool"] == "proton-cachyos-native"
assert data["tool_ready"] is True
rows = data["rows"]
assert isinstance(rows, list)
assert [r["app_id"] for r in rows] == [10, 20, 30]
assert rows[1]["reasons"] == ["native"]
_, kwargs = env["context"].call_args
assert kwargs == {"anticheat_max_age": _compat_view.ANTICHEAT_MAX_AGE}
def test_same_key_is_served_from_memory(env: dict[str, MagicMock]) -> None:
"""A second GET with unchanged files decides nothing again."""
_compat_view.compat_payload()
_compat_view.compat_payload()
env["rows"].assert_called_once()
def test_a_changed_file_recomputes(env: dict[str, MagicMock]) -> None:
"""Any stat change (config.vdf written by apply) is a fresh decision."""
_compat_view.compat_payload()
env["key"].return_value = ("k2",)
_compat_view.compat_payload()
assert env["rows"].call_count == 2
@pytest.mark.usefixtures("env")
def test_view_replies_ok() -> None:
"""The route answers 200 with the payload."""
reply = _compat_view.compat_view(make_request())
assert reply.status == 200
assert isinstance(reply.payload, dict)
@pytest.mark.parametrize(
"exc", [AppInfoError("no cache"), FileNotFoundError("no Steam"), ValueError("x")]
)
def test_view_failure_is_op_failed(env: dict[str, MagicMock], exc: Exception) -> None:
"""No app cache, no Steam or a bad overrides file is a 502, not a crash."""
env["rows"].side_effect = exc
with pytest.raises(ApiError) as err:
_compat_view.compat_view(make_request())
assert err.value.code == "op_failed"
def test_route_is_registered() -> None:
"""``GET /api/compat`` is in the route table."""
assert any(
e.method == "GET" and re.fullmatch(e.pattern, "/api/compat")
for e in _web_routes.ROUTES
)
def test_cache_key_tracks_the_files(tmp_path: Path) -> None:
"""The key changes when config.vdf or a manifest changes."""
root = tmp_path / "Steam"
(root / "config").mkdir(parents=True)
(root / "steamapps").mkdir()
config = root / "config" / "config.vdf"
config.write_text("a")
with patch(f"{V}.appinfo_cache.default_path", return_value=root / "none.vdf"):
first = _compat_view.cache_key(root)
config.write_text("ab")
second = _compat_view.cache_key(root)
(root / "steamapps" / "appmanifest_1.acf").write_text("x")
third = _compat_view.cache_key(root)
assert len({first, second, third}) == 3
class TestCheckedAppids:
"""The ``appids`` param: digits only, installed only, never empty."""
@pytest.mark.usefixtures("env")
def test_none_means_every_changing_game(self) -> None:
"""No appids: every row that would change."""
assert _compat_view.checked_appids(None) == [10, 30]
@pytest.mark.usefixtures("env")
def test_list_is_parsed_and_deduped(self) -> None:
"""Spaces forgiven, duplicates dropped, order kept."""
assert _compat_view.checked_appids(" 30, 10,30 ") == [30, 10]
@pytest.mark.usefixtures("env")
@pytest.mark.parametrize("raw", ["10,x", "10,,20", "-1", "10;20"])
def test_junk_is_refused(self, raw: str) -> None:
"""Anything but comma-separated digits is invalid."""
with pytest.raises(InvalidParamsError):
_compat_view.checked_appids(raw)
@pytest.mark.usefixtures("env")
def test_a_game_that_is_not_installed_is_refused(self) -> None:
"""Apply never maps a game that is not installed."""
with pytest.raises(InvalidParamsError, match="999"):
_compat_view.checked_appids("10,999")
def test_nothing_to_map_is_refused(self, env: dict[str, MagicMock]) -> None:
"""No changing game and no list: nothing to do is an error, not a no-op."""
env["rows"].return_value = [_row(20, changes=False)]
with pytest.raises(InvalidParamsError):
_compat_view.checked_appids(None)
@pytest.mark.usefixtures("env")
def test_phrase_fields(self) -> None:
"""The phrase counts exactly the games the job will be given."""
assert _compat_view.phrase_fields({"appids": "10,20"}) == {"appid_count": 2}
assert _compat_view.phrase_fields({}) == {"appid_count": 2}

View File

@ -60,15 +60,12 @@ class TestFastInstallRunning:
@pytest.mark.parametrize(
"cmdline",
[
(
b"sudo\0-u\0u\0env\0PYTHONPATH=/r\0/usr/bin/python3\0"
b"-m\0steam_installer.cli\0--appid\0001"
),
b"bash\0/home/u/src/steam-game-installer/run.sh\0--appid\0001",
b"python\0-m\0steam_installer.cli\0--appid\0001",
],
)
def test_detects_installer(self, tmp_path: Path, cmdline: bytes) -> None:
"""The sudo wrapper and the Python module both count as the installer."""
"""Both the run.sh wrapper and the Python module count as the installer."""
proc = self._proc(tmp_path, {"self": b"", "10": None, "11": cmdline})
with patch(f"{GUARD}.Path", return_value=proc):
assert fast_install_running() is True

View File

@ -7,6 +7,7 @@ to keep both files under the 250-line cap.
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from steam_backlog_enforcer import _fast_install, _fast_install_cmd, _steam_state
@ -16,6 +17,41 @@ PKG = "steam_backlog_enforcer._fast_install"
CMD = "steam_backlog_enforcer._fast_install_cmd"
class TestInstallerPath:
"""run.sh is resolved from the desktop user's passwd home."""
def test_found_in_user_home(self, tmp_path: Path) -> None:
"""run.sh is found under the desktop user's passwd home."""
installer = tmp_path / "src" / "steam-game-installer" / "run.sh"
installer.parent.mkdir(parents=True)
installer.write_text("#!/bin/bash\n")
# The autouse guard points _INSTALLER at a dead absolute path; put the
# real relative one back so the home join itself is what is tested.
relative = Path("src", "steam-game-installer", "run.sh")
with (
patch.object(_fast_install_cmd, "_INSTALLER", relative),
patch(f"{CMD}.pwd.getpwnam", return_value=SimpleNamespace(pw_dir=tmp_path)),
):
assert _fast_install_cmd.installer_path("kuhy") == installer
def test_missing_file_is_none(self, tmp_path: Path) -> None:
"""A home without run.sh yields no installer."""
with patch(
f"{CMD}.pwd.getpwnam", return_value=SimpleNamespace(pw_dir=tmp_path)
):
assert _fast_install_cmd.installer_path("kuhy") is None
def test_unknown_user_is_none(self) -> None:
"""A user unknown to passwd yields no installer."""
with patch(f"{CMD}.pwd.getpwnam", side_effect=KeyError("nobody")):
assert _fast_install_cmd.installer_path("nobody") is None
def test_no_user_uses_own_home(self, tmp_path: Path) -> None:
"""With no user the process's own home is searched."""
with patch(f"{CMD}.Path.home", return_value=tmp_path):
assert _fast_install_cmd.installer_path(None) is None
class TestSteamAccountName:
"""The username comes from Steam's own loginusers.vdf."""
@ -69,15 +105,10 @@ class TestBuildCmd:
patch(f"{CMD}.steam_account_name", return_value="krzys"),
patch(f"{CMD}.desktop_user_cmd", side_effect=lambda cmd, _u: cmd),
):
cmd = _fast_install_cmd.build_cmd(
Path("/r/steam_installer/cli.py"), 42, "kuhy"
)
cmd = _fast_install_cmd.build_cmd(Path("/i/run.sh"), 42, "kuhy")
assert cmd == [
"env",
"PYTHONPATH=/r",
"/usr/bin/python3",
"-m",
"steam_installer.cli",
"/i/run.sh",
"--no-deps",
"--appid",
"42",
"--yes",
@ -93,9 +124,9 @@ class TestBuildCmd:
patch(f"{CMD}.steam_account_name", return_value=None),
patch(f"{CMD}.desktop_user_cmd", return_value=["wrapped"]) as wrap,
):
assert _fast_install_cmd.build_cmd(
Path("/r/steam_installer/cli.py"), 42, "kuhy"
) == ["wrapped"]
assert _fast_install_cmd.build_cmd(Path("/i/run.sh"), 42, "kuhy") == [
"wrapped"
]
argv, user = wrap.call_args.args
assert "--username" not in argv
assert user == "kuhy"
@ -110,12 +141,3 @@ class TestIsFastInstalling:
_RUNS.append(_DetachedRun(5, MagicMock(), Path("/nonexistent")))
assert _fast_install.is_fast_installing(5) is True
assert _fast_install.is_fast_installing(6) is False
def test_build_cmd_valve_proton_and_dry_run() -> None:
"""The two install switches become the installer's own flags."""
with patch.object(_fast_install_cmd, "steam_account_name", return_value=None):
cmd = _fast_install_cmd.build_cmd(
Path("/x/steam_installer/cli.py"), 7, None, valve_proton=True, dry_run=True
)
assert cmd[-2:] == ["--valve-proton", "--dry-run"]

View File

@ -1,87 +0,0 @@
"""The installer ships in this repo: where it is, and the argv that starts it.
The daemon is root and the installer runs as the desktop user, so every piece
of the command line must survive ``sudo``: the interpreter, ``PYTHONPATH`` and
a flag set the installer's own parser accepts. A flag the parser rejects makes
argparse exit 2 and every fast install silently fall back to Steam's download.
"""
from __future__ import annotations
from pathlib import Path
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _fast_install_cmd
from steam_backlog_enforcer._fast_install_cmd import build_cmd, installer_path
from steam_backlog_enforcer._steam_restart_guard import _INSTALLER_MARKERS
from steam_installer import cli_args
CMD = "steam_backlog_enforcer._fast_install_cmd"
# Read at import: the autouse guard swaps the attribute out before each test.
REAL_INSTALLER: Path = vars(_fast_install_cmd)["_INSTALLER"]
REPO = Path(__file__).resolve().parents[2]
def _argv_after_launcher(cmd: list[str]) -> list[str]:
"""The installer's own arguments: everything after ``-m steam_installer.cli``."""
return cmd[cmd.index("steam_installer.cli") + 1 :]
class TestInstallerLocation:
"""The installer is found in this checkout, never under ~/src."""
def test_real_path_is_inside_this_repo(self) -> None:
"""Unpatched, the installer is this repo's own cli module, and exists."""
assert REAL_INSTALLER == REPO / "steam_installer" / "cli.py"
assert REAL_INSTALLER.is_file()
assert "steam-game-installer" not in REAL_INSTALLER.parts
def test_found_when_present(self) -> None:
"""installer_path returns the repo's cli module."""
with patch.object(_fast_install_cmd, "_INSTALLER", REAL_INSTALLER):
assert installer_path() == REAL_INSTALLER
def test_missing_is_none(self, tmp_path: Path) -> None:
"""A checkout without the installer falls back to Steam's download."""
with patch.object(_fast_install_cmd, "_INSTALLER", tmp_path / "gone.py"):
assert installer_path() is None
class TestBuiltArgv:
"""The exact argv the daemon hands to the desktop user."""
@pytest.fixture(name="argv")
def _argv(self) -> list[str]:
with patch(f"{CMD}.steam_account_name", return_value="krzys"):
return build_cmd(REAL_INSTALLER, 284160, None)
def test_installer_parser_accepts_it(self, argv: list[str]) -> None:
"""The installer's argparse takes the argv as built, with no exit 2."""
args = cli_args.build_parser().parse_args(_argv_after_launcher(argv))
assert args.appid == 284160
assert args.yes is True
assert args.language == "english"
assert args.username == "krzys"
def test_parser_accepts_it_without_account(self) -> None:
"""No signed-in account means no ``--username``, still parseable."""
with patch(f"{CMD}.steam_account_name", return_value=None):
argv = build_cmd(REAL_INSTALLER, 7, None)
cli_args.build_parser().parse_args(_argv_after_launcher(argv))
assert "--username" not in argv
def test_no_run_sh_only_flag(self, argv: list[str]) -> None:
"""``--no-deps`` belongs to run.sh; the module's parser has no such flag."""
assert "--no-deps" not in argv
def test_imports_from_this_checkout(self, argv: list[str]) -> None:
"""sudo resets the environment, so PYTHONPATH is named in the argv."""
assert f"PYTHONPATH={REPO}" in argv
assert argv[argv.index("steam_installer.cli") - 1] == "-m"
def test_scan_marker_matches_the_real_cmdline(self, argv: list[str]) -> None:
"""The /proc guard sees the process this argv starts, sudo wrapper too."""
cmdline = b"\0".join(arg.encode() for arg in argv)
assert any(marker in cmdline for marker in _INSTALLER_MARKERS)

View File

@ -27,9 +27,7 @@ class TestQueueBeforeFastInstall:
install is queued with Steam before the installer runs, not after."""
seen: list[bool] = []
def fast(
_app_id: int, _label: str, prepare: Callable[[], object], **_kw: object
) -> bool:
def fast(_app_id: int, _label: str, prepare: Callable[[], object]) -> bool:
prepare()
seen.append((tmp_path / "appmanifest_440.acf").exists())
return True

View File

@ -1,228 +0,0 @@
"""Tests for ``install`` with a target, a dry run and the Valve-Proton switch.
The locker stays intact: the target is resolved and checked by the enforcer
against the games allowed today (the assignment, manual picks and approved
exceptions), and the installer only ever gets the checked ``--appid``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from steam_backlog_enforcer._command_params import validate_params
from steam_backlog_enforcer._prompter import use_prompter
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.jobs import _registry
from steam_backlog_enforcer.jobs._errors import JobError
from steam_backlog_enforcer.main import cmd_install
from steam_backlog_enforcer.main._install_target import (
install_candidates,
resolve_target,
)
from steam_backlog_enforcer.tests._fake_prompter import FakePrompter
if TYPE_CHECKING:
from collections.abc import Iterator
PKG = "steam_backlog_enforcer.main.install"
TGT = "steam_backlog_enforcer.main._install_target"
CANDIDATES = [(1, "Portal"), (2, "Portal 2"), (3, "Hades")]
def _state() -> State:
return State(
current_app_id=1,
current_game_name="Portal",
manual_picks=[{"app_id": 2, "game_name": "Portal 2"}],
)
@pytest.fixture(name="env")
def _env() -> Iterator[dict[str, MagicMock]]:
"""Exceptions = {3: Hades}; nothing installed; no game running."""
with (
patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({3})),
patch(
f"{TGT}.load_owned_records",
return_value=[{"app_id": 3, "name": "Hades"}],
),
patch(f"{PKG}.is_game_fully_installed", return_value=False),
patch(f"{PKG}.install_game", return_value=True) as install,
patch(f"{PKG}.fast_install_failure", return_value=None),
patch(f"{PKG}.game_is_running", return_value=False) as running,
patch(f"{TGT}.subprocess.run") as run,
patch(f"{TGT}.installer_path", return_value=MagicMock()),
patch(f"{TGT}.build_cmd", return_value=["installer"]) as build,
patch(f"{PKG}._echo"),
patch(f"{TGT}._echo"),
):
run.return_value = MagicMock(returncode=0, stdout="would install\n")
yield {"install": install, "run": run, "build": build, "running": running}
class TestCandidates:
"""Allowed today = allowed_games plus approved exceptions."""
def test_exception_is_a_candidate_with_its_owned_name(self) -> None:
"""An approved exception is offered under its owned-records name."""
with (
patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({3})),
patch(
f"{TGT}.load_owned_records",
return_value=[{"app_id": 3, "name": "Hades"}, {"app_id": 9}],
),
):
assert install_candidates(Config(steam_id="i"), _state()) == CANDIDATES
def test_exception_without_records_gets_an_empty_name(self) -> None:
"""No owned records: the exception still counts, nameless."""
with (
patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({1, 5})),
patch(f"{TGT}.load_owned_records", return_value=None),
):
got = install_candidates(Config(steam_id="i"), _state())
assert got == [(1, "Portal"), (2, "Portal 2"), (5, "")]
class TestResolveTarget:
"""AppID, URL and name all resolve inside the allowed set only."""
def test_appid(self) -> None:
"""A bare allowed AppID resolves to itself."""
assert resolve_target("2", CANDIDATES) == (2, "Portal 2")
def test_url(self) -> None:
"""A store URL resolves through its ``app/<id>``."""
url = "https://store.steampowered.com/app/3/Hades/"
assert resolve_target(url, CANDIDATES) == (3, "Hades")
@pytest.mark.parametrize(
"text", ["999", "https://steamcommunity.com/app/999/guides/", "Doom"]
)
def test_not_allowed_is_refused(self, text: str) -> None:
"""Any game outside the allowed set is refused as ``locked``."""
with pytest.raises(JobError) as exc:
resolve_target(text, CANDIDATES)
assert exc.value.code == "locked"
def test_exact_name_wins(self) -> None:
"""A fully typed title does not install the sequel."""
assert resolve_target("portal", CANDIDATES) == (1, "Portal")
def test_unique_partial_name(self) -> None:
"""A unique partial name resolves without asking."""
assert resolve_target("had", CANDIDATES) == (3, "Hades")
def test_ambiguous_name_asks(self) -> None:
"""Several matches are offered as a choice, never guessed."""
prompter = FakePrompter(choices=["2"])
with use_prompter(prompter):
assert resolve_target("Port", CANDIDATES) == (2, "Portal 2")
assert prompter.asked[0][1] == ["1", "2"]
class TestInstallJob:
"""cmd_install with the web job's params."""
def test_picker_offers_not_installed_exception(
self, env: dict[str, MagicMock]
) -> None:
"""Todo 6ee260a4: the no-target picker includes approved exceptions."""
prompter = FakePrompter(choices=["3"])
with use_prompter(prompter):
cmd_install(Config(steam_id="i"), _state())
assert prompter.asked[0][1] == ["1", "2", "3"]
assert env["install"].call_args.args[:2] == (3, "Hades")
def test_disallowed_target_starts_nothing(self, env: dict[str, MagicMock]) -> None:
"""A refused target never reaches the installer."""
with pytest.raises(JobError):
cmd_install(Config(steam_id="i"), _state(), target="999")
env["install"].assert_not_called()
env["run"].assert_not_called()
def test_allowed_target_installs(self, env: dict[str, MagicMock]) -> None:
"""An allowed target installs, Valve Proton passed through."""
result = cmd_install(
Config(steam_id="i"), _state(), target="Hades", valve_proton=True
)
assert env["install"].call_args.args[:2] == (3, "Hades")
assert env["install"].call_args.kwargs["valve_proton"] is True
assert result == {"app_id": 3, "dry_run": False, "fast_install_skipped": None}
def test_game_running_is_reported(self, env: dict[str, MagicMock]) -> None:
"""The fast-install guard's refusal is in the result data for the UI."""
env["running"].return_value = True
result = cmd_install(Config(steam_id="i"), _state(), target="3")
assert result is not None
assert result["fast_install_skipped"] == "game_running"
def test_dry_run_changes_nothing(self, env: dict[str, MagicMock]) -> None:
"""Dry run: only the installer's --dry-run, even with a game running."""
env["running"].return_value = True
result = cmd_install(
Config(steam_id="i"), _state(), target="3", dry_run=True, valve_proton=True
)
env["install"].assert_not_called()
assert env["build"].call_args.kwargs == {"valve_proton": True, "dry_run": True}
assert env["build"].call_args.args[1] == 3
assert result == {"app_id": 3, "dry_run": True, "fast_install_skipped": None}
def test_failed_dry_run_fails_the_job(self, env: dict[str, MagicMock]) -> None:
"""A dry run the installer rejects is a failed job, not a success."""
env["run"].return_value = MagicMock(returncode=1, stdout="ERROR x\n")
with pytest.raises(JobError) as exc:
cmd_install(Config(steam_id="i"), _state(), target="3", dry_run=True)
assert exc.value.code == "op_failed"
def test_dry_run_without_installer(self, env: dict[str, MagicMock]) -> None:
"""No installer in the checkout: the dry run fails loudly."""
with (
patch(f"{TGT}.installer_path", return_value=None),
pytest.raises(JobError),
):
cmd_install(Config(steam_id="i"), _state(), target="3", dry_run=True)
env["run"].assert_not_called()
class TestInstallParamsAndHandler:
"""The web form's params reach cmd_install unchanged."""
def test_install_params_are_optional(self) -> None:
"""target / dry_run / valve_proton are all optional."""
assert validate_params("install", {}) == {"dry_run": 0, "valve_proton": 0}
got = validate_params("install", {"target": " Hades ", "dry_run": 1})
assert got == {"target": "Hades", "dry_run": 1, "valve_proton": 0}
def test_handler_maps_params(self) -> None:
"""The job handler turns the flat params into cmd_install kwargs."""
with (
patch.object(_registry, "cmd_install", return_value={"app_id": 3}) as cmd,
patch.object(_registry.State, "load", return_value=_state()),
patch.object(_registry.Config, "load", return_value=Config()),
):
out = _registry.HANDLERS["install"](
{"target": "3", "dry_run": 1, "valve_proton": 0},
MagicMock(),
MagicMock(),
)
assert out == {"app_id": 3}
assert cmd.call_args.kwargs == {
"target": "3",
"dry_run": True,
"valve_proton": False,
}
def test_handler_without_target(self) -> None:
"""No target: the picker path, and None data becomes the assignment."""
with (
patch.object(_registry, "cmd_install", return_value=None) as cmd,
patch.object(_registry.State, "load", return_value=_state()),
patch.object(_registry.Config, "load", return_value=Config()),
):
out = _registry.HANDLERS["install"]({}, MagicMock(), MagicMock())
assert cmd.call_args.kwargs["target"] is None
assert out == {"current_app_id": 1, "current_game_name": "Portal"}

View File

@ -1,208 +0,0 @@
"""``map-installed``: the apply job, its streaming and the tables."""
from __future__ import annotations
import io
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from steam_backlog_enforcer import _command_catalog
from steam_backlog_enforcer._command_params import PARAMS, InvalidParamsError
from steam_backlog_enforcer._fast_install_cmd import build_map_installed_cmd
from steam_backlog_enforcer._friction import expected_phrase
from steam_backlog_enforcer._prompter import PromptAbortedError, use_prompter
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.jobs import _registry
from steam_backlog_enforcer.jobs._errors import JobError
from steam_backlog_enforcer.jobs._specs import JOB_FLAGS
from steam_backlog_enforcer.main import COMMANDS
from steam_backlog_enforcer.main import map_installed as job
from steam_backlog_enforcer.tests._fake_prompter import FakePrompter
if TYPE_CHECKING:
from collections.abc import Callable, Iterator
from pathlib import Path
PKG = "steam_backlog_enforcer.main.map_installed"
def _proc(lines: str, code: int = 0) -> MagicMock:
proc = MagicMock(returncode=code)
proc.stdout = io.StringIO(lines)
proc.wait.return_value = code
proc.__enter__.return_value = proc
return proc
@pytest.fixture(name="env")
def _env() -> Iterator[dict[str, MagicMock]]:
"""No game running, two games to map, an installer, Popen mocked."""
with (
patch(f"{PKG}.game_is_running", return_value=False) as running,
patch(f"{PKG}.checked_appids", return_value=[10, 30]) as ids,
patch(f"{PKG}.installer_path", return_value=MagicMock()),
patch(f"{PKG}.build_map_installed_cmd", return_value=["inst"]) as build,
patch(f"{PKG}.subprocess.Popen") as popen,
patch(f"{PKG}._echo") as echo,
):
popen.return_value = _proc("Compat tool for 10: mapped.\n")
yield {
"running": running,
"ids": ids,
"build": build,
"popen": popen,
"echo": echo,
}
def _run(
raw: str | None = "10,30", phrases: tuple[bool, ...] = (True,)
) -> FakePrompter:
prompter = FakePrompter(phrases=phrases)
with use_prompter(prompter):
job.run_map_installed(raw)
return prompter
class TestJob:
"""``run_map_installed``: guard, phrase, then the streamed installer."""
def test_maps_the_checked_ids_and_streams_output(
self, env: dict[str, MagicMock]
) -> None:
"""The phrase counts the ids; the installer gets exactly those ids."""
prompter = _run()
assert prompter.asked[0][1] == "map 2 games"
env["ids"].assert_called_once_with("10,30")
assert env["build"].call_args.args[2] == [10, 30]
env["echo"].assert_any_call(" Compat tool for 10: mapped.")
def test_game_running_refuses_first(self, env: dict[str, MagicMock]) -> None:
"""Closing Steam would kill the game: refuse before anything else."""
env["running"].return_value = True
with pytest.raises(JobError) as exc:
_run(phrases=())
assert exc.value.code == "game_running"
env["popen"].assert_not_called()
def test_wrong_phrase_aborts(self, env: dict[str, MagicMock]) -> None:
"""A wrong phrase never starts the installer."""
with pytest.raises(PromptAbortedError):
_run(phrases=(False,))
env["popen"].assert_not_called()
def test_bad_appids_fail_the_job(self, env: dict[str, MagicMock]) -> None:
"""Ids that stopped being valid since the POST are ``invalid_params``."""
env["ids"].side_effect = InvalidParamsError("999 is not installed")
with pytest.raises(JobError) as exc:
_run()
assert exc.value.code == "invalid_params"
def test_installer_failure(self, env: dict[str, MagicMock]) -> None:
"""A non-zero exit is ``op_failed``."""
env["popen"].return_value = _proc("ERROR\n", code=1)
with pytest.raises(JobError) as exc:
_run()
assert exc.value.code == "op_failed"
def test_missing_installer(self, env: dict[str, MagicMock]) -> None:
"""No installer in the checkout fails before any subprocess."""
with patch(f"{PKG}.installer_path", return_value=None), pytest.raises(JobError):
_run()
env["popen"].assert_not_called()
def test_cli_command_maps_every_changing_game(
self, env: dict[str, MagicMock]
) -> None:
"""``./run.sh map-installed`` is the job with no list."""
with use_prompter(FakePrompter(phrases=(True,))):
job.cmd_map_installed(Config(), State())
env["ids"].assert_called_once_with(None)
def test_job_handler_passes_the_param(self, env: dict[str, MagicMock]) -> None:
"""The job handler hands ``appids`` through and reports the ids."""
with use_prompter(FakePrompter(phrases=(True,))):
data = _registry.HANDLERS["map-installed"](
{"appids": "10,30"}, MagicMock(), MagicMock()
)
env["ids"].assert_called_once_with("10,30")
assert data == {"app_ids": [10, 30]}
class _FiringTimer:
"""A ``threading.Timer`` whose deadline has already passed."""
def __init__(self, _seconds: float, fn: Callable[[], None]) -> None:
self.fn = fn
self.daemon = False
def start(self) -> None:
"""Fire at once: the deadline has already passed."""
self.fn()
def cancel(self) -> None:
"""Nothing left to cancel."""
def test_stream_times_out_and_kills() -> None:
"""A run past its deadline is killed and reported as a failure."""
proc = _proc("")
proc.wait.return_value = -9
with (
patch(f"{PKG}.subprocess.Popen", return_value=proc),
patch(f"{PKG}.threading.Timer", _FiringTimer),
patch(f"{PKG}._echo") as echo,
):
assert job.stream_installer(["x"], timeout=1) == -9
proc.kill.assert_called_once()
echo.assert_any_call(" Killed after 1 s.")
def test_stream_killed_with_a_zero_exit_still_fails() -> None:
"""A kill that somehow reports 0 is still a failure."""
proc = _proc("")
proc.wait.return_value = 0
with (
patch(f"{PKG}.subprocess.Popen", return_value=proc),
patch(f"{PKG}.threading.Timer", _FiringTimer),
patch(f"{PKG}._echo"),
):
assert job.stream_installer(["x"], timeout=1) == 1
def test_stream_returns_the_exit_code() -> None:
"""No timeout: the installer's own exit code."""
proc = _proc("a\n", code=3)
with patch(f"{PKG}.subprocess.Popen", return_value=proc), patch(f"{PKG}._echo"):
assert job.stream_installer(["x"], timeout=60) == 3
def test_argv(tmp_path: Path) -> None:
"""``--map-installed --apply --yes --appids`` with the checked ids."""
installer = tmp_path / "steam_installer" / "cli.py"
with patch(
"steam_backlog_enforcer._fast_install_cmd.desktop_user_cmd",
side_effect=lambda cmd, _user: cmd,
):
cmd = build_map_installed_cmd(installer, None, [10, 30])
assert cmd[-6:] == [
"steam_installer.cli",
"--map-installed",
"--apply",
"--yes",
"--appids",
"10,30",
]
assert f"PYTHONPATH={tmp_path}" in cmd
def test_tables() -> None:
"""Phrase, CLI command, job, catalog entry and the optional param."""
assert expected_phrase("map-installed", appid_count=3) == "map 3 games"
assert COMMANDS["map-installed"][1] is job.cmd_map_installed
assert JOB_FLAGS["map-installed"].mutating
assert _command_catalog.CATALOG["map-installed"].category == "library"
(spec,) = PARAMS["map-installed"]
assert (spec.name, spec.type, spec.required) == ("appids", "string", False)

View File

@ -1,73 +0,0 @@
"""``map-installed``: what ``POST /api/jobs`` refuses before a job exists."""
from __future__ import annotations
from http import HTTPStatus
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from steam_backlog_enforcer._command_params import InvalidParamsError
from steam_backlog_enforcer._web_errors import ApiError
from steam_backlog_enforcer.tests._post_job import assert_refused, post_job
if TYPE_CHECKING:
from unittest.mock import MagicMock
def _post(
phrase: str | None, appids: str = "10,30", *, running: bool = False
) -> tuple[object, MagicMock]:
checked = patch(
"steam_backlog_enforcer._compat_view.checked_appids",
side_effect=lambda raw: (
[int(x) for x in str(raw).split(",") if x.isdigit()] or _bad()
),
)
return post_job(
"map-installed", {"appids": appids}, phrase, running=running, extra=[checked]
)
def _bad() -> list[int]:
msg = "not installed"
raise InvalidParamsError(msg)
class TestPostTimeFriction:
"""``POST /api/jobs`` refuses before a job exists."""
@pytest.mark.parametrize("phrase", [None, "map 3 games", "Map 2 games"])
def test_wrong_phrase_creates_no_job(self, phrase: str | None) -> None:
"""The count is part of the phrase: a stale count is wrong."""
assert_refused(*_post(phrase), "wrong_phrase")
def test_game_running_is_409(self) -> None:
"""The right phrase while a game runs: ``game_running``, no job."""
assert_refused(
*_post("map 2 games", running=True), "game_running", HTTPStatus.CONFLICT
)
def test_bad_appids_are_invalid_params(self) -> None:
"""Ids that are not installed games: 400 before the phrase."""
assert_refused(*_post("map 0 games", appids="x"), "invalid_params")
def test_unreadable_steam_is_op_failed(self) -> None:
"""Steam's library cannot be read: ``op_failed`` before a job exists."""
unreadable = patch(
"steam_backlog_enforcer._compat_view.checked_appids",
side_effect=OSError("no library"),
)
reply, create = post_job(
"map-installed", {"appids": "10"}, "map 1 games", extra=[unreadable]
)
assert_refused(reply, create, "op_failed")
def test_right_phrase_creates_the_job(self) -> None:
"""Right phrase, no game: the job, with the phrase passed on."""
reply, create = _post("map 2 games")
assert not isinstance(reply, ApiError)
create.assert_called_once_with(
"map-installed", {"appids": "10,30"}, confirm_phrase="map 2 games"
)

View File

@ -63,7 +63,6 @@ class TestDrivesSteam:
["sudo", "-u", "kuhy", "steam.sh"],
["xdg-open", "https://example.com"],
["runuser", "steam-game-installer", "620"],
["python3", "-m", "steam_installer.cli", "--appid", "620"],
["pkill", "-f", "x"],
["killall", "x"],
["/bin/kill", "-TERM", "42"],

View File

@ -1,172 +0,0 @@
"""Tests for ``repair-ghosts``: CLI command, job, catalog and POST-time friction."""
from __future__ import annotations
from http import HTTPStatus
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from steam_backlog_enforcer import _command_catalog
from steam_backlog_enforcer._fast_install_cmd import build_repair_ghosts_cmd
from steam_backlog_enforcer._friction import expected_phrase
from steam_backlog_enforcer._prompter import PromptAbortedError, use_prompter
from steam_backlog_enforcer._web_errors import STATUS_BY_CODE, ApiError
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.jobs import _registry
from steam_backlog_enforcer.jobs._errors import JobError
from steam_backlog_enforcer.jobs._specs import JOB_FLAGS
from steam_backlog_enforcer.main import COMMANDS
from steam_backlog_enforcer.main.repair_ghosts import cmd_repair_ghosts
from steam_backlog_enforcer.tests._fake_prompter import FakePrompter
from steam_backlog_enforcer.tests._post_job import assert_refused, post_job
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
PKG = "steam_backlog_enforcer.main.repair_ghosts"
TGT = "steam_backlog_enforcer.main._install_target"
PHRASE = "delete ghost manifests"
@pytest.fixture(name="env")
def _env() -> Iterator[dict[str, MagicMock]]:
"""No game running, an installer present, the subprocess mocked."""
with (
patch(f"{PKG}.game_is_running", return_value=False) as running,
patch(f"{PKG}.installer_path", return_value=MagicMock()),
patch(f"{PKG}.build_repair_ghosts_cmd", return_value=["inst"]) as build,
patch(f"{TGT}.subprocess.run") as run,
patch(f"{TGT}._echo") as echo,
):
run.return_value = MagicMock(returncode=0, stdout="No ghost installs found.\n")
yield {"running": running, "run": run, "build": build, "echo": echo}
def _run(phrases: tuple[bool, ...] = (True,)) -> FakePrompter:
prompter = FakePrompter(phrases=phrases)
with use_prompter(prompter):
cmd_repair_ghosts(Config(), State())
return prompter
class TestCommand:
"""``cmd_repair_ghosts``: guard, phrase, then the installer."""
def test_runs_the_installer_and_relays_its_report(
self, env: dict[str, MagicMock]
) -> None:
"""The right phrase runs ``--repair-ghosts`` and echoes every line."""
prompter = _run()
assert prompter.asked[0][1] == PHRASE
env["run"].assert_called_once()
assert env["run"].call_args.args[0] == ["inst"]
env["echo"].assert_any_call(" No ghost installs found.")
def test_game_running_refuses_before_the_phrase(
self, env: dict[str, MagicMock]
) -> None:
"""A running game refuses with ``game_running``; nothing runs."""
env["running"].return_value = True
with pytest.raises(JobError) as exc:
_run(phrases=())
assert exc.value.code == "game_running"
env["run"].assert_not_called()
def test_wrong_phrase_aborts(self, env: dict[str, MagicMock]) -> None:
"""A wrong phrase aborts the job and never runs the installer."""
with pytest.raises(PromptAbortedError):
_run(phrases=(False,))
env["run"].assert_not_called()
def test_installer_failure_fails_the_job(self, env: dict[str, MagicMock]) -> None:
"""A non-zero installer exit is ``op_failed``."""
env["run"].return_value = MagicMock(returncode=1, stdout="ERROR x\n")
with pytest.raises(JobError) as exc:
_run()
assert exc.value.code == "op_failed"
def test_missing_installer(self, env: dict[str, MagicMock]) -> None:
"""No installer in the checkout fails loudly before any subprocess."""
with (
patch(f"{PKG}.installer_path", return_value=None),
pytest.raises(JobError),
):
_run()
env["run"].assert_not_called()
class TestWiring:
"""CLI, job, catalog, friction and error-code tables."""
def test_argv(self, tmp_path: Path) -> None:
"""The installer gets ``--repair-ghosts`` and no AppID."""
installer = tmp_path / "steam_installer" / "cli.py"
with patch(
"steam_backlog_enforcer._fast_install_cmd.desktop_user_cmd",
side_effect=lambda cmd, _user: cmd,
):
cmd = build_repair_ghosts_cmd(installer, None)
assert cmd[-3:] == ["-m", "steam_installer.cli", "--repair-ghosts"]
assert f"PYTHONPATH={tmp_path}" in cmd
assert "--appid" not in cmd
def test_tables(self) -> None:
"""One phrase, one 409 code, a CLI command, a job and a library card."""
assert expected_phrase("repair-ghosts") == PHRASE
assert STATUS_BY_CODE["game_running"] == HTTPStatus.CONFLICT
assert COMMANDS["repair-ghosts"][1] is cmd_repair_ghosts
assert JOB_FLAGS["repair-ghosts"].mutating
assert "repair-ghosts" in _registry.HANDLERS
assert _command_catalog.CATALOG["repair-ghosts"].category == "library"
def test_job_handler_returns_the_assignment(
self, env: dict[str, MagicMock]
) -> None:
"""The job runs the CLI command and reports the assignment."""
with (
use_prompter(FakePrompter(phrases=(True,))),
patch.object(_registry.State, "load", return_value=State()),
patch.object(_registry.Config, "load", return_value=Config()),
):
data = _registry.HANDLERS["repair-ghosts"]({}, MagicMock(), MagicMock())
env["run"].assert_called_once()
assert data == {"current_app_id": None, "current_game_name": None}
def _post(phrase: str | None, *, running: bool = False) -> tuple[object, MagicMock]:
return post_job("repair-ghosts", {}, phrase, running=running)
class TestPostTimeFriction:
"""``POST /api/jobs`` refuses before a job exists."""
@pytest.mark.parametrize("phrase", [None, "", "Delete ghost manifests"])
def test_wrong_phrase_creates_no_job(self, phrase: str | None) -> None:
"""A missing or wrong phrase is ``wrong_phrase`` and no job."""
assert_refused(*_post(phrase), "wrong_phrase")
def test_wrong_phrase_wins_over_a_running_game(self) -> None:
"""The phrase is checked first, so friction is provable mid-game."""
assert_refused(*_post("nope", running=True), "wrong_phrase")
def test_game_running_creates_no_job(self) -> None:
"""The right phrase while a game runs is ``game_running`` (409)."""
assert_refused(
*_post(PHRASE, running=True), "game_running", HTTPStatus.CONFLICT
)
def test_right_phrase_creates_the_job(self) -> None:
"""The right phrase with no game creates the job, phrase passed on."""
reply, create = _post(f" {PHRASE} ")
assert not isinstance(reply, ApiError)
create.assert_called_once_with(
"repair-ghosts", {}, confirm_phrase=f" {PHRASE} "
)
def test_other_commands_are_not_prechecked(self) -> None:
"""Commands outside the set keep their job-side check only."""
_, create = post_job("uninstall", {}, None, running=True)
create.assert_called_once()

View File

@ -1 +0,0 @@
"""Fast Steam game installer (depotdownloader plus a hand-written manifest)."""

View File

@ -1,26 +0,0 @@
"""One https-only way to open a URL, shared by the network callers."""
from __future__ import annotations
import contextlib
from typing import TYPE_CHECKING
import urllib.request
if TYPE_CHECKING:
from collections.abc import Iterator
from http.client import HTTPResponse
@contextlib.contextmanager
def open_https(
url: str, *, timeout: float, user_agent: str | None = None
) -> Iterator[HTTPResponse]:
"""Open `url` (https only) with `user_agent`; a context manager."""
if not url.startswith("https://"):
msg = f"refusing a non-https URL: {url}"
raise ValueError(msg)
# No header when none is given: urllib then sends its own default agent.
headers = {} if user_agent is None else {"User-Agent": user_agent}
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=timeout) as response:
yield response

View File

@ -1,72 +0,0 @@
"""Steam app ids that use anti-cheat, from AreWeAntiCheatYet's `games.json`.
Fetched on every run; the last good copy is kept so a flaky network does not
change any decision. With neither a fetch nor a copy the answer is "unknown",
and an unknown list maps nothing. Every listed game counts, whatever its
status: kuhy's library has 54 such games (CS2, Garry's Mod, TF2, ...), and VAC
runs inside Valve's client, so those stay on Valve's own setup.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import time
import urllib.error
from steam_installer import _http
URL = (
"https://raw.githubusercontent.com/AreWeAntiCheatYet/AreWeAntiCheatYet/"
"HEAD/games.json"
)
CACHE = Path.home() / ".cache" / "steam-game-installer" / "anticheat-games.json"
def _download() -> bytes:
with _http.open_https(URL, timeout=20) as response:
return response.read()
def _ids(raw: bytes | str) -> set[int]:
"""Steam ids in a games.json; ValueError/TypeError when it is not one."""
games = json.loads(raw)
if not isinstance(games, list):
msg = "games.json is not a list"
raise TypeError(msg)
ids: set[int] = set()
for game in games:
stores = game.get("storeIds") if isinstance(game, dict) else None
steam = stores.get("steam") if isinstance(stores, dict) else None
if isinstance(steam, str) and steam.isdigit():
ids.add(int(steam))
return ids
def steam_ids(cache: Path = CACHE, max_age: float | None = None) -> set[int] | None:
"""Anti-cheat Steam app ids, or None when no list can be had.
With *max_age* (seconds), a cache younger than that is used as it is, so a
caller that must answer fast (the web view) never waits on the network.
"""
if max_age is not None:
try:
if time.time() - cache.stat().st_mtime < max_age:
return _ids(cache.read_bytes())
except OSError, ValueError, TypeError:
pass
try:
raw = _download()
ids = _ids(raw)
# URLError is an OSError; named so the handler reads as network failure.
except urllib.error.URLError, OSError, ValueError, TypeError:
try:
return _ids(cache.read_bytes())
except OSError, ValueError, TypeError:
return None
cache.parent.mkdir(parents=True, exist_ok=True)
tmp = cache.with_name(f"{cache.name}.tmp{os.getpid()}")
tmp.write_bytes(raw)
tmp.replace(cache)
return ids

View File

@ -1,229 +0,0 @@
"""App metadata (name, installdir, depots, build) from Steam's local app cache."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from steam_installer import appinfo_cache, errors
# depotdownloader is never given -branch, so it always fetches this one.
PUBLIC_BRANCH = "public"
class AppInfoError(errors.InstallerError):
"""Steam's app info is missing or unreadable."""
@dataclass
class AppMetadata:
"""What the installer needs to know about one app, from Steam's cache."""
appid: int
name: str
installdir: str
@dataclass
class DepotPlan:
"""Which depots a given (os, language) install is actually supposed to contain.
Needed to check that a download finished. "Every depot in app_info" is the
wrong bar: KCD2 lists 12 depots but an english/windows install only ever
fetches 3 of them, the rest being other languages, DLC and other platforms.
"""
required: set[str]
shared: set[str]
# depot id -> the DLC app it belongs to. Steam writes that dlcappid into
# InstalledDepots, and a DLC depot recorded without it is not credited.
dlc: dict[str, str] = field(default_factory=dict)
# depot id -> the manifest gid the public branch ships, for every depot in
# the app's list. A cached depot manifest matching it proves the build.
manifests: dict[str, str] = field(default_factory=dict)
# shared depot id -> the app it is installed under (its `depotfromapp`).
# A manifest written from scratch records these as SharedDepots.
shared_owner: dict[str, str] = field(default_factory=dict)
@property
def all_expected(self) -> set[str]:
"""Every depot the install should end up with."""
return self.required | self.shared
def cached_blocks(appids: list[int]) -> dict[int, dict[str, Any]]:
"""App info for those of `appids` Steam's local cache holds.
Read from `appcache/appinfo.vdf` (see :mod:`appinfo_cache`), not from
steamcmd: this tool no longer runs steamcmd at all.
"""
try:
apps = appinfo_cache.load()
except appinfo_cache.CacheError as exc:
raise AppInfoError(str(exc)) from exc
return {appid: apps[appid] for appid in appids if appid in apps}
def _fetch_app_blocks(appids: list[int]) -> dict[int, dict[str, Any]]:
"""App info for every id in `appids`; a missing one is an error with the fix."""
blocks = cached_blocks(appids)
missing = [str(appid) for appid in appids if appid not in blocks]
if missing:
msg = (
f"app {', '.join(missing)} is not in Steam's local app cache: "
f"{appinfo_cache.FIX}"
)
raise AppInfoError(msg)
return blocks
def fetch_app_block(appid: int) -> dict[str, Any]:
"""App info for one id; a missing one is an error with the fix."""
return _fetch_app_blocks([appid])[appid]
def get_metadata(appid: int) -> AppMetadata:
"""Fetch the fields this project actually needs: display name and installdir."""
app_block = fetch_app_block(appid)
common = app_block.get("common", {})
if not isinstance(common, dict):
msg = f"no 'common' section in app info for {appid}"
raise AppInfoError(msg)
name = common.get("name")
if not isinstance(name, str):
msg = f"no name field found for app {appid}"
raise AppInfoError(msg)
installdir = common.get("installdir")
if not isinstance(installdir, str):
config = app_block.get("config", {})
installdir = config.get("installdir") if isinstance(config, dict) else None
if not isinstance(installdir, str):
msg = f"no installdir field found for app {appid}"
raise AppInfoError(msg)
return AppMetadata(appid=appid, name=name, installdir=installdir)
def get_build_id(appid: int, branch: str = "public") -> str | None:
"""Current buildid for `branch`, used to sanity-check the manifest we write."""
app_block = fetch_app_block(appid)
depots = app_block.get("depots", {})
if not isinstance(depots, dict):
return None
branches = depots.get("branches", {})
if not isinstance(branches, dict):
return None
entry = branches.get(branch, {})
if not isinstance(entry, dict):
return None
build_id = entry.get("buildid")
return build_id if isinstance(build_id, str) else None
def get_depot_plan(
appid: int, language: str = "english", os_name: str = "windows"
) -> DepotPlan:
"""Depots an (os, language) install should end up with.
Skips depots belonging to another language, another OS, a DLC (`dlcappid`)
or marked `optional` -- none of those are fetched by a default install, so
demanding them would make a healthy download look incomplete.
"""
app_block = fetch_app_block(appid)
depots = app_block.get("depots", {})
if not isinstance(depots, dict):
msg = f"no 'depots' section in app info for {appid}"
raise AppInfoError(msg)
plan = _plan_from_depots(appid, depots, language, os_name)
# Tag the game's own list's DLC depots too: depotdownloader fetches the
# owned ones in the base run, and Steam records each with its dlcappid.
for depot_id, entry in depots.items():
if isinstance(entry, dict) and isinstance(entry.get("dlcappid"), str):
plan.dlc[depot_id] = entry["dlcappid"]
gid = _public_gid(entry)
if gid is not None:
plan.manifests[depot_id] = gid
return plan
def _public_gid(entry: object) -> str | None:
"""The manifest gid a depot ships on the public branch, if it ships one."""
manifests = entry.get("manifests") if isinstance(entry, dict) else None
public = manifests.get(PUBLIC_BRANCH) if isinstance(manifests, dict) else None
gid = public.get("gid") if isinstance(public, dict) else None
return gid if isinstance(gid, str) else None
def get_dlc_plans(
appid: int, language: str = "english", os_name: str = "windows"
) -> dict[int, dict[str, str]]:
"""Map each DLC app id to the {depot: public gid} it installs itself.
Only DLC with depots of its own appear.
Some DLC (Cyberpunk 2077's Phantom Liberty, app 2138330, ~25 GB) keeps its
content under its own app id rather than in the game's depot list, so a
depotdownloader run for the game never sees it. DLC with no depots of its
own, or whose depots the game already lists, needs no run of its own.
"""
app_block = fetch_app_block(appid)
extended = app_block.get("extended", {})
listed = extended.get("listofdlc", "") if isinstance(extended, dict) else ""
dlc_ids = [int(x) for x in str(listed).split(",") if x.strip().isdigit()]
if not dlc_ids:
return {}
game_depots = app_block.get("depots", {})
game_depot_ids = set(game_depots) if isinstance(game_depots, dict) else set()
plans: dict[int, dict[str, str]] = {}
# A DLC the cache lacks is not owned: Steam caches app info for every app
# the account owns (1828 of 7102 listed DLC ids on 2026-11-22), and
# depotdownloader would refuse an unowned one anyway.
for dlc_id, dlc_block in cached_blocks(dlc_ids).items():
depots = dlc_block.get("depots", {})
if not isinstance(depots, dict):
continue
plan = _plan_from_depots(dlc_id, depots, language, os_name)
# Every required depot has a public gid: the plan only takes those.
own = {d: _public_gid(depots[d]) for d in plan.required - game_depot_ids}
if own:
plans[dlc_id] = own
return plans
def _plan_from_depots(
appid: int, depots: dict[str, Any], language: str, os_name: str
) -> DepotPlan:
"""The depots of one app's `depots` section that an (os, language) install gets."""
required: set[str] = set()
shared: set[str] = set()
shared_owner: dict[str, str] = {}
for depot_id, entry in depots.items():
if not depot_id.isdigit() or not isinstance(entry, dict):
continue
# A shared depot is installed once under its owning app, not here.
if "depotfromapp" in entry or "sharedinstall" in entry:
shared.add(depot_id)
if isinstance(entry.get("depotfromapp"), str):
shared_owner[depot_id] = entry["depotfromapp"]
continue
# Another app's DLC is not part of this install -- but a DLC app's own
# depots carry its own id as dlcappid, and are exactly what it installs.
dlc_owner = entry.get("dlcappid")
if (dlc_owner and dlc_owner != str(appid)) or entry.get("optional") == "1":
continue
# A placeholder (BG3 lists 1419654 as `{}`): no manifest on the branch
# depotdownloader fetches means nothing to download, so never missing.
if _public_gid(entry) is None:
continue
config = entry.get("config", {})
config = config if isinstance(config, dict) else {}
oslist = config.get("oslist")
if isinstance(oslist, str) and oslist and os_name not in oslist.split(","):
continue
depot_language = config.get("language")
if isinstance(depot_language, str) and depot_language != language:
continue
required.add(depot_id)
return DepotPlan(required=required, shared=shared, shared_owner=shared_owner)

View File

@ -1,91 +0,0 @@
"""Read app info from the Steam client's own cache, `appcache/appinfo.vdf`.
This replaced `steamcmd +app_info_print`. On 2026-11-22 all 11 compared
fields for app 1201270 (name, installdir, build id, change number, depot
gids, ...) matched steamcmd's answer exactly. The cache is only as fresh as
Steam's last run, which is why callers check its gids against what
depotdownloader actually fetched.
Layout (magic 0x07564429): u32 magic, u32 universe, i64 offset of a string
table; then per app: u32 appid, u32 size, `size` bytes made of a 60-byte
header and binary key-values whose keys are u32 indexes into the string
table. Appid 0 ends the list. The table is a u32 count followed by
NUL-terminated strings.
Every scalar comes back as a string, the way `app_info_print` printed it:
the rest of the tool compares `== "1"` and `!= str(appid)`, and an int there
would silently change which depots count.
"""
from __future__ import annotations
import struct
from typing import TYPE_CHECKING, Any
from steam_installer import errors
from steam_installer.appinfo_kv import (
HEADER,
MAGIC,
AppinfoFormatError,
read_block,
string_table,
)
from steam_installer.library import find_steam_root
if TYPE_CHECKING:
from pathlib import Path
FIX = "start Steam once, let it sync, rerun"
_memo: dict[Path, tuple[tuple[int, int], dict[int, dict[str, Any]]]] = {}
class CacheError(errors.InstallerError):
"""Steam's appinfo cache cannot be read."""
def default_path() -> Path:
"""Where Steam keeps its binary appinfo cache."""
return find_steam_root() / "appcache" / "appinfo.vdf"
def load(path: Path | None = None) -> dict[int, dict[str, Any]]:
"""Every app in the cache, appid -> its `appinfo` block.
Parsed once per file version: four lookups in one run would otherwise
parse the ~100 MB file four times.
"""
path = path or default_path()
try:
stat = path.stat()
except OSError as exc:
msg = f"cannot read Steam's app cache {path}: {FIX}"
raise CacheError(msg) from exc
key = (stat.st_mtime_ns, stat.st_size)
cached = _memo.get(path)
if cached is not None and cached[0] == key:
return cached[1]
apps = _parse(path.read_bytes())
_memo[path] = (key, apps)
return apps
def _parse(buf: bytes) -> dict[int, dict[str, Any]]:
magic, _universe, table_offset = struct.unpack_from("<IIq", buf, 0)
if magic != MAGIC:
msg = f"unsupported appinfo.vdf format {magic:#010x}"
raise CacheError(msg)
strings = string_table(buf, table_offset)
apps: dict[int, dict[str, Any]] = {}
pos = 16
while True:
appid, size = struct.unpack_from("<II", buf, pos)
if appid == 0:
return apps
try:
data, _ = read_block(buf, pos + 8 + HEADER, strings)
except AppinfoFormatError as exc:
raise CacheError(str(exc)) from exc
inner = data.get("appinfo")
apps[appid] = inner if isinstance(inner, dict) else data
pos += 8 + size

View File

@ -1,68 +0,0 @@
"""Binary key-value decoding shared by both readers of ``appinfo.vdf``.
``steam_installer.appinfo_cache`` (every app) and
``steam_backlog_enforcer._appinfo_cache`` (selected apps) read the same v29
layout; this module holds the parts they have in common: the string table and
the nested key-value blocks. It raises ``AppinfoFormatError`` (a ``ValueError``)
and each reader keeps the exception type its callers already handle.
"""
from __future__ import annotations
import struct
from typing import Any, Final
MAGIC: Final = 0x07564429
HEADER: Final = 60
# KV type bytes: a nested block, a NUL-terminated string, end of block.
_BLOCK: Final = 0
_STRING: Final = 1
_END: Final = 8
# Fixed-width value types: KV type byte -> struct format.
_SCALARS: Final = {2: "<i", 3: "<f", 4: "<i", 6: "<i", 7: "<Q", 10: "<q"}
class AppinfoFormatError(ValueError):
"""A key-value block holds a value type this decoder does not know."""
def string_table(buf: bytes, offset: int) -> list[str]:
"""The NUL-terminated strings (u32 count first) that keys index into."""
(count,) = struct.unpack_from("<I", buf, offset)
pos = offset + 4
out: list[str] = []
for _ in range(count):
end = buf.index(b"\0", pos)
out.append(buf[pos:end].decode("utf-8", "replace"))
pos = end + 1
return out
def read_block(buf: bytes, pos: int, strings: list[str]) -> tuple[dict[str, Any], int]:
"""Decode one key-value block at *pos*; return it and the next position.
Every scalar comes back as a string, as Steam's text VDF prints it.
"""
out: dict[str, Any] = {}
while True:
kind = buf[pos]
pos += 1
if kind == _END:
return out, pos
(index,) = struct.unpack_from("<I", buf, pos)
pos += 4
key = strings[index]
if kind == _BLOCK:
out[key], pos = read_block(buf, pos, strings)
elif kind == _STRING:
end = buf.index(b"\0", pos)
out[key] = buf[pos:end].decode("utf-8", "replace")
pos = end + 1
elif kind in _SCALARS:
fmt = _SCALARS[kind]
(value,) = struct.unpack_from(fmt, buf, pos)
out[key] = str(value)
pos += struct.calcsize(fmt)
else:
msg = f"unsupported value type {kind} in appinfo.vdf"
raise AppinfoFormatError(msg)

View File

@ -1,226 +0,0 @@
"""Entry point: resolve, confirm, adopt what exists, download, recognize."""
from __future__ import annotations
import logging
import sys
from typing import TYPE_CHECKING
from steam_installer import (
cli_args,
config,
deps,
errors,
flow,
ghost,
map_installed,
resolve,
runlog,
takeover,
target,
)
from steam_installer.job import Job
from steam_installer.library import find_steam_root, list_libraries, pick_install_target
if TYPE_CHECKING:
import argparse
from pathlib import Path
def main(argv: list[str] | None = None) -> int:
"""Run the installer; return the process exit code."""
parser = cli_args.build_parser()
args = parser.parse_args(argv)
if not (args.repair_ghosts or args.map_installed) and not (
args.appid or args.target
):
parser.error(
"provide an AppID, a Steam URL, a game name, "
"--repair-ghosts or --map-installed"
)
map_installed.check_arguments(parser, args)
literal = target.parse_literal(args.target) if args.target else None
log = runlog.setup(
args.appid or (literal[0] if literal else None), verbose=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.
logger.info("Run log: %s", log.path)
logger.debug("argv: %s", sys.argv)
# Any Exception ends in "log it, exit 1" plus the run-log path, as before.
with errors.CrashGuard(logger, log.path):
return _run(args, log)
return 1
def _is_interactive(args: argparse.Namespace) -> bool:
return sys.stdin.isatty() and not args.yes
def _ask(args: argparse.Namespace, question: str, *, interactive: bool) -> 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
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,
)
continue
ghost.repair(report, logger)
logger.info("Run log: %s", log.path)
return 0
def _describe(
logger: logging.Logger,
install_target: Path,
report: ghost.GhostReport,
staged: takeover.Staged | None,
) -> 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 _log_error(logger: logging.Logger, exc: Exception) -> None:
"""Log the message alone, with no traceback: these are user errors."""
logger.log(logging.ERROR, "%s", exc)
def _resolve(
args: argparse.Namespace, logger: logging.Logger, *, interactive: bool
) -> target.Resolved | int:
"""Resolve the target, or return the exit code for a failure already logged."""
try:
deps.require()
return target.resolve_target(args.target, args.appid, interactive=interactive)
except deps.DependencyError as exc:
_log_error(logger, exc)
return 1
except (target.TargetError, resolve.ResolveError) as exc:
_log_error(logger, exc)
return 2
def _pick_username(
args: argparse.Namespace, logger: logging.Logger, *, interactive: bool
) -> str | None:
"""Return the Steam username, or None after logging why there is none."""
try:
return config.resolve_username(args.username, interactive=interactive)
except config.ConfigError as exc:
_log_error(logger, exc)
return None
def _run(args: argparse.Namespace, log: runlog.RunLog) -> int:
if args.repair_ghosts:
return _repair_ghosts(log)
if args.map_installed:
return map_installed.run(args, log, find_steam_root())
return _run_install(args, log)
def _run_install(args: argparse.Namespace, log: runlog.RunLog) -> int:
logger = log.logger
interactive = _is_interactive(args)
resolved = _resolve(args, logger, interactive=interactive)
if isinstance(resolved, int):
return resolved
metadata = resolved.metadata
logger.info(
"Confirmed: %s (appid %s, matched by %s)",
metadata.name,
metadata.appid,
resolved.source,
)
steam_root = find_steam_root()
libraries = list_libraries(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, 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: steam_installer/run.sh --repair-ghosts",
metadata.appid,
)
return 1
username = _pick_username(args, logger, interactive=interactive)
if username is None:
return 1
logger.info("Install target: %s", install_target)
if not _ask(args, "Proceed? [y/N]: ", interactive=interactive):
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,
steam_root=steam_root,
job=Job(
library=library,
metadata=metadata,
install_target=install_target,
staged=staged,
username=username,
language=language,
),
)
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -1,70 +0,0 @@
"""Command-line argument definitions for the installer."""
from __future__ import annotations
import argparse
from kuhy_credit import credit_line
from steam_installer import depotdl, map_installed
def build_parser() -> argparse.ArgumentParser:
"""Build the installer's argument parser."""
parser = argparse.ArgumentParser(
description="Download an owned Steam game fast, then make Steam recognize it.",
# kuhy's shared credit line (kuhy_credit, kuhyx/utils).
epilog=credit_line(),
)
parser.add_argument(
"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(
"--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."
),
)
map_installed.add_arguments(parser)
parser.add_argument(
"--verbose",
action="store_true",
help="Show on the console everything that goes to the run log.",
)
return parser

View File

@ -1,100 +0,0 @@
"""Run the per-game decision and, when it says so, write the mapping.
Shared by the install flow (right after the manifest is finished, while Steam
is still closed) and by `--map-installed`. The decision rules live in
:mod:`compat_decide`, the config.vdf edit in :mod:`compat_map`.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from steam_installer import anticheat, appinfo, compat_decide, compat_map, proton_pkg
if TYPE_CHECKING:
import logging
from pathlib import Path
VALVE_PROTON = "--valve-proton"
TOOL_DIR = "compatibilitytools.d/proton-cachyos-native"
class Context:
"""What every decision in one run shares: fetched once, not per game."""
def __init__(
self,
steam_root: Path,
extra_overrides: dict[str, str] | None = None,
*,
anticheat_max_age: float | None = None,
) -> None:
"""Remember what every decision in this run shares.
*anticheat_max_age* lets a fast reader reuse a recent anti-cheat list
instead of downloading it (``anticheat.steam_ids``).
"""
self.steam_root = steam_root
self.config = compat_map.config_path(steam_root)
self.anticheat = anticheat.steam_ids(max_age=anticheat_max_age)
self.overrides = {**compat_decide.load_overrides(), **(extra_overrides or {})}
self.tool_ready = compat_decide.tool_ready(
steam_root / TOOL_DIR, proton_pkg.read_lock().version
)
def decide(
self, appid: int, block: dict[str, Any], *, owned_dlc: bool
) -> compat_decide.Decision:
"""Decide whether *appid* maps to the native Proton."""
facts = compat_decide.Facts(
anticheat=self.anticheat,
overrides=self.overrides,
tool_ready=self.tool_ready,
)
return compat_decide.decide(appid, block, facts, owned_dlc=owned_dlc)
def after_install(
steam_root: Path,
appid: int,
*,
owned_dlc: bool,
valve_proton: bool,
logger: logging.Logger,
) -> None:
"""Map a freshly installed game, or say why it keeps Valve's default.
Never fails the install: a game left unmapped still runs on Valve's
Proton, exactly as before this tool knew about compat tools.
"""
extra = {str(appid): VALVE_PROTON} if valve_proton else {}
try:
context = Context(steam_root, extra)
decision = context.decide(
appid, appinfo.fetch_app_block(appid), owned_dlc=owned_dlc
)
if not decision.map:
logger.info("Compat tool: %s", decision.describe())
return
outcome = compat_map.map_app(context.config, appid)
except (
appinfo.AppInfoError,
compat_map.CompatMapError,
OSError,
ValueError,
) as exc:
logger.warning(
"Compat tool not set (%s); the game stays on Valve's default.", exc
)
return
report(logger, appid, outcome)
def report(logger: logging.Logger, appid: int, outcome: compat_map.Outcome) -> None:
"""Log what happened to *appid*'s compat mapping."""
if outcome.action == "kept":
logger.info("Compat tool for %s kept: %s", appid, outcome.detail)
elif outcome.action == "already":
logger.info("Compat tool for %s: already mapped to %s.", appid, compat_map.TOOL)
else:
logger.info("Compat tool for %s: mapped to %s.", appid, compat_map.TOOL)

View File

@ -1,114 +0,0 @@
"""Decide per game whether Steam may run it on the native Proton.
Only a game this can prove safe is mapped: Windows-only (the app, every depot
and every launch option), no shared depots, no owned DLC depot, not in the
anti-cheat list, not overridden. Anything else keeps Valve's default, so
Valve's tools come back while that game is installed -- every game stays
playable. When unsure, the answer is no.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import json
from pathlib import Path
OVERRIDES = Path(__file__).parent / "data" / "compat_overrides.json"
@dataclass
class Decision:
"""Whether one game goes on the native Proton, and why."""
appid: int
reasons: list[str] = field(default_factory=list)
@property
def map(self) -> bool:
"""Whether the game gets the native Proton."""
return not self.reasons
def describe(self) -> str:
"""One line naming the verdict and its reasons."""
return "map" if self.map else f"Valve default: {', '.join(self.reasons)}"
def load_overrides(path: Path = OVERRIDES) -> dict[str, str]:
"""`{appid: reason}` for games that break on the native build."""
data = json.loads(path.read_text())
if not isinstance(data, dict) or not all(
key.isdigit() and isinstance(reason, str) for key, reason in data.items()
):
msg = f"{path.name}: compat_overrides must map app ids to reasons"
raise ValueError(msg)
return data
def tool_ready(tool_dir: Path, pinned_version: str) -> bool:
"""The tool is there and is the exact pinned, verified build."""
stamp = tool_dir / "VERSION"
return (
(tool_dir / "toolmanifest.vdf").is_file()
and stamp.is_file()
and stamp.read_text().strip() == pinned_version
)
def _oses(value: object) -> set[str]:
return {os for os in value.split(",") if os} if isinstance(value, str) else set()
def _dicts(section: object) -> list[dict]:
if not isinstance(section, dict):
return []
return [entry for entry in section.values() if isinstance(entry, dict)]
def _config_oslist(entry: dict) -> set[str]:
config = entry.get("config")
return _oses(config.get("oslist")) if isinstance(config, dict) else set()
def _platform_reasons(block: dict) -> list[str]:
common = block.get("common")
app_oses = _oses(common.get("oslist")) if isinstance(common, dict) else set()
depots = _dicts(block.get("depots"))
config = block.get("config")
launches = _dicts(config.get("launch")) if isinstance(config, dict) else []
oses = app_oses.union(*(_config_oslist(e) for e in depots + launches))
reasons = []
if not app_oses:
reasons.append("no OS list")
if "linux" in oses:
reasons.append("native")
if oses - {"windows", "linux"}:
reasons.append("not Windows-only")
if any("depotfromapp" in d or "sharedinstall" in d for d in depots):
reasons.append("shared depots")
return reasons
@dataclass(frozen=True)
class Facts:
"""What every decision in one run shares: fetched once, not per game."""
anticheat: set[int] | None
overrides: dict[str, str]
tool_ready: bool
def decide(appid: int, block: dict, facts: Facts, *, owned_dlc: bool) -> Decision:
"""Every reason `appid` must keep Valve's default; none means map it."""
reasons: list[str] = []
if facts.anticheat is None:
reasons.append("anti-cheat list unavailable")
elif appid in facts.anticheat:
reasons.append("anti-cheat")
reasons += _platform_reasons(block)
if owned_dlc:
reasons.append("owned DLC")
if str(appid) in facts.overrides:
reasons.append(f"override: {facts.overrides[str(appid)]}")
if not facts.tool_ready:
reasons.append("native Proton not installed")
return Decision(appid, reasons)

View File

@ -1,237 +0,0 @@
"""Map one game to the native Proton in Steam's `config/config.vdf`.
The entry goes under InstallConfigStore/Software/Valve/Steam/CompatToolMapping,
the same shape Steam writes for a per-game choice in its own UI:
"<appid>" { "name" "proton-cachyos-native" "config" "" "priority" "250" }
Steam itself records Valve's per-game defaults at priority 100. On 2026-11-22
Steam honoured a 250 entry: `compat_log.txt` named the native tool as the only
tool. A global default was never tested, so only per-game entries are written.
The file is edited as text, never round-tripped through a parser: every other
byte stays as Steam wrote it. It also holds private values (tokens, account
ids), so no line of it is ever logged or put in an error message -- errors
carry line numbers only. Steam rewrites the file from memory on exit, so a
write while it runs would be lost; it is refused.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import os
from pathlib import Path
import re
import tempfile
from steam_installer import errors, recognize
TOOL = "proton-cachyos-native"
PRIORITY = "250"
VALVE_PRIORITY = "100"
_STEAM = ("installconfigstore", "software", "valve", "steam")
_MAPPING = (*_STEAM, "compattoolmapping")
# A quoted string (escapes allowed, newlines too), a brace, or anything else.
_TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|[{}]|[^\s"{}]+')
class CompatMapError(errors.InstallerError):
"""Steam's config.vdf cannot be edited safely."""
@dataclass
class Outcome:
"""What editing the compat mapping did."""
action: str # "mapped", "already" or "kept"
detail: str = ""
@dataclass
class _Entry:
open_line: int # the `{` after the appid key
close_line: int = -1
values: dict[str, str] = field(default_factory=dict)
@dataclass
class _Layout:
lines: list[str]
steam_open: int = -1
mapping_open: int = -1
entry: _Entry | None = None
def config_path(steam_root: Path) -> Path:
"""Path of Steam's ``config.vdf`` under *steam_root*."""
return steam_root / "config" / "config.vdf"
def current(config: Path, appid: int) -> tuple[str, str] | None:
"""The (name, priority) the game is mapped to, or None when unmapped."""
entry = _scan(_read(config), str(appid)).entry
if entry is None:
return None
return entry.values.get("name", ""), entry.values.get("priority", "")
def keep_reason(entry: tuple[str, str] | None) -> Outcome | None:
"""Why :func:`map_app` would leave *entry* alone, or None when it would map.
*entry* is :func:`current`'s ``(name, priority)``. The native tool is
"already"; any other tool off Valve's priority is kuhy's own choice, "kept".
"""
name, priority = entry or ("", "")
if name == TOOL:
return Outcome("already")
if name and priority != VALVE_PRIORITY:
return Outcome("kept", f"already mapped to {name} (priority {priority})")
return None
def map_app(config: Path, appid: int) -> Outcome:
"""Point `appid` at the native Proton unless kuhy chose another tool."""
pids = recognize.steam_client_pids()
if pids:
msg = (
"Steam is running and would overwrite config.vdf on exit -- close it first"
)
raise CompatMapError(msg)
layout = _scan(_read(config), str(appid))
lines = layout.lines
entry = layout.entry
if entry is not None:
name = entry.values.get("name", "")
held = keep_reason((name, entry.values.get("priority", "")))
if held is not None:
return held
key_line = entry.open_line - 1
if (
lines[key_line].strip() != f'"{appid}"'
or lines[entry.close_line].strip() != "}"
):
msg = f"config.vdf line {key_line + 1}: unexpected layout"
raise CompatMapError(msg)
indent = _indent(lines[entry.open_line])
lines[key_line : entry.close_line + 1] = _entry(appid, indent)
_write(config, lines)
return Outcome("mapped", f"replaced Valve's choice {name or '(empty)'}")
if layout.mapping_open >= 0:
indent = _indent(lines[layout.mapping_open]) + "\t"
lines[layout.mapping_open + 1 : layout.mapping_open + 1] = _entry(appid, indent)
else:
one = _indent(lines[layout.steam_open]) + "\t"
block = [f'{one}"CompatToolMapping"\n', f"{one}{{\n"]
block += [*_entry(appid, one + "\t"), f"{one}}}\n"]
lines[layout.steam_open + 1 : layout.steam_open + 1] = block
_write(config, lines)
return Outcome("mapped")
def _read(config: Path) -> list[str]:
try:
return config.read_text(encoding="utf-8").splitlines(keepends=True)
except OSError as exc:
msg = f"cannot read {config}"
raise CompatMapError(msg) from exc
def _tokens(lines: list[str]) -> list[tuple[str, int, bool]]:
"""(text, line index, is_quoted) for every token; quoted values may span lines."""
text = "".join(lines)
starts = [0]
for line in lines:
starts.append(starts[-1] + len(line))
out: list[tuple[str, int, bool]] = []
line_no = 0
for match in _TOKEN.finditer(text):
while starts[line_no + 1] <= match.start():
line_no += 1
piece = match.group(0)
if piece[0] == '"':
out.append((piece[1:-1], line_no, True))
elif piece in "{}":
out.append((piece, line_no, False))
else:
msg = f"config.vdf line {line_no + 1}: unexpected layout"
raise CompatMapError(msg)
return out
def _scan(lines: list[str], appid: str) -> _Layout:
"""Find the Steam block, its mapping block and the app's entry."""
layout = _Layout(lines)
stack: list[str] = []
pending: str | None = None
for text, index, quoted in _tokens(lines):
entry = layout.entry if tuple(stack) == (*_MAPPING, appid) else None
if quoted:
if pending is None:
pending = text
continue
if entry is not None:
entry.values[pending.lower()] = text
pending = None
elif text == "{":
if pending is None:
msg = f"config.vdf line {index + 1}: block without a key"
raise CompatMapError(msg)
stack.append(pending.lower())
pending = None
_note_open(layout, tuple(stack), appid, index)
else:
if not stack or pending is not None:
msg = f"config.vdf line {index + 1}: unbalanced brace"
raise CompatMapError(msg)
if entry is not None:
entry.close_line = index
stack.pop()
if layout.steam_open < 0:
msg = "config.vdf has no InstallConfigStore/Software/Valve/Steam"
raise CompatMapError(msg)
return layout
def _note_open(layout: _Layout, path: tuple[str, ...], appid: str, index: int) -> None:
if (
path in (_STEAM, _MAPPING, (*_MAPPING, appid))
and layout.lines[index].strip() != "{"
):
msg = f"config.vdf line {index + 1}: unexpected layout"
raise CompatMapError(msg)
if path == _STEAM:
layout.steam_open = index
elif path == _MAPPING:
layout.mapping_open = index
elif path == (*_MAPPING, appid):
layout.entry = _Entry(open_line=index)
def _indent(line: str) -> str:
return line[: len(line) - len(line.lstrip())]
def _entry(appid: int, indent: str) -> list[str]:
inner = indent + "\t"
return [
f'{indent}"{appid}"\n',
f"{indent}{{\n",
f'{inner}"name"\t\t"{TOOL}"\n',
f'{inner}"config"\t\t""\n',
f'{inner}"priority"\t\t"{PRIORITY}"\n',
f"{indent}}}\n",
]
def _write(config: Path, lines: list[str]) -> None:
"""Replace the file atomically, keeping its permissions."""
mode = config.stat().st_mode & 0o777
fd, tmp = tempfile.mkstemp(dir=config.parent, prefix=".config.vdf.")
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write("".join(lines))
Path(tmp).chmod(mode)
Path(tmp).replace(config)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise

View File

@ -1,149 +0,0 @@
"""What ``--map-installed --apply`` would do, one structured row per game.
``map_installed.run`` logs from these rows and the enforcer's web view serves
them (``GET /api/compat``), so the two can never disagree and nothing ever
parses the log. ``changes`` uses the same :func:`compat_map.keep_reason` that
:func:`compat_map.map_app` uses, so a row says "changes" exactly when apply
would rewrite that game's entry.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any
from steam_installer import appinfo, compat_apply, compat_map, recognize
from steam_installer.library import SteamLibrary, list_libraries
if TYPE_CHECKING:
from pathlib import Path
# Steam's own compat tools and runtimes are apps too, but not games.
TOOL_TYPES = {"tool", "config"}
NOT_CACHED = "not in Steam's app cache"
@dataclass(frozen=True)
class Row:
"""One game's compat decision.
Attributes:
current: The tool config.vdf maps it to; None = unmapped (Valve's default).
priority: That mapping's priority, None when unmapped.
decided: The tool after apply; None = Valve's default.
reasons: Why the decision keeps Valve's default (empty = map it).
note: Why apply leaves an entry the decision would map ("already
mapped", or kuhy's own tool "kept: ...").
map: The decision's verdict.
changes: Whether apply would rewrite this game's entry.
cached: Whether Steam's app cache knows the game at all.
"""
appid: int
name: str
current: str | None
priority: str | None
decided: str | None
reasons: tuple[str, ...]
note: str | None
map: bool
changes: bool
cached: bool
def to_json(self) -> dict[str, object]:
"""The web contract's ``CompatRow``."""
data = asdict(self)
data["app_id"] = data.pop("appid")
data["reasons"] = list(self.reasons)
return data
def installed(libraries: list[SteamLibrary]) -> dict[int, dict[str, Any]]:
"""Appid -> AppState for every manifest in every library."""
found: dict[int, dict[str, Any]] = {}
for library in libraries:
for manifest in sorted(library.steamapps.glob("appmanifest_*.acf")):
appid = manifest.stem.removeprefix("appmanifest_")
if appid.isdigit():
found[int(appid)] = recognize.read_app_state(manifest)
return found
def owned_dlc(app_state: dict[str, Any]) -> bool:
"""Whether the manifest lists an owned DLC depot."""
depots = app_state.get("InstalledDepots")
entries = depots.values() if isinstance(depots, dict) else []
return any(isinstance(entry, dict) and "dlcappid" in entry for entry in entries)
def is_tool(block: dict[str, Any]) -> bool:
"""Whether the app is one of Steam's tools or runtimes, not a game."""
common = block.get("common")
kind = common.get("type", "") if isinstance(common, dict) else ""
return isinstance(kind, str) and kind.lower() in TOOL_TYPES
def _row(
context: compat_apply.Context,
appid: int,
block: dict[str, Any] | None,
app_state: dict[str, Any],
) -> Row:
entry = compat_map.current(context.config, appid)
current = (entry[0] or None) if entry else None
priority = (entry[1] or None) if entry else None
if block is None:
name = app_state.get("name", "")
return Row(
appid=appid,
name=name if isinstance(name, str) else "",
current=current,
priority=priority,
decided=current,
reasons=(NOT_CACHED,),
note=None,
map=False,
changes=False,
cached=False,
)
decision = context.decide(appid, block, owned_dlc=owned_dlc(app_state))
held = compat_map.keep_reason(entry) if decision.map else None
changes = decision.map and held is None
note = None
if held is not None:
note = "already mapped" if held.action == "already" else f"kept: {held.detail}"
common = block.get("common")
name = common.get("name", "?") if isinstance(common, dict) else "?"
return Row(
appid=appid,
name=str(name),
current=current,
priority=priority,
decided=compat_map.TOOL if changes else current,
reasons=tuple(decision.reasons),
note=note,
map=decision.map,
changes=changes,
cached=True,
)
def rows(
steam_root: Path,
appids: list[int] | None = None,
context: compat_apply.Context | None = None,
) -> list[Row]:
"""Rows for every installed game, or for exactly *appids* (tools included).
Raises:
appinfo.AppInfoError: Steam's app cache cannot be read.
"""
context = context or compat_apply.Context(steam_root)
states = installed(list_libraries(steam_root))
ids = appids if appids is not None else sorted(states)
blocks = appinfo.cached_blocks(ids)
return [
_row(context, appid, blocks.get(appid), states.get(appid, {}))
for appid in ids
if appids is not None or appid not in blocks or not is_tool(blocks[appid])
]

View File

@ -1,66 +0,0 @@
"""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 depotdownloader's `-remember-password` login token
(prompted through the pty in `runlog.run_logged`). Writing them 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
from steam_installer import errors
CONFIG_DIR = Path.home() / ".config" / "steam-game-installer"
CONFIG_PATH = CONFIG_DIR / "config"
USERNAME_KEY = "username"
ENV_VAR = "STEAM_USERNAME"
class ConfigError(errors.InstallerError):
"""The saved config is unusable or a username is missing."""
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:
msg = (
"No Steam username available. Pass --username, set "
f"${ENV_VAR}, or run once interactively to save one."
)
raise ConfigError(msg)
entered = input("Steam username: ").strip()
if not entered:
msg = "No Steam username entered."
raise ConfigError(msg)
save_username(entered)
return entered

View File

@ -1,53 +0,0 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: Hostname:
Version: Hockeypuck 2.2
xsDNBGERxNwBDAD1aEVN8rdWBlV2sOwkiW1ddO44xKjdumwuGhoXP1pUzK4SkNUb
IrQ1cenckdxzZsS8cbXTvEteC4K8tTYxobZpgzAPhKZNECsyCyDf2DEYv7bS75gy
sdl0bh+mOXPjvOe9IK3eFPQWWFd0erYyf9SHjlZ0utOg3qZ2JuVupGOH8W3taKth
ijR98RzUqP5rPoMPKcrOdBUiIREHx0y6SwdyX0c2XKm52T3cP8O0MPsvZLbRwGU0
DTyr7knzuGhR9tLxsy4PqKz3tSUEGM7PhFcpEoRFvV/4Al8/OpRaPj3zRn6RbL1D
9ZAH9OblgHkQlK6MPnLOygoaAvjreMHK3ykjlRugUtnRBmQHhH+o3iXb8Ep5GXjZ
XJZazy5ZSTbuJ8+DcjuC/G459ePnQ658od2Sxz5OBRmK3a1taAtgszHio1EHb8Db
OZ+Za5E46VOHM/8sl8toGbK4JOqpgdQ3YqIH4R915WqCYnMvfTQbCiHLYzWHrgAA
awBu3kaV2MagPnkAEQEAAc0bQ2FjaHlPUyA8YWRtaW5AY2FjaHlvcy5vcmc+wsEO
BBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEEiC3P5I4gUdSOJWKr
87YHSI2zWkcFAmTUdqcACgkQ87YHSI2zWkc2ygwAknD+O2LQeHp1tEYwplF9Rthq
uPN64IxC/8nAc+L92fSOkVJKUfRh0PJcCCZgpTBAa7UV++GsT9SZ8jRtUPDfAy/R
0TSwKkEC6b1291xNdV3O83CtkSJRTP39nVCefXrBUpIwmkQJuytBF1qypTuw4jom
orcbmE40O7uNDe0FpZOJkUxT1sVJqj+y2h4mJsDuEAYKVQa4809yDwlQOYlLg6i3
wEBut7PPh8bEFWycNElKseh3dpQfvFVWMcUBafpQq7Q9zVFDW3nCUkFBMErcLb0y
VARQizrO3GqmWSU0zmgs8ruc3HnYjIfLIU68JRDsLdFgzIstEasnOskdUYywdvYw
BeGpCQX2ZFcTosLrZc1SRAk/XKioVXeHA92dcQacBClzKCmbat0CcNng5phu9fom
xGbNijvV5NWmQITw7j2sco0nLtfx2MiyRlR8s6pgrZ/VgfGq5K2gM306MgshgyMW
oIELm7aUTkbY+QH4v0y+U/KUNeHetDZhsMLwZq1DwsEUBBMBCAA+FiEEiC3P5I4g
UdSOJWKr87YHSI2zWkcFAmERxNwCGwMFCQPCZwAFCwkIBwIGFQoJCAsCBBYCAwEC
HgECF4AACgkQ87YHSI2zWkcB8QwA5+lumQa7SItzfd5v7HJhDU9IEE6gvxhs9wPC
UxcZmbCVj4AoP0yLXshbKpbwfpXQN+CmlnNr+U9TmUe0q6f6L7qdqIAfDGOy2BOX
Xn/x1h5u7jeppUYpSiB4oZW2A6zHuWp1RyGSiPFO0W+k5awA8nBNnZpnCdZIjT2R
OWCpSOpGgR8V35joq/tUxje/A1W7oaHuWnuSIz8nEqHQc9xTXbU4tFab24cxRxV+
3U1wJ10jC0VoBPX2B7KhutgEIqwq9V2XOfRUAKO2u5IcKKwYFhjHa4O951rm+YoV
L2fj3BNeQwwwufofEHat4GhVXhvw+oZli3PMZ/9PZBf40/T5I4m+t+4nkpyyl3ng
Z8iW55gGKkcjgEmGBurmB+KuRbSBG6gQrYIfVvil+QFRVFh9yQJNKX7lzZpBv6M2
tc1kC8N0jV2pTjlTwjDhn5xm3qC00FHLuvp6kNNDpnkYxYhVYR5PVLE1TOyPqL4L
J3I93lNfpef8p6jjBEJXi6C8PL+mzsDNBGERxNwBDAC1RE2JFOjAMzqg3f5JsTa5
1WgApe2zlS/QjD+qr2LbC0CvQK3WO/MseqnEBfnXlUrL+tCzQXG79+kJk5xHsdaI
bblTqdX3xNbT0/+sJkLsUWbfLh1lTgs+NnltsCtg1cIKm/eOBEWyVfnrkKI+uTlQ
DDGcHW9XGaxLaIMi8FgaitMtrvH3AdajEpvpvdAAUbeIUL/hFs6VTSs74xJRxy0J
1eZYlZXo2YQ8EuZCAtyaQuvoDKijybxqj+FKPRiL920UI2emBYL0cwMRq1XylZST
7xXEzrEVgQ+xEUTBOUgmbRmIJVsSE/pDy7127dwPVpTglWiwfqntgdujrl6HM2b0
a6lV5/ZoeYL5ucu6bku0ewbkoEKhqTe1JSVYWbStW5hwGFBxCFxGpKQMMsDltmst
8Z0Ic1Bhes00gd7LAC0AK8OkWFs4sIbHinNBVXQH/5MINF2ngm9tP9kym17Nr5Jt
erbxOOyNYl+ZOq6HFsrMXMZ1Cx+d4diqK2GnSeCZIvMAEQEAAcLA/AQYAQgAJhYh
BIgtz+SOIFHUjiViq/O2B0iNs1pHBQJhEcTcAhsMBQkDwmcAAAoJEPO2B0iNs1pH
mFMMAOuyEJ93J4X5H+Jnf8/pXg2PFVvp0se7weCFha1d9umGSTrQEjivm55z1X4R
+Jt6D/cL3wN1WnayyNEtVzTD1CiuMDNO4a+qyBmE3/tJRWyIXoZ/wdNu38rRNO/S
dNbDWj0dCl6HCokLKSlfpP7996zymNeVX7yCw7T56jb2mTILTszyE0xYPVAKb8cR
Zt9gUTivxQ3SPw5xVe1OXcF0Dkwx2EAAm7Alo6DMCZlqTii8Xc6KYcaSRHNdlmkk
W3RcTMkNja5mRFhzygklh9ViXqQs+9gZB+VHDqB2iNKbHJwO40aLRo/bta1h9P0H
DD8q8mZWkZpGBlzul0x5UMedCeYudk9tOMwFCKRrhZeAyzMRn/+FXUw7oFiWX6RX
9ujq0O+Yna6WsWe+YN/vmT0KloTzRb0yqeDc37zc850+woYy+mNpV2+Tq6hBDajk
+BohvFyI7T4vvs45e+GwN2fTS6oqVsc9TfO7Q8JTi5y9UqByEbNCbqY/IeIwaapR
IqDYsg==
=N+41
-----END PGP PUBLIC KEY BLOCK-----

View File

@ -1 +0,0 @@
{}

View File

@ -1,7 +0,0 @@
# pacman-repo lock: the exact proton-cachyos-native build steam-game-installer
# installs. The dependency-freshness gate (kuhyx/utils, pacman-repo adapter)
# compares it with cachyos.db; bump version and sha256 together.
name=proton-cachyos-native
repo=https://mirror.cachyos.org/repo/x86_64/cachyos/cachyos.db
version=1:11.0.20261015-1
sha256=25bf302f90e8e01118555b997b873c3cd06a33b5647e79d049a59e29794b43e0

View File

@ -1,84 +0,0 @@
"""Wraps depotdownloader for the bulk content pull -- this is the fast path.
No `-depot` filter is passed: depotdownloader's own per-depot ownership check
(AccountHasAccess, checked before any key fetch) already skips depots the
account doesn't own and continues with the rest, as long as `-os` is set
correctly. Without `-os`, it defaults to the host OS and can filter out every
real (Windows-tagged) depot, leaving only stray OS-agnostic ones -- that's
what caused the very first "0 bytes from 0 depots" failure this project was
built to avoid.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from steam_installer import deps, runlog
if TYPE_CHECKING:
import logging
from pathlib import Path
DEFAULT_MAX_DOWNLOADS = 32
# Windows depots only: a game this tool can map to Proton ships no other kind.
OS_NAME = "windows"
# depotdownloader's licence check refusing a DLC app. The one failure that is
# expected: most games list DLC the account never bought.
NOT_OWNED_MARKER = "is not available from this account"
@dataclass(frozen=True)
class Pull:
"""Where and as whom depotdownloader pulls content, and in which language."""
install_dir: Path
username: str
language: str = "english"
max_downloads: int = DEFAULT_MAX_DOWNLOADS
def _command(appid: int, pull: Pull) -> list[str]:
return [
deps.depotdownloader_bin(),
"-app",
str(appid),
"-os",
OS_NAME,
"-language",
pull.language,
"-max-downloads",
str(pull.max_downloads),
"-username",
pull.username,
"-remember-password",
"-dir",
str(pull.install_dir),
]
def download(appid: int, pull: Pull, logger: logging.Logger) -> int:
"""Run depotdownloader against the install dir, streaming its progress live.
Returns the exit code rather than raising: the caller has to distinguish
"download failed" from "download fine, manifest step failed" to decide
whether touching the manifest is safe at all.
"""
pull.install_dir.mkdir(parents=True, exist_ok=True)
returncode, _ = runlog.run_logged(_command(appid, pull), logger)
return returncode
def download_dlc(dlc_appid: int, pull: Pull, logger: logging.Logger) -> bool | None:
"""Fetch one DLC app into the game's own install dir.
Returns True when downloaded, None when the account does not own it, and
False for any other failure -- which the caller must treat as fatal.
"""
returncode, output = runlog.run_logged(_command(dlc_appid, pull), logger)
if returncode == 0:
return True
return None if NOT_OWNED_MARKER in output else False

View File

@ -1,57 +0,0 @@
"""External binaries this tool shells out to, and a clear error when they're missing."""
from __future__ import annotations
import os
from pathlib import Path
import shutil
from steam_installer import errors
TOOL_HINTS = {
"depotdownloader": (
"Run steam_installer/install_deps.sh, "
"which fetches it from the SteamRE release."
),
}
# The copy install_deps.sh manages. Preferred over whatever PATH finds first: each
# depotdownloader binary keeps its remembered login in its own IsolatedStorage
# slot, keyed by its path. With an AUR copy in /usr/bin as well, a terminal run
# (PATH has ~/.local/bin) and a sudo'd run (secure_path does not) used two
# different binaries -- one logged in, one asking for a password nobody was
# there to type.
MANAGED_DEPOTDOWNLOADER = Path.home() / ".local" / "bin" / "depotdownloader"
class DependencyError(errors.InstallerError):
"""A tool this installer shells out to is missing."""
def depotdownloader_bin() -> str:
"""The depotdownloader to run: install_deps.sh's own copy, else PATH's."""
if os.access(MANAGED_DEPOTDOWNLOADER, os.X_OK):
return str(MANAGED_DEPOTDOWNLOADER)
return "depotdownloader"
def missing_tools() -> list[str]:
"""Which required binaries are not on PATH, in the order they'd be used.
steamcmd is not one of them: app info comes from Steam's own cache and
the manifest is written by this tool.
"""
needed = ["depotdownloader"]
resolved = {"depotdownloader": depotdownloader_bin()}
return [tool for tool in needed if shutil.which(resolved.get(tool, tool)) is None]
def require() -> None:
"""Fail with the fix when a required tool is missing."""
missing = missing_tools()
if missing:
details = "; ".join(
f"`{tool}` not found -- {TOOL_HINTS[tool]}" for tool in missing
)
raise DependencyError(details)

View File

@ -1,49 +0,0 @@
"""Owned DLC that ships as an app of its own, fetched next to the base game.
depotdownloader's `-app <game>` run only walks the game's own depot list. DLC
such as Cyberpunk 2077's Phantom Liberty (app 2138330, ~25 GB) keeps its depot
under its own app id, so that run never touches it -- and the Steam client,
restarted onto a manifest without it, then downloaded all 24 GB at its own
pace. Each such DLC now gets a depotdownloader run of its own into the same
install dir, where the manifest step picks its depot up from the cache.
Ownership is left to depotdownloader's licence check. Its refusal is the one
failure that is expected (games list DLC nobody bought); anything else aborts
the install before the manifest is touched, like a failed base download.
"""
from __future__ import annotations
from steam_installer import appinfo, depotdl, runlog
def download_owned(
appid: int, pull: depotdl.Pull, log: runlog.RunLog
) -> appinfo.DepotPlan | None:
"""Download every owned DLC of `appid` that has depots of its own.
Returns:
The DLC depots now downloaded -- each credited to its DLC app, with
its public gid -- or None if a DLC download failed for a reason other
than not owning it.
"""
logger = log.logger
plans = appinfo.get_dlc_plans(appid, pull.language)
downloaded = appinfo.DepotPlan(required=set(), shared=set())
for dlc_appid, depots in sorted(plans.items()):
log.section(f"depotdownloader DLC {dlc_appid}")
outcome = depotdl.download_dlc(dlc_appid=dlc_appid, pull=pull, logger=logger)
if outcome is None:
logger.info("DLC %d is not owned by this account -- skipped.", dlc_appid)
continue
if not outcome:
logger.error(
"depotdownloader failed for DLC %d -- not touching the manifest.",
dlc_appid,
)
return None
logger.info("Downloaded DLC %d (depots %s).", dlc_appid, sorted(depots))
downloaded.required |= set(depots)
downloaded.dlc.update(dict.fromkeys(depots, str(dlc_appid)))
downloaded.manifests.update(depots)
return downloaded

View File

@ -1,45 +0,0 @@
"""Base class of every error this package raises on purpose, and the crash guard."""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import logging
from pathlib import Path
from types import TracebackType
class InstallerError(Exception):
"""A failure the installer reports and exits on, as opposed to a bug."""
class CrashGuard:
"""Context manager: log any ``Exception`` with the run-log path, swallow it.
``try/except Exception`` would say the same, but pylint's broad-exception
check rejects it. ``KeyboardInterrupt`` and other ``BaseException`` pass.
"""
def __init__(self, logger: logging.Logger, log_path: Path) -> None:
"""Remember where a crash is reported."""
self.logger = logger
self.log_path = log_path
def __enter__(self) -> None:
"""Nothing to set up."""
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> bool:
"""Report an ``Exception`` and swallow it; let everything else pass."""
if not isinstance(exc, Exception):
return False
self.logger.error(
"Run failed with an unhandled error", exc_info=(exc_type, exc, tb)
)
self.logger.info("Run log (send this): %s", self.log_path)
return True

View File

@ -1,101 +0,0 @@
"""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.
It patches the manifest Steam (or the backlog enforcer) already wrote, and
writes one from scratch when none exists -- steamcmd, which used to create
it, is no longer run. Either way every precondition is checked first.
"""
from __future__ import annotations
import time
from typing import TYPE_CHECKING
from steam_installer import appinfo, finish_check, manifest_write, recognize, runlog
from steam_installer.manifest_depots import Proven
if TYPE_CHECKING:
from pathlib import Path
from steam_installer.library import SteamLibrary
def finish(
log: runlog.RunLog,
library: SteamLibrary,
metadata: appinfo.AppMetadata,
target: Path,
depot_plan: appinfo.DepotPlan,
) -> int:
"""Finish the manifest and close out the run."""
logger = log.logger
expected_build_id = appinfo.get_build_id(metadata.appid)
manifest_path = library.steamapps / f"appmanifest_{metadata.appid}.acf"
seed = None
if manifest_path.is_file():
app_state = recognize.read_app_state(manifest_path)
else:
# Nothing on disk to patch. Build the manifest in memory and write it
# only once every check below has passed: a StateFlags=4 file left
# behind by a refused run would make Steam fetch the whole game.
logger.info("No %s yet -- writing one from scratch.", manifest_path.name)
seed = manifest_write.seed_app_state(
metadata.appid, metadata.name, target.name, depot_plan.shared_owner
)
app_state = seed
problems = finish_check.check_ready_to_finish(
install_dir=target,
app_state=app_state,
required_depots=depot_plan.required,
expected_build_id=expected_build_id,
expected_manifests=depot_plan.manifests,
)
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)
build_proven = finish_check.build_proven(
recognize.discover_cached_depot_manifests(target),
depot_plan.required,
depot_plan.manifests,
)
written = manifest_write.finish_manifest_manually(
library=library,
appid=metadata.appid,
install_dir=target,
now_unix=int(time.time()),
proven=Proven(
dlc_depots=depot_plan.dlc,
seed=seed,
# Proven depot by depot, so it outranks whatever the manifest says.
build_id=expected_build_id if build_proven else None,
),
)
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

@ -1,142 +0,0 @@
"""The fail-closed preconditions for hand-finishing a manifest.
Split out of recognize.py (250-line cap). Everything here only *reads*; the
write it gates lives in :mod:`manifest_write`.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from steam_installer import manifest_write, recognize
if TYPE_CHECKING:
from pathlib import Path
def check_ready_to_finish(
install_dir: Path,
app_state: dict[str, Any],
required_depots: set[str],
expected_build_id: str | None,
expected_manifests: dict[str, str] | None = None,
) -> list[str]:
"""Reasons the manifest must NOT be hand-finished. Empty list means go ahead.
Every one of these was a real failure mode: writing StateFlags=4 after a
steamcmd run that did nothing turned a dead run into a reported success.
"""
problems: list[str] = []
# An empty required set would make the depot check below vacuously true and
# wave through a download that fetched nothing. It means the depot filter
# matched no depot at all (wrong language or OS for this app), not that
# there is nothing to install.
if not required_depots:
problems.append(
"no depots match this app for the chosen language/OS -- refusing to "
"guess that the install is complete"
)
cached = recognize.discover_cached_depot_manifests(install_dir)
# `finish_manifest_manually` drops depots the on-disk manifest lists under
# SharedDepots, which is a different source of truth from app_info's
# depotfromapp/sharedinstall. If they disagree it can end up with nothing to
# install and raise -- and by then clear_steam_staging has already deleted
# Steam's resumable staging tree. Catch the disagreement here, while
# refusing is still free.
shared = app_state.get("SharedDepots")
shared_ids = set(shared) if isinstance(shared, dict) else set()
if cached and set(cached) <= shared_ids:
problems.append(
"every cached depot is listed under SharedDepots in the existing "
"manifest, so there would be nothing to record as installed"
)
missing = sorted(required_depots - set(cached))
if missing:
problems.append(
f"depot(s) {', '.join(missing)} have no cached manifest under "
f"{install_dir}/{recognize.DEPOTDOWNLOADER_DIR} -- "
"the download did not finish"
)
expected_manifests = expected_manifests or {}
stale = sorted(
depot
for depot in required_depots & set(cached) & set(expected_manifests)
if cached[depot] != expected_manifests[depot]
)
if stale:
problems.append(
f"depot(s) {', '.join(stale)} hold a manifest other than the public "
"gid in Steam's local app cache -- stale content. depotdownloader "
"always fetches the current build, so the cache is the stale side: "
"start Steam once, let it sync, rerun"
)
if build_proven(cached, required_depots, expected_manifests):
# The manifest's buildid only ever stood in for this proof. A stub
# (StateFlags 1026, buildid 0) that Steam never got to fill in is no
# reason to refuse content that matches the current build depot by depot.
if expected_build_id is None:
problems.append(
"could not determine the current public build from app info, "
"so there is no buildid to record"
)
return problems + _content_and_steam_problems(install_dir)
buildid = app_state.get("buildid")
target = app_state.get("TargetBuildID")
if not (buildid and buildid != "0") and not (target and target != "0"):
problems.append(
"manifest has no usable buildid (both buildid and TargetBuildID are 0) "
"-- no real build was ever recorded"
)
resolved = buildid if buildid and buildid != "0" else target
if expected_build_id is None:
# Don't silently skip the comparison: a None here means app_info had no
# branches.public, so we cannot tell a current build from a stale one.
problems.append(
"could not determine the current public build from app info, so the "
"manifest's buildid cannot be checked"
)
elif resolved and resolved != expected_build_id:
problems.append(
f"manifest buildid {resolved} != current public build "
f"{expected_build_id} -- content is for a different build"
)
return problems + _content_and_steam_problems(install_dir)
def build_proven(
cached: dict[str, str], required_depots: set[str], expected: dict[str, str]
) -> bool:
"""Whether every required depot holds the manifest the public branch ships."""
return bool(required_depots) and all(
depot in expected and cached.get(depot) == expected[depot]
for depot in required_depots
)
def _content_and_steam_problems(install_dir: Path) -> list[str]:
"""The checks that hold however the build was established."""
problems: list[str] = []
# Cache *filenames* are not content. Without this, an install dir holding
# only `.DepotDownloader/<id>_<id>.manifest` and no game files passes every
# other check and gets written as StateFlags=4 with SizeOnDisk=0.
if not manifest_write.measure_content_size(install_dir):
problems.append(
f"no game content found under {install_dir} (only depotdownloader "
"cache files) -- nothing was actually installed"
)
pids = recognize.steam_client_pids()
if pids:
problems.append(
f"the Steam client is running (pid {', '.join(str(p) for p in pids)}) "
"and will overwrite the manifest -- close Steam and re-run"
)
return problems

View File

@ -1,171 +0,0 @@
"""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
import logging
from typing import TYPE_CHECKING
from steam_installer import (
appinfo,
compat_apply,
depotdl,
dlc,
manifest_write,
recognize,
runlog,
steamctl,
takeover,
)
from steam_installer.finalize import finish
if TYPE_CHECKING:
import argparse
from pathlib import Path
from steam_installer.job import Job
def prepare_steam(args: argparse.Namespace, logger: logging.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.SteamStillRunningError as exc:
logger.log(logging.ERROR, "%s", exc)
return None
def install(
*,
args: argparse.Namespace,
log: runlog.RunLog,
steam_root: Path,
job: Job,
) -> int:
"""Adopt anything Steam already fetched, download the rest, make it count."""
logger = log.logger
metadata = job.metadata
steam_was_running = prepare_steam(args, logger)
if steam_was_running is None:
return 1
try:
returncode = _download_and_recognize(args, log, job)
if returncode == 0:
# Still inside the window where Steam is closed: config.vdf written
# under a running client is lost when it exits.
cached = recognize.discover_cached_depot_manifests(job.install_target)
dlc_depots = appinfo.get_depot_plan(metadata.appid, job.language).dlc
compat_apply.after_install(
steam_root,
metadata.appid,
owned_dlc=bool(set(dlc_depots) & set(cached)),
valve_proton=args.valve_proton,
logger=logger,
)
return returncode
finally:
if steam_was_running:
steamctl.start(logger)
def _adopt_staged(log: runlog.RunLog, job: Job) -> None:
"""Hardlink whatever Steam already staged into the install dir."""
staged = job.staged
if staged is None:
return
logger = log.logger
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,
)
job.install_target.mkdir(parents=True, exist_ok=True)
takeover.adopt(staged, logger)
def _log_plan(
log: runlog.RunLog, job: Job, depot_plan: appinfo.DepotPlan, max_downloads: int
) -> None:
"""Record what this run is about to fetch, for the run log."""
logger = log.logger
log.section("Plan")
logger.debug("language=%s max_downloads=%s", job.language, 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", appinfo.get_build_id(job.metadata.appid))
manifest_path = job.library.steamapps / f"appmanifest_{job.metadata.appid}.acf"
log.file_contents("Manifest before run", manifest_path)
def _download_and_recognize(
args: argparse.Namespace, log: runlog.RunLog, job: Job
) -> int:
logger = log.logger
metadata, install_target = job.metadata, job.install_target
# First thing with Steam closed: whatever happens next, Steam resumes onto
# this field, and a stub written from the display name ("Baldur's Gate 3")
# would point it at a folder the download never fills.
manifest_write.ensure_installdir_correct(
job.library, metadata.appid, install_target
)
_adopt_staged(log, job)
depot_plan = appinfo.get_depot_plan(metadata.appid, job.language)
_log_plan(log, job, depot_plan, args.max_downloads)
logger.info("Downloading via depotdownloader (fast path)...")
log.section("depotdownloader")
pull = depotdl.Pull(
install_dir=install_target,
username=job.username,
language=job.language,
max_downloads=args.max_downloads,
)
returncode = depotdl.download(metadata.appid, pull, 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
logger.info("Checking for owned DLC with depots of its own...")
dlc_plan = dlc.download_owned(metadata.appid, pull, log)
if dlc_plan is None:
logger.info("Run log (send this): %s", log.path)
return 1
# Downloaded DLC is part of this install now: the finish gate must find its
# depot cached at its public gid, and the manifest must credit it to its
# DLC app.
depot_plan.required |= dlc_plan.required
depot_plan.dlc.update(dlc_plan.dlc)
depot_plan.manifests.update(dlc_plan.manifests)
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)
return finish(log, job.library, metadata, install_target, depot_plan)

View File

@ -1,207 +0,0 @@
"""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
from dataclasses import dataclass
import time
from typing import TYPE_CHECKING, Any
from steam_installer import manifest_write, recognize, vdf
if TYPE_CHECKING:
import logging
from pathlib import Path
from steam_installer.library import SteamLibrary
INSTALLED_STATE_FLAG = 4
@dataclass(frozen=True)
class GhostReport:
"""What the scan found about one app's manifest."""
appid: int
manifest_path: Path
install_dir: Path | None
content_bytes: int
staging_bytes: int
reasons: tuple[str, ...]
@property
def is_ghost(self) -> bool:
"""Whether the manifest claims an install with nothing behind it."""
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:
"""Bytes of staged content for *appid* in *library*."""
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[str, Any]) -> Path | None:
installdir = app_state.get("installdir")
if not isinstance(installdir, str) or not installdir:
return None
return library.common / installdir
def _load_state(manifest_path: Path, appid: int) -> dict[str, Any] | None:
"""The manifest's AppState, or None when it is absent, unparsable or foreign."""
if not manifest_path.is_file():
return None
try:
app_state = recognize.read_app_state(manifest_path)
except vdf.VdfParseError:
return None
if str(app_state.get("appid", "")) != str(appid):
return None
return app_state
def _looks_installed_but_empty(
app_state: dict[str, Any], content_bytes: int, install_dir: Path | None
) -> bool:
"""Every ghost condition at once; one failing condition rules a ghost out."""
state_flags = app_state.get("StateFlags", "")
if not (str(state_flags).isdigit() and int(state_flags) & INSTALLED_STATE_FLAG):
return False
if app_state.get("InstalledDepots"):
return False
if str(app_state.get("SizeOnDisk", "0")) != "0" or content_bytes:
return False
# 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.
return not (
install_dir is not None
and recognize.discover_cached_depot_manifests(install_dir)
)
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"
app_state = _load_state(manifest_path, appid)
if app_state is None:
return GhostReport(appid, manifest_path, None, 0, 0, ())
install_dir = _install_dir(library, app_state)
content_bytes = (
manifest_write.measure_content_size(install_dir)
if install_dir is not None and install_dir.is_dir()
else 0
)
staged = staging_size(library, appid)
if not _looks_installed_but_empty(app_state, content_bytes, install_dir):
return GhostReport(appid, manifest_path, install_dir, content_bytes, staged, ())
return GhostReport(
appid,
manifest_path,
install_dir,
content_bytes,
staged,
(
f"manifest claims StateFlags={app_state.get('StateFlags')} (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:
msg = f"appid {report.appid} is not a ghost; refusing to touch it"
raise ValueError(msg)
if report.is_warm:
msg = (
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."
)
raise ValueError(msg)
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,185 +0,0 @@
#!/bin/bash
# ============================================================================
# Install everything the Steam game installer shells out to.
#
# libibus the one runtime library of proton-cachyos-native's 63
# package dependencies a plain Arch desktop may lack (pacman)
# depotdownloader official self-contained release from SteamRE/DepotDownloader
# kuhy-credit the installer's one third-party import (user site, pinned in
# requirements.txt)
# native Proton proton-cachyos-native, pinned in
# steam_installer/data/proton-native.lock, signature- and
# sha256-checked, into Steam's compatibilitytools.d
#
# steamcmd is not needed any more: app info comes from Steam's own cache and
# the manifest is written by the tool itself.
#
# Idempotent: every step no-ops when its target is already in place, so
# steam_installer/run.sh can call it on every run. Installing libibus runs `sudo -n pacman`; when sudo
# would prompt, it stops and prints the one command to type.
# ============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly REPO_DIR="${SCRIPT_DIR%/*}"
readonly PYTHON="${SGI_PYTHON:-/usr/bin/python3}"
readonly STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/steam-game-installer"
readonly STAMP="${STATE_DIR}/.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"
CHECK_ONLY=0
TEMP_DIR=""
cleanup() {
if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then
rm -rf -- "$TEMP_DIR"
fi
}
trap cleanup EXIT
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_libibus() {
if pacman -Q libibus >/dev/null 2>&1; then
return 0
fi
if [[ "$CHECK_ONLY" -eq 1 ]]; then
echo "missing: libibus -- run: sudo pacman -S --needed libibus" >&2
return 1
fi
sudo -n true 2>/dev/null ||
die "libibus is missing and sudo needs a password. Run: sudo pacman -S --needed libibus"
# No -y: syncing the db without upgrading is a partial upgrade on Arch.
sudo -n pacman -S --needed --noconfirm libibus ||
die "pacman could not install libibus (a stale package db 404s). Run: sudo pacman -Syu libibus"
}
# The installer's one third-party import. The daemon launches it with the
# system interpreter as the desktop user, so it must live in that user's site.
ensure_kuhy_credit() {
if "$PYTHON" -c 'import kuhy_credit' >/dev/null 2>&1; then
return 0
fi
if [[ "$CHECK_ONLY" -eq 1 ]]; then
echo "missing: kuhy-credit -- run steam_installer/install_deps.sh" >&2
return 1
fi
local pin
pin="$(grep -m1 '^kuhy-credit' "${REPO_DIR}/requirements.txt")" ||
die "no kuhy-credit pin in ${REPO_DIR}/requirements.txt"
"$PYTHON" -m pip install --user --break-system-packages "$pin" ||
die "could not install kuhy-credit"
}
# Never runs the package's .INSTALL; see steam_installer/proton_native.py.
ensure_native_proton() {
export PYTHONPATH="${REPO_DIR}${PYTHONPATH:+:$PYTHONPATH}"
if [[ "$CHECK_ONLY" -eq 1 ]]; then
if ! "$PYTHON" -m steam_installer.proton_native --check; then
echo "missing: proton-cachyos-native at the pinned version -- run steam_installer/install_deps.sh" >&2
return 1
fi
return 0
fi
"$PYTHON" -m steam_installer.proton_native || die "native Proton install failed"
}
# 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 steam_installer/install_deps.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."
}
main() {
local missing=0
ensure_libibus || missing=1
ensure_depotdownloader || missing=1
ensure_kuhy_credit || missing=1
if [[ "$CHECK_ONLY" -eq 1 ]]; then
ensure_native_proton || missing=1
[[ "$missing" -eq 0 ]] && echo "All dependencies present."
exit "$missing"
fi
ensure_kuhy_credit
ensure_native_proton
echo "All dependencies present."
mkdir -p "$STATE_DIR"
: >"$STAMP"
}
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
main

View File

@ -1,24 +0,0 @@
"""Everything one install run is about, bundled so it travels as one argument."""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pathlib import Path
from steam_installer import appinfo, takeover
from steam_installer.library import SteamLibrary
@dataclass(frozen=True)
class Job:
"""The app, where it goes, what Steam already staged, and as whom."""
library: SteamLibrary
metadata: appinfo.AppMetadata
install_target: Path
staged: takeover.Staged | None
username: str
language: str

View File

@ -1,79 +0,0 @@
"""Steam library discovery: find install roots and where a given app lives."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from steam_installer import vdf
DEFAULT_STEAM_ROOT = Path.home() / ".local/share/Steam"
@dataclass
class SteamLibrary:
"""One Steam library folder."""
path: Path
@property
def common(self) -> Path:
"""Folder holding installed games."""
return self.path / "steamapps" / "common"
@property
def steamapps(self) -> Path:
"""The library's ``steamapps`` folder."""
return self.path / "steamapps"
def find_steam_root() -> Path:
"""Locate the Steam installation. Raises if none of the usual paths exist."""
for candidate in (DEFAULT_STEAM_ROOT, Path.home() / ".steam/steam"):
if (candidate / "steamapps").is_dir():
return candidate
msg = "No Steam installation found at ~/.local/share/Steam or ~/.steam/steam"
raise FileNotFoundError(msg)
def list_libraries(steam_root: Path) -> list[SteamLibrary]:
"""Every Steam library folder in libraryfolders.vdf, plus steam_root itself."""
libraries = [SteamLibrary(steam_root)]
vdf_path = steam_root / "steamapps" / "libraryfolders.vdf"
if not vdf_path.is_file():
return libraries
data = vdf.parse(vdf_path.read_text())
folders = data.get("libraryfolders", {})
if not isinstance(folders, dict):
return libraries
seen = {steam_root.resolve()}
for entry in folders.values():
if not isinstance(entry, dict):
continue
raw_path = entry.get("path")
if not raw_path:
continue
path = Path(raw_path).resolve()
if path not in seen:
seen.add(path)
libraries.append(SteamLibrary(path))
return libraries
def find_existing_install(
libraries: list[SteamLibrary], installdir: str
) -> Path | None:
"""Return the install path if `installdir` already exists in any library."""
for library in libraries:
candidate = library.common / installdir
if candidate.is_dir():
return candidate
return None
def pick_install_target(libraries: list[SteamLibrary], installdir: str) -> Path:
"""Where to install: an existing partial install, else the primary library."""
existing = find_existing_install(libraries, installdir)
if existing is not None:
return existing
return libraries[0].common / installdir

View File

@ -1,58 +0,0 @@
"""What a manifest finish records about depots and builds, apart from file I/O.
Split out of manifest_write.py (250-line cap).
"""
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Proven:
"""The extras a finish may add beyond what the manifest on disk already says.
``dlc_depots`` maps a DLC depot to its DLC app id. Steam's own manifests
record each DLC depot with that ``dlcappid``, so it is written the same way.
``build_id``, when given, is a build the caller proved from the cached depot
manifests; it replaces the one Steam recorded. ``seed`` (from
:func:`seed_app_state`) is written instead when there is no manifest.
"""
dlc_depots: dict[str, str] = field(default_factory=dict)
build_id: str | None = None
seed: dict | None = None
def pick_buildid(app_state: dict, proven_build: str | None) -> str:
"""The build to record: the proven one, else Steam's, else "0".
"0" means "no real build installed yet" (Steam uses it as a sentinel) -- a
bare `or` treats that non-empty string as truthy and never falls through to
TargetBuildID, leaving a stale/wrong buildid.
"""
existing = app_state.get("buildid")
recorded = existing if existing and existing != "0" else None
return proven_build or recorded or app_state.get("TargetBuildID") or "0"
def installed_depots(
app_state: dict, depot_manifests: dict[str, str], dlc_depots: dict[str, str]
) -> dict:
"""InstalledDepots for the cached depots, minus the shared ones.
A shared depot (e.g. Steamworks Common Redistributables) is installed once
under its owning app and only referenced here. Listing it in
InstalledDepots as though this app owned a copy contradicts SharedDepots.
"""
shared = app_state.get("SharedDepots")
shared_ids = set(shared) if isinstance(shared, dict) else set()
installed: dict = {}
for depot_id, manifest_id in depot_manifests.items():
if depot_id in shared_ids:
continue
entry = {"manifest": manifest_id, "size": "0"}
if depot_id in dlc_depots:
entry["dlcappid"] = dlc_depots[depot_id]
installed[depot_id] = entry
return installed

View File

@ -1,203 +0,0 @@
"""Every write this tool makes to an appmanifest, and only from verified values.
Split out of recognize.py (250-line cap). The manifest is finished by hand
using ONLY values already verified: the exact manifest IDs from
depotdownloader's own local cache (never guessed), the build those prove, and
the real on-disk size measured directly. When no manifest exists it is
written from scratch with the 15 keys Steam accepted on 2026-11-22.
Do NOT leave the download bookkeeping for Steam to tidy up on its next launch.
An earlier version did, on the belief that Steam self-corrects; it does not. A
manifest that says StateFlags=4 while `BytesDownloaded` still differs from
`BytesToDownload` is self-contradictory, and Steam resolves the contradiction
by discarding the "installed" claim and resuming the download -- 90 GB of it,
in the run that prompted this comment.
"""
from __future__ import annotations
import os
from typing import TYPE_CHECKING
from steam_installer import recognize, vdf
from steam_installer.manifest_depots import Proven, installed_depots, pick_buildid
if TYPE_CHECKING:
from pathlib import Path
from steam_installer.library import SteamLibrary
def ensure_installdir_correct(
library: SteamLibrary, appid: int, install_dir: Path
) -> None:
"""Patch a stale `installdir` field before anything else, not just after.
Confirmed necessary: a prior, unrelated Steam GUI glitch left this app's
manifest pointing at a different folder name, and relaunching the Steam
client read that stale field and wiped the correctly-downloaded folder as
"orphaned" while starting a fresh download into the wrong one. Fixing it
first, as soon as Steam is closed, closes that window entirely. Does
nothing if no manifest exists yet: the one written from scratch takes
installdir from the real install folder.
"""
manifest_path = library.steamapps / f"appmanifest_{appid}.acf"
if not manifest_path.is_file():
return
data = vdf.parse(manifest_path.read_text())
app_state = data.get("AppState", {})
if not isinstance(app_state, dict):
return
if app_state.get("installdir") == install_dir.name:
return
app_state["installdir"] = install_dir.name
backup_once(manifest_path)
write_atomic(manifest_path, vdf.dumps("AppState", app_state))
def measure_content_size(install_dir: Path) -> int:
"""Bytes of real game content, excluding depotdownloader's own cache/staging.
`.DepotDownloader/` holds manifests and a staging tree that Steam knows
nothing about; counting them overstates SizeOnDisk by gigabytes.
"""
total = 0
for entry in install_dir.rglob("*"):
if recognize.DEPOTDOWNLOADER_DIR in entry.parts:
continue
if entry.is_file() and not entry.is_symlink():
total += entry.stat().st_size
return total
def seed_app_state(
appid: int, name: str, installdir: str, shared_owner: dict[str, str]
) -> dict:
"""The skeleton of a from-scratch manifest, in the key order Steam writes.
These 15 keys are the proven minimum: Steam logged "Fully Installed,App
Running", queued no download and added LastOwner, UserConfig and the rest
itself. Placeholders here are overwritten by `finish_manifest_manually`.
SharedDepots is only added for a game that has some (fixture-tested only).
"""
state: dict = {
"appid": str(appid),
"universe": "1",
"name": name,
"StateFlags": "4",
"installdir": installdir,
"LastUpdated": "0",
"SizeOnDisk": "0",
"StagingSize": "0",
"buildid": "0",
"UpdateResult": "0",
# All four at 0: counters that disagree made Steam download a game again.
"BytesToDownload": "0",
"BytesDownloaded": "0",
"BytesToStage": "0",
"BytesStaged": "0",
"InstalledDepots": {},
}
if shared_owner:
state["SharedDepots"] = dict(shared_owner)
return state
def finish_manifest_manually(
library: SteamLibrary,
appid: int,
install_dir: Path,
now_unix: int,
proven: Proven | None = None,
) -> Path:
"""Patch appmanifest_<appid>.acf to StateFlags=4 using only verified-known values.
Patches the manifest on disk, or -- when there is none -- writes
``proven.seed`` instead. With neither it refuses.
"""
proven = proven or Proven()
manifest_path = library.steamapps / f"appmanifest_{appid}.acf"
existed = manifest_path.is_file()
if not existed and proven.seed is None:
msg = f"No existing {manifest_path.name} to finish and no seed to write"
raise recognize.RecognizeError(msg)
app_state = (
vdf.parse(manifest_path.read_text()).get("AppState", {})
if existed
else proven.seed
)
if not isinstance(app_state, dict):
msg = f"{manifest_path} is not a valid AppState manifest"
raise recognize.RecognizeError(msg)
depot_manifests = recognize.discover_cached_depot_manifests(install_dir)
if not depot_manifests:
msg = (
"No cached depot manifests found under "
f"{install_dir}/{recognize.DEPOTDOWNLOADER_DIR}"
)
raise recognize.RecognizeError(msg)
depots = installed_depots(app_state, depot_manifests, proven.dlc_depots)
if not depots:
msg = f"Every cached depot for {appid} is a shared depot -- nothing to install"
raise recognize.RecognizeError(msg)
app_state["StateFlags"] = "4"
app_state["installdir"] = install_dir.name
app_state["LastUpdated"] = str(now_unix)
app_state["SizeOnDisk"] = str(measure_content_size(install_dir))
app_state["StagingSize"] = "0"
app_state["buildid"] = pick_buildid(app_state, proven.build_id)
app_state["UpdateResult"] = "0"
app_state["InstalledDepots"] = depots
app_state.pop("StagedDepots", None)
# Steam's own per-DLC progress for a download it started: left in place it
# contradicts the settled counters and Steam resumes fetching the DLC.
app_state.pop("DlcDownloads", None)
settle_download_counters(app_state)
if existed:
backup_once(manifest_path)
write_atomic(manifest_path, vdf.dumps("AppState", app_state))
return manifest_path
def backup_once(manifest_path: Path) -> None:
"""Keep the *pristine* manifest, not the previous run's output.
An unconditional backup means a second run overwrites the original with
run 1's already-patched file, so the recovery artifact for a 90+ GB install
is one re-run away from being useless. Only write it if absent.
"""
backup_path = manifest_path.with_suffix(".acf.bak")
if not backup_path.exists():
backup_path.write_text(manifest_path.read_text())
def write_atomic(path: Path, text: str) -> None:
"""Write via a temp file + rename so a crash can't truncate the manifest.
A partial write leaves an unparsable manifest, which Steam and this tool
both then choke on. `Path.replace` is atomic within a filesystem, and the
temp file is created alongside the target to stay on the same one.
"""
tmp = path.with_name(f"{path.name}.tmp{os.getpid()}")
try:
tmp.write_text(text)
tmp.replace(path)
except BaseException:
tmp.unlink(missing_ok=True)
raise
def settle_download_counters(app_state: dict) -> None:
"""Zero the download bookkeeping: nothing is queued, nothing is staged.
Leaving these at their mid-download values is what made Steam discard a
StateFlags=4 manifest and resume fetching. All four go to "0", the same as
the from-scratch skeleton Steam accepted, rather than merely equal: the
older equal-pair form wrote `1000`/`1000` from a broken manifest, a value
no real install ever had.
"""
for key in ("BytesToDownload", "BytesDownloaded", "BytesToStage", "BytesStaged"):
app_state[key] = "0"

View File

@ -1,101 +0,0 @@
"""`--map-installed`: run the compat decision over every installed game.
steam_installer/run.sh --map-installed # dry run: write nothing
steam_installer/run.sh --map-installed --apply # close Steam, map the safe ones
steam_installer/run.sh --map-installed --appids 730,10 # any cached app, read-only
The dry run only reads, so it works with Steam open. `--apply` closes Steam
first (it rewrites config.vdf on exit) and restarts it afterwards.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from steam_installer import (
compat_apply,
compat_map,
compat_rows,
flow,
runlog,
steamctl,
)
if TYPE_CHECKING:
import argparse
from pathlib import Path
def add_arguments(parser: argparse.ArgumentParser) -> None:
"""Register the ``--map-installed`` options on *parser*."""
parser.add_argument(
"--valve-proton",
action="store_true",
help="Keep this game on Valve's default Proton for this run.",
)
parser.add_argument(
"--map-installed",
action="store_true",
help="Decide every installed game's compat tool. Dry run unless --apply.",
)
parser.add_argument(
"--apply", action="store_true", help="With --map-installed: write the mappings."
)
parser.add_argument(
"--appids",
default=None,
help="With --map-installed: comma-separated app ids to decide instead.",
)
def check_arguments(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""Reject option combinations that make no sense."""
if args.map_installed and args.valve_proton:
parser.error("--valve-proton goes with an install, not --map-installed")
def _line(row: compat_rows.Row) -> str:
"""The log line for one decided row (the dry run's report)."""
verdict = "map" if row.map else f"Valve default: {', '.join(row.reasons)}"
line = f"{row.appid} {row.name}: {verdict}"
already = row.map and row.current == compat_map.TOOL
return line + " -- already mapped" if already else line
def run(args: argparse.Namespace, log: runlog.RunLog, steam_root: Path) -> int:
"""Decide, and with ``--apply`` write, mappings for installed games."""
logger = log.logger
appids = None
if args.appids:
appids = [int(x) for x in args.appids.split(",") if x.strip().isdigit()]
context = compat_apply.Context(steam_root)
decided = compat_rows.rows(steam_root, appids, context)
for row in decided:
if row.cached:
logger.info("%s", _line(row))
else:
logger.info("%s: not in Steam's app cache -- skipped", row.appid)
if not args.apply:
logger.info("Dry run: nothing written. Rerun with --apply to write.")
return 0
to_map = [row.appid for row in decided if row.map]
return _apply(args, logger, context.config, to_map)
def _apply(
args: argparse.Namespace, logger: logging.Logger, config: Path, to_map: list[int]
) -> int:
was_running = flow.prepare_steam(args, logger)
if was_running is None:
return 1
try:
for appid in to_map:
compat_apply.report(logger, appid, compat_map.map_app(config, appid))
except compat_map.CompatMapError as exc:
logger.log(logging.ERROR, "Mapping stopped: %s", exc)
return 1
finally:
if was_running:
steamctl.start(logger)
return 0

View File

@ -1,186 +0,0 @@
"""Install the pinned proton-cachyos-native build into Steam's compatibilitytools.d.
python -m steam_installer.proton_native # what install_deps.sh runs
python -m steam_installer.proton_native --check # exit 0 when in place
The package comes straight from the CachyOS mirror: the `proton-cachyos-native`
entry of `cachyos.db`, its signature and sha256 checked (see :mod:`proton_pkg`),
and only `usr/share/steam/compatibilitytools.d/proton-cachyos-native/` taken
out of it. Its `.INSTALL` is never run. It is a WoW64 build that needs no
lib32 packages, and unlike the `-slr` variant its toolmanifest requires no
Steam Linux Runtime -- which is the point.
A `VERSION` stamp equal to the lock means there is nothing to do and no
network is touched. Otherwise the new build is extracted next to the old one
and swapped in by rename -- never while Steam or a game from the tool runs,
since a game would lose its files mid-run. A copy already on disk with no
stamp is adopted as is when every file matches the package's `.MTREE`.
`SGI_PROTON_REPO` points the fetch at another copy of the repo db (a local
test mirror); the pinned key and sha256 still decide what is accepted.
"""
from __future__ import annotations
import dataclasses
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import urllib.request
from steam_installer import proton_pkg, recognize
from steam_installer.library import find_steam_root
from steam_installer.proton_pkg import FINGERPRINT, KEY, Lock, PkgError
TOOL_NAME = "proton-cachyos-native"
# On PATH, as ever (see steamctl.STEAM on why a name and not a literal).
GPGCONF = "gpgconf"
# A generic agent: the mirror answers 403 to urllib's default one.
USER_AGENT = "steam-game-installer"
def in_use(tool: Path) -> list[int]:
"""Steam client pids plus every process running from the tool folder."""
pids = list(recognize.steam_client_pids())
root = tool.resolve()
for entry in recognize.PROC_DIR.iterdir():
if not entry.name.isdigit():
continue
try:
exe = (entry / "exe").resolve(strict=True)
except OSError:
continue
if exe.is_relative_to(root):
pids.append(int(entry.name))
return pids
def _download(url: str, dest: Path) -> None:
# A generic agent: the mirror answers 403 to urllib's default one.
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with (
urllib.request.urlopen(request, timeout=60) as response,
dest.open("wb") as out,
):
shutil.copyfileobj(response, out, 1 << 20)
def _fetch_verified(lock: Lock, work: Path, key: Path, fingerprint: str) -> Path:
"""Download the pinned package and prove it, or raise PkgError."""
db = work / "repo.db"
_download(lock.repo, db)
entry = proton_pkg.find_in_db(db, lock.name)
if entry.version != lock.version:
msg = (
f"the repo serves {lock.name} {entry.version} but the lock pins "
f"{lock.version}: bump steam_installer/data/proton-native.lock "
"(version and sha256)"
)
raise PkgError(msg)
if entry.sha256 != lock.sha256:
msg = "the repo's sha256 for the pinned version differs from the lock"
raise PkgError(msg)
package = work / entry.filename
url = proton_pkg.package_url(lock, entry.filename)
_download(url, package)
sig = work / f"{entry.filename}.sig"
_download(f"{url}.sig", sig)
home = work / "gnupg"
home.mkdir(mode=0o700)
try:
proton_pkg.verify_signature(package, sig, key, fingerprint, home)
finally:
subprocess.run(
[GPGCONF, "--homedir", str(home), "--kill", "all"],
check=False,
capture_output=True,
)
if proton_pkg.sha256_file(package) != lock.sha256:
msg = "the downloaded package's sha256 differs from the pinned sha256"
raise PkgError(msg)
return package
def _stamp(tool: Path, version: str) -> None:
(tool / "VERSION").write_text(version + "\n")
def _swap(package: Path, tools_dir: Path, tool: Path, version: str) -> None:
new = tools_dir / f".{TOOL_NAME}.new"
old = tools_dir / f".{TOOL_NAME}.old"
for leftover in (new, old):
shutil.rmtree(leftover, ignore_errors=True)
new.mkdir()
proton_pkg.extract(package, new)
if tool.exists():
tool.rename(old)
new.rename(tool)
shutil.rmtree(old, ignore_errors=True)
_stamp(tool, version)
def ensure(
tools_dir: Path, lock: Lock, *, key: Path = KEY, fingerprint: str = FINGERPRINT
) -> str:
"""Make `tools_dir/proton-cachyos-native` the pinned build; return what happened."""
tool = tools_dir / TOOL_NAME
stamp = tool / "VERSION"
current = stamp.read_text().strip() if stamp.is_file() else None
if current == lock.version:
return f"current: {lock.version}"
tools_dir.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(dir=tools_dir, prefix=".proton-download."))
try:
package = _fetch_verified(lock, work, key, fingerprint)
checks = f"signature by {fingerprint} and sha256 both passed"
if not tool.exists():
verb = f"installed: {lock.version}"
elif current is not None:
verb = f"updated: {current} -> {lock.version}"
else:
entries = proton_pkg.read_mtree(package)
mismatch = proton_pkg.first_mismatch(tool, entries)
if mismatch is None:
_stamp(tool, lock.version)
count = sum(entry.kind != "dir" for entry in entries.values())
return f"adopted: all {count} files match .MTREE ({checks})"
verb = f"replaced: mismatch in {mismatch}"
busy = in_use(tool) if tool.exists() else []
if busy:
return (
"deferred: Steam or a game is running "
f"(pid {', '.join(map(str, busy))}); rerun with Steam closed"
)
_swap(package, tools_dir, tool, lock.version)
return f"{verb} ({checks})"
finally:
shutil.rmtree(work, ignore_errors=True)
def main(argv: list[str] | None = None) -> int:
"""Install the pinned build; with `--check`, only say whether it is in place."""
lock = proton_pkg.read_lock()
if os.environ.get("SGI_PROTON_REPO"):
lock = dataclasses.replace(lock, repo=os.environ["SGI_PROTON_REPO"])
try:
tools_dir = find_steam_root() / "compatibilitytools.d"
except FileNotFoundError:
sys.stdout.write("native Proton skipped: no Steam installation\n")
return 0
if argv and argv[0] == "--check":
stamp = tools_dir / TOOL_NAME / "VERSION"
return 0 if stamp.is_file() and stamp.read_text().strip() == lock.version else 1
try:
status = ensure(tools_dir, lock)
except (PkgError, OSError) as exc:
sys.stderr.write(f"error: native Proton: {exc}\n")
return 1
sys.stdout.write(f"native Proton {status}\n")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))

View File

@ -1,235 +0,0 @@
"""The CachyOS package formats and the two checks every download must pass.
The repo database is not signed, so nothing in it is trusted on its own:
- the package's detached `.sig` must verify against the CachyOS key pinned in
`data/cachyos_signing_key.asc`, by primary-key fingerprint, in a throwaway
gpg home that holds that key and nothing else;
- the package's sha256 must equal both the db entry and the pinned lock.
Either failing stops the install before anything is extracted.
Pinned key: 882DCFE48E2051D48E2562ABF3B607488DB35A47 ("CachyOS
<admin@cachyos.org>"). The .sig names its own issuer, so it could not vouch
for the pin. Taken on 2026-11-22 from two other sources instead:
https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x882DCFE48E2051D48E2562ABF3B607488DB35A47
(the key file) and the long id F3B607488DB35A47 that CachyOS's own installer
imports:
https://github.com/CachyOS/cachyos-repo-add-script/blob/5b27dc1eff276e104077cfaf75798b4c290eaef4/cachyos-repo.sh#L156
"""
from __future__ import annotations
from dataclasses import dataclass
import gzip
import hashlib
from pathlib import Path
import re
import subprocess
import tarfile
from urllib.parse import quote
from steam_installer import errors
# On PATH, as ever (see steamctl.STEAM on why a name and not a literal).
GPG = "gpg"
DATA = Path(__file__).parent / "data"
LOCK = DATA / "proton-native.lock"
KEY = DATA / "cachyos_signing_key.asc"
FINGERPRINT = "882DCFE48E2051D48E2562ABF3B607488DB35A47"
PREFIX = "usr/share/steam/compatibilitytools.d/proton-cachyos-native/"
class PkgError(errors.InstallerError):
"""A package failed a check and must not be installed."""
@dataclass(frozen=True)
class Lock:
"""The pinned package: name, version and checksum."""
name: str
repo: str # URL of the <repo>.db
version: str
sha256: str
@dataclass(frozen=True)
class DbEntry:
"""One package's entry in the repo database."""
filename: str
version: str
sha256: str
@dataclass(frozen=True)
class MtreeEntry:
"""One file's entry in a package's ``.MTREE``."""
kind: str # "file", "link" or "dir"
sha256: str = ""
link: str = ""
def read_lock(path: Path = LOCK) -> Lock:
"""Read the pinned package lock at *path*."""
fields = {}
for line in path.read_text().splitlines():
if line.strip() and not line.lstrip().startswith("#"):
key, _, value = line.partition("=")
fields[key.strip()] = value.strip()
try:
return Lock(fields["name"], fields["repo"], fields["version"], fields["sha256"])
except KeyError as exc:
msg = f"{path.name} has no {exc.args[0]}="
raise PkgError(msg) from exc
def package_url(lock: Lock, filename: str) -> str:
"""The package sits next to the db; the epoch colon must be escaped."""
return f"{lock.repo.rsplit('/', 1)[0]}/{quote(filename)}"
def find_in_db(db: Path, name: str) -> DbEntry:
"""The db entry whose %NAME% is exactly `name` (not `<name>-v3`)."""
with tarfile.open(db, "r:*") as tar:
for member in tar:
if not member.name.endswith("/desc"):
continue
fields = _desc(tar.extractfile(member).read().decode())
if fields.get("NAME") == name:
return DbEntry(
fields["FILENAME"], fields["VERSION"], fields["SHA256SUM"]
)
msg = f"the repo database lists no {name}"
raise PkgError(msg)
def _desc(text: str) -> dict[str, str]:
fields: dict[str, str] = {}
for block in text.strip().split("\n\n"):
head, _, value = block.partition("\n")
fields[head.strip("%")] = value.strip()
return fields
def sha256_file(path: Path) -> str:
"""Hex sha256 of the file at *path*."""
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def _gpg(home: Path, *args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[GPG, "--homedir", str(home), "--batch", "--no-tty", *args],
capture_output=True,
text=True,
check=False,
timeout=60,
)
def key_fingerprints(key: Path, home: Path) -> list[str]:
"""Primary-key fingerprints in `key`, imported into the empty `home`."""
_gpg(home, "--import", str(key))
listing = _gpg(home, "--with-colons", "--fingerprint").stdout.splitlines()
out, after_pub = [], False
for line in listing:
if line.startswith("pub"):
after_pub = True
elif line.startswith("fpr") and after_pub:
out.append(line.split(":")[9])
after_pub = False
return out
def verify_signature(
package: Path, sig: Path, key: Path, fingerprint: str, home: Path
) -> None:
"""Fail unless `sig` is a good signature by the pinned primary key."""
if fingerprint not in key_fingerprints(key, home):
msg = "the pinned key file does not hold the pinned fingerprint"
raise PkgError(msg)
result = _gpg(home, "--status-fd", "1", "--verify", str(sig), str(package))
signers = [
line.split()[-1]
for line in result.stdout.splitlines()
if line.startswith("[GNUPG:] VALIDSIG ")
]
if result.returncode != 0 or signers != [fingerprint]:
msg = f"package signature does not verify against {fingerprint}"
raise PkgError(msg)
def _unescape(path: str) -> str:
return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), path)
def read_mtree(package: Path) -> dict[str, MtreeEntry]:
"""The package's own file list for the tool folder, relative to it."""
with tarfile.open(package, "r:zst") as tar:
for member in tar:
if member.name == ".MTREE":
text = gzip.decompress(tar.extractfile(member).read()).decode()
break
else:
msg = "package has no .MTREE"
raise PkgError(msg)
entries: dict[str, MtreeEntry] = {}
defaults: dict[str, str] = {}
for line in text.splitlines():
if not line or line.startswith("#"):
continue
path, *pairs = line.split(" ")
values = dict(pair.partition("=")[::2] for pair in pairs)
if path == "/set":
defaults.update(values)
continue
path = _unescape(path.removeprefix("./"))
if not path.startswith(PREFIX) or path == PREFIX:
continue
values = {**defaults, **values}
entries[path[len(PREFIX) :]] = MtreeEntry(
values.get("type", "file"),
values.get("sha256digest", ""),
values.get("link", ""),
)
return entries
def first_mismatch(folder: Path, entries: dict[str, MtreeEntry]) -> str | None:
"""The first path where `folder` differs from the package, or None.
Files the package does not list count as a difference (a stray
user_settings.py changes how Proton runs), except Python's own
`__pycache__`, which running protonfixes creates.
"""
for rel, entry in sorted(entries.items()):
path = folder / rel
if entry.kind == "link":
if not path.is_symlink() or str(path.readlink()) != entry.link:
return rel
elif entry.kind == "file" and (
path.is_symlink() or not path.is_file() or sha256_file(path) != entry.sha256
):
return rel
for path in sorted(folder.rglob("*")):
if path.is_dir() and not path.is_symlink():
continue
rel = str(path.relative_to(folder))
if rel not in entries and "__pycache__" not in path.parts and rel != "VERSION":
return rel
return None
def extract(package: Path, dest: Path) -> None:
"""Unpack only the tool folder into `dest`; scripts are never run."""
with tarfile.open(package, "r:zst") as tar:
members = []
for member in tar.getmembers():
if member.name.startswith(PREFIX) and member.name != PREFIX:
member.name = member.name[len(PREFIX) :]
members.append(member)
tar.extractall(dest, members=members, filter="data")

View File

@ -1,157 +0,0 @@
"""Read-only questions about whether Steam will see an install as real.
Split on 2026-09-25 (250-line cap): every manifest write lives in
:mod:`manifest_write`, and
the preconditions for writing in :mod:`finish_check`. What stays here is the
shared vocabulary they all read: depotdownloader's cache, Steam's staging tree
and client process, and whether a manifest's bookkeeping says "done".
"""
from __future__ import annotations
from pathlib import Path
import re
import shutil
from typing import TYPE_CHECKING, Any
from steam_installer import errors, vdf
if TYPE_CHECKING:
from steam_installer.library import SteamLibrary
MANIFEST_CACHE_RE = re.compile(r"^(\d+)_(\d+)\.manifest$")
# depotdownloader's own cache/staging area lives inside the install dir but is
# not game content -- Steam's SizeOnDisk must not count it.
DEPOTDOWNLOADER_DIR = ".DepotDownloader"
# Module-level so tests can point it at a fake /proc tree.
PROC_DIR = Path("/proc")
class RecognizeError(errors.InstallerError):
"""The manifest does not match the install."""
def manifest_reflects_real_install(
library: SteamLibrary, appid: int, install_dir: Path
) -> bool:
"""Whether the manifest matches the real install, not just steamcmd's exit code.
Don't trust steamcmd's exit code alone. Confirmed necessary the hard way:
steamcmd exited 0 while leaving `installdir` pointed at a stale, unrelated
folder name from an earlier corrupted manifest state, `InstalledDepots`
empty, and `StateFlags` still "update needed" -- a "clean" exit that hadn't
actually recognized anything. Relaunching the Steam client then treated the
real, correctly-downloaded folder as orphaned and wiped it while starting a
fresh (slow, wrong-folder) download.
"""
manifest_path = library.steamapps / f"appmanifest_{appid}.acf"
if not manifest_path.is_file():
return False
data = vdf.parse(manifest_path.read_text())
app_state = data.get("AppState", {})
if not isinstance(app_state, dict):
return False
return (
app_state.get("StateFlags") == "4"
and app_state.get("installdir") == install_dir.name
and bool(app_state.get("InstalledDepots"))
and download_counters_settled(app_state)
)
def download_counters_settled(app_state: dict[str, Any]) -> bool:
"""Whether the download bookkeeping agrees that nothing is left to fetch.
This is the check that was missing when Steam threw away a StateFlags=4
manifest and resumed a 90 GB download: the file simultaneously claimed
"fully installed" and "22 GB of 92 GB downloaded". Across every genuine
installed manifest on this machine the counters are equal in pairs and
StagingSize is "0", so treat any inequality as "still downloading".
"""
pairs = (("BytesToDownload", "BytesDownloaded"), ("BytesToStage", "BytesStaged"))
for total_key, done_key in pairs:
total = app_state.get(total_key)
done = app_state.get(done_key)
# Absent counters are fine (Steam omits them on some apps); mismatched
# ones are not.
if total is not None and done is not None and total != done:
return False
return bool(app_state.get("StagingSize", "0") == "0")
def discover_cached_depot_manifests(install_dir: Path) -> dict[str, str]:
"""Depot ID -> manifest ID, from depotdownloader's local cache filenames."""
cache_dir = install_dir / DEPOTDOWNLOADER_DIR
found: dict[str, str] = {}
if not cache_dir.is_dir():
return found
for entry in cache_dir.iterdir():
match = MANIFEST_CACHE_RE.match(entry.name)
if match:
depot_id, manifest_id = match.groups()
found[depot_id] = manifest_id
return found
def clear_steam_staging(library: SteamLibrary, appid: int) -> int:
"""Drop Steam's half-finished staging tree for `appid`. Returns bytes freed.
Steam stages downloaded chunks in `steamapps/downloading/<appid>/` and
commits them into `common/` afterwards. If we declare the app installed
while that tree still holds tens of GB plus its `state_*.patch` files,
Steam finds work pending and resumes the update -- the manifest says
"done", the staging area says "mid-download". Every genuinely installed app
on this machine has an empty (4 KB) staging dir, so matching that is what
"installed" actually looks like on disk.
Only ever discards Steam's own staging copies, never `common/` content.
"""
downloading = library.steamapps / "downloading"
staged = downloading / str(appid)
freed = 0
if staged.is_dir():
freed = sum(f.stat().st_size for f in staged.rglob("*") if f.is_file())
shutil.rmtree(staged)
staged.mkdir(parents=True, exist_ok=True)
for patch in downloading.glob(f"state_{appid}_*.patch"):
freed += patch.stat().st_size
patch.unlink()
return freed
def read_app_state(manifest_path: Path) -> dict[str, Any]:
"""The `AppState` block of a manifest, or an empty dict if unreadable."""
if not manifest_path.is_file():
return {}
data = vdf.parse(manifest_path.read_text())
app_state = data.get("AppState", {})
return app_state if isinstance(app_state, dict) else {}
def steam_client_pids() -> list[int]:
"""PIDs of a running Steam client, if any.
Steam owns appmanifest_*.acf while it runs and rewrites it from its own
in-memory state, so a manifest patched underneath a live client is simply
discarded -- which is exactly what happened on the run that prompted all
this. Matching on the executable path (not a `pgrep -f` pattern) avoids
matching our own command line.
"""
pids: list[int] = []
for entry in PROC_DIR.iterdir():
if not entry.name.isdigit():
continue
try:
exe = (entry / "exe").resolve()
except OSError:
continue
# Match the client by executable name alone. An earlier version also
# required "ubuntu12_32" in the path, which silently fails open for a
# Flatpak install (/app/bin/steam) -- and a guard that quietly stops
# guarding is worse than no guard. `steamcmd` is a different binary, so
# it is not matched here.
if exe.name in ("steam", "steamwebhelper"):
pids.append(int(entry.name))
return pids

View File

@ -1,155 +0,0 @@
"""Resolve a game name to a Steam AppID.
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
from dataclasses import dataclass
import json
import sys
import time
import urllib.error
import urllib.parse
from steam_installer import _http, errors
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
class SearchResult:
"""One candidate from a name search."""
appid: int
name: str
class ResolveError(errors.InstallerError):
"""The target could not be resolved to a single app."""
class SearchUnavailableError(errors.InstallerError):
"""Neither search endpoint could be reached (network/TLS block, not a code bug)."""
def _fetch_json(url: str, timeout: float, *, attempts: int = ATTEMPTS) -> object:
last: Exception = RuntimeError("no attempts made")
for attempt in range(attempts):
try:
with _http.open_https(
url, timeout=timeout, user_agent=USER_AGENT
) 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):
msg = f"unexpected community search payload: {type(payload)}"
raise TypeError(msg)
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):
msg = f"unexpected store search payload: {type(payload)}"
raise TypeError(msg)
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 SearchUnavailableError("; ".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:
"""Show numbered candidates and require an explicit choice. Never guesses."""
if not results:
msg = "No matches found on Steam."
raise ResolveError(msg)
sys.stdout.write("Matches found:\n")
for i, result in enumerate(results, start=1):
sys.stdout.write(f" {i}. {result.name} (appid {result.appid})\n")
while True:
choice = input(f"Which one? [1-{len(results)}, or 0 to cancel]: ").strip()
if choice == "0":
msg = "Cancelled by user."
raise ResolveError(msg)
if choice.isdigit() and 1 <= int(choice) <= len(results):
return results[int(choice) - 1]
sys.stdout.write("Invalid choice, try again.\n")

View File

@ -1,103 +0,0 @@
#!/bin/bash
# ============================================================================
# Install a Steam game from whatever you happen to have: an AppID, a Steam URL,
# or the game's name. Part of steam-backlog-enforcer; the root daemon launches
# `python3 -m steam_installer.cli` itself, so this is the by-hand entry point.
#
# steam_installer/run.sh 284160
# steam_installer/run.sh https://steamcommunity.com/app/284160/guides/
# steam_installer/run.sh BeamNG.drive
# steam_installer/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 REPO_DIR="${SCRIPT_DIR%/*}"
readonly PYTHON="${SGI_PYTHON:-/usr/bin/python3}"
readonly STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/steam-game-installer"
readonly STAMP="${STATE_DIR}/.deps-ok"
readonly INSTALLER="${SCRIPT_DIR}/install_deps.sh"
readonly PROTON_LOCK="${SCRIPT_DIR}/data/proton-native.lock"
# The package lives in this checkout, not in site-packages.
export PYTHONPATH="${REPO_DIR}${PYTHONPATH:+:$PYTHONPATH}"
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
"$PYTHON" -m steam_installer.cli --help
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() {
[[ -f "$STAMP" ]] || return 1
[[ "$STAMP" -nt "$INSTALLER" ]] || return 1
[[ "$STAMP" -nt "${REPO_DIR}/pyproject.toml" ]] || return 1
[[ "$STAMP" -nt "$PROTON_LOCK" ]] || return 1
# A bumped pin or a deleted tool folder: the stamp alone would miss both.
"$PYTHON" -m steam_installer.proton_native --check >/dev/null 2>&1
}
main() {
if [[ "$SKIP_DEPS" != "1" ]] && ! deps_are_current; then
"$INSTALLER"
fi
if [[ "$DEPS_ONLY" -eq 1 ]]; then
exit 0
fi
# `-m` rather than a console script, so a stale install can never shadow
# the working tree.
exec "$PYTHON" -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,233 +0,0 @@
"""Per-run logging.
Everything a run does lands in one file the user can copy-paste verbatim when
something goes wrong. The first version of this tool had no logging at all, and
when a run failed the evidence was gone: Steam owns appmanifest_<appid>.acf and
had already overwritten the manifest we wrote by the time anyone looked. So the
log records the manifest *verbatim, before and after* every write, alongside the
full output of every subprocess.
Subprocess output is teed through a pty rather than captured with
`capture_output=True`. depotdownloader prompts for a password (and possibly a
Steam Guard code) on stdin; prompt text written to a captured/buffered pipe never
reaches the terminal, so the process looks hung with no visible request for
input. A pty keeps it in line-buffered interactive mode and lets us
mirror every byte to both the terminal and the log.
"""
from __future__ import annotations
from dataclasses import dataclass
import errno
import io
import logging
import os
from pathlib import Path
import pty
import select
import shlex
import subprocess
import sys
import time
LOG_DIR = Path.home() / ".local/state/steam-game-installer"
LOGGER_NAME = "steam_installer"
_CONSOLE_FORMAT = "%(message)s"
_FILE_FORMAT = "%(asctime)s %(levelname)-7s %(name)s: %(message)s"
# Read granularity for the pty relay. Large enough that depotdownloader's
# progress spam doesn't cost a syscall per line, small enough to stay responsive.
_READ_CHUNK = 65536
@dataclass
class RunLog:
"""A single run's log file, plus the `latest.log` symlink pointing at it."""
path: Path
logger: logging.Logger
def section(self, title: str) -> None:
"""A visual divider so a pasted log is skimmable."""
self.logger.debug("=" * 72)
self.logger.debug(title)
self.logger.debug("=" * 72)
def file_contents(self, label: str, path: Path) -> None:
"""Record a file verbatim. Used for manifests before/after every write."""
self.section(f"{label}: {path}")
try:
self.logger.debug("\n%s", path.read_text())
except OSError as exc:
self.logger.debug("(unreadable: %s)", exc)
def setup(appid: int | None, *, verbose: bool = False) -> RunLog:
"""Start a run log. Console stays terse; the file gets everything at DEBUG."""
LOG_DIR.mkdir(parents=True, exist_ok=True)
stamp = time.strftime("%Y%m%d-%H%M%S")
path = LOG_DIR / f"run-{stamp}-{appid if appid is not None else 'noappid'}.log"
logger = logging.getLogger(LOGGER_NAME)
logger.setLevel(logging.DEBUG)
logger.propagate = False
# A second setup() in the same process (tests) must not double-log.
for handler in list(logger.handlers):
logger.removeHandler(handler)
handler.close()
file_handler = logging.FileHandler(path, encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(_FILE_FORMAT))
logger.addHandler(file_handler)
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.DEBUG if verbose else logging.INFO)
console.setFormatter(logging.Formatter(_CONSOLE_FORMAT))
logger.addHandler(console)
_point_latest_at(path)
return RunLog(path=path, logger=logger)
def _point_latest_at(path: Path) -> None:
"""Best-effort `latest.log` symlink -- a stale symlink must never fail a run."""
latest = LOG_DIR / "latest.log"
try:
if latest.is_symlink() or latest.exists():
latest.unlink()
latest.symlink_to(path.name)
except OSError:
pass
def _spawn_on_pty(
cmd: list[str], master_fd: int, slave_fd: int
) -> subprocess.Popen[bytes]:
"""Start `cmd` with its output on the pty; close both ends if it won't start."""
try:
return subprocess.Popen(
cmd,
stdout=slave_fd,
stderr=slave_fd,
stdin=_stdin_for_child(slave_fd),
close_fds=True,
)
except OSError:
os.close(master_fd)
os.close(slave_fd)
raise
def run_logged(
cmd: list[str],
logger: logging.Logger,
timeout: float | None = None,
) -> tuple[int, str]:
"""Run `cmd` on a pty, mirroring output to both the terminal and the log.
Returns (returncode, combined_output). stdin stays attached to the real
terminal so interactive prompts (depotdownloader's password / Steam Guard) work
exactly as they do without logging.
"""
logger.debug("$ %s", shlex.join(cmd))
started = time.monotonic()
master_fd, slave_fd = pty.openpty()
chunks: list[bytes] = []
process = _spawn_on_pty(cmd, master_fd, slave_fd)
# The child owns the slave end now; holding it open here would keep the
# master readable forever and hang the relay after the child exits.
os.close(slave_fd)
try:
_relay(master_fd, chunks, process, timeout, started)
except subprocess.TimeoutExpired as exc:
# Record what the child managed to say before it hung, then re-raise.
# Losing it here defeats the whole point of the log in precisely the
# case where it matters most -- a download hung until its timeout.
output = _log_output(logger, chunks, started, returncode=None)
process.wait()
exc.output = output.encode()
raise
finally:
os.close(master_fd)
returncode = process.wait()
output = _log_output(logger, chunks, started, returncode)
return returncode, output
def _log_output(
logger: logging.Logger,
chunks: list[bytes],
started: float,
returncode: int | None,
) -> str:
output = b"".join(chunks).decode("utf-8", errors="replace")
elapsed = time.monotonic() - started
logger.debug("--- output (%d bytes) ---\n%s", len(output), output)
if returncode is None:
logger.debug("TIMED OUT after %.1fs", elapsed)
else:
logger.debug("exit=%d elapsed=%.1fs", returncode, elapsed)
return output
def _read_pty(fd: int, size: int) -> bytes:
"""Read from the pty; an indirection so tests can fault-inject it.
Tests use it instead of patching the global `os.read`, which subprocess
itself uses during spawn.
"""
return os.read(fd, size)
def _stdin_for_child(slave_fd: int) -> int:
"""The child's stdin: the real terminal when there is one, else the pty.
depotdownloader needs a readable stdin to prompt for a password, but `sys.stdin`
is not always a real file descriptor -- under pytest's capture, systemd, or
a piped invocation it has no fileno(). Falling back to the pty's slave end
keeps the child on a terminal-like stdin instead of crashing.
"""
try:
return sys.stdin.fileno()
except AttributeError, ValueError, OSError, io.UnsupportedOperation:
return slave_fd
def _relay(
master_fd: int,
chunks: list[bytes],
process: subprocess.Popen[bytes],
timeout: float | None,
started: float,
) -> None:
"""Pump pty output to stdout and `chunks` until the child closes it."""
while True:
if timeout is not None and time.monotonic() - started > timeout:
process.kill()
raise subprocess.TimeoutExpired(process.args, timeout)
try:
ready, _, _ = select.select([master_fd], [], [], 0.2)
except OSError:
break
if not ready:
# No output pending; the child may still have exited.
if process.poll() is not None:
break
continue
try:
data = _read_pty(master_fd, _READ_CHUNK)
except OSError as exc:
# EIO is the normal "child closed the pty" signal on Linux.
if exc.errno == errno.EIO:
break
raise
if not data:
break
chunks.append(data)
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()

View File

@ -1,84 +0,0 @@
"""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 subprocess
import time
from typing import TYPE_CHECKING
from steam_installer import errors, recognize
if TYPE_CHECKING:
from collections.abc import Callable
import logging
# Looked up on PATH by the OS, as `steam` always was; a name, not a literal in
# the argv list, because ruff S607 objects to partial executable paths there.
STEAM = "steam"
SHUTDOWN_TIMEOUT = 60.0
POLL_INTERVAL = 0.5
class SteamStillRunningError(errors.InstallerError):
"""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 SteamStillRunningError 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()
msg = (
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."
)
raise SteamStillRunningError(msg)
def _spawn_detached(cmd: list[str]) -> subprocess.Popen[bytes]:
"""Start `cmd` in its own session with no output; the caller never waits."""
return subprocess.Popen(
cmd,
start_new_session=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
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.
_spawn_detached([STEAM])

View File

@ -1,125 +0,0 @@
"""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
from dataclasses import dataclass
import os
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import logging
from pathlib import Path
from steam_installer.library import SteamLibrary
@dataclass(frozen=True)
class Staged:
"""Content Steam staged for a download in progress."""
appid: int
staging_dir: Path
install_dir: Path
file_count: int
bytes_staged: int
@dataclass(frozen=True)
class Adoption:
"""What taking over staged content achieved."""
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

@ -1,117 +0,0 @@
"""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 against Steam's own app
cache (`appcache/appinfo.vdf`) 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
from dataclasses import dataclass
import re
import sys
from steam_installer import appinfo, errors, 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(errors.InstallerError):
"""The input could not be resolved to exactly one Steam app."""
@dataclass(frozen=True)
class Resolved:
"""A target resolved to an app and its metadata."""
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:
msg = f"appid {appid} is not a known Steam app ({exc})"
raise TargetError(msg) from exc
def _by_name(text: str, *, interactive: bool) -> Resolved:
try:
results = resolve.search(text)
except resolve.SearchUnavailableError as exc:
msg = f"Steam search is unavailable ({exc}). Pass the numeric AppID instead."
raise TargetError(msg) from exc
if not results:
msg = f"No Steam app matches {text!r}."
raise TargetError(msg)
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.
sys.stderr.write(f"{text!r} is ambiguous. Candidates:\n")
for result in results:
sys.stderr.write(f" {result.appid} {result.name}\n")
msg = (
"Ambiguous name in a non-interactive run. Re-run with the exact "
"title or the numeric AppID."
)
raise TargetError(msg)
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:
msg = "No target given."
raise TargetError(msg)
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 +0,0 @@
"""Installer tests."""

View File

@ -1,79 +0,0 @@
"""Manifest helpers for tests that need a Steam library on disk."""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_installer import vdf
if TYPE_CHECKING:
from pathlib import Path
from steam_installer.library import SteamLibrary
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}
}
"""
def _write(library: SteamLibrary, appid: int, text: str) -> Path:
path = library.steamapps / f"appmanifest_{appid}.acf"
path.write_text(text)
return path
def _real_install(
library: SteamLibrary,
appid: int = 475150,
installdir: str = "RealGame",
size: str = "13908166765",
) -> Path:
"""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
def stamp_native_tool(root: Path, version: str) -> None:
"""Put a ready native Proton (manifest and version stamp) under *root*."""
tool = root / "compatibilitytools.d" / "proton-cachyos-native"
tool.mkdir(parents=True)
(tool / "toolmanifest.vdf").write_text("x")
(tool / "VERSION").write_text(version + "\n")

View File

@ -1,50 +0,0 @@
"""Build a binary appinfo.vdf (magic 0x07564429) for tests.
The writer mirrors what Steam stores: a header, one entry per app (appid,
size, 60 header bytes, binary key-values whose keys index a string table),
a zero appid terminator, then the string table itself.
"""
from __future__ import annotations
import struct
MAGIC = 0x07564429
def _kv(data: dict, strings: dict[str, int]) -> bytes:
out = bytearray()
for key, value in data.items():
index = strings.setdefault(key, len(strings))
if isinstance(value, dict):
out += b"\x00" + struct.pack("<I", index) + _kv(value, strings)
elif isinstance(value, int):
out += b"\x02" + struct.pack("<I", index) + struct.pack("<i", value)
elif isinstance(value, float):
out += b"\x03" + struct.pack("<I", index) + struct.pack("<f", value)
elif isinstance(value, tuple):
kind, raw = value # (7, u64) / (10, i64): the wide integer types
fmt = "<Q" if kind == 7 else "<q"
out += bytes([kind]) + struct.pack("<I", index) + struct.pack(fmt, raw)
else:
out += b"\x01" + struct.pack("<I", index) + value.encode() + b"\x00"
return bytes(out) + b"\x08"
def encode(apps: dict[int, dict], change_number: int = 41062472) -> bytes:
"""Serialize `{appid: appinfo-dict}`; each dict is wrapped in "appinfo"."""
strings: dict[str, int] = {}
body = bytearray()
for appid, data in apps.items():
kv = _kv({"appinfo": data}, strings)
header = struct.pack(
"<IIQ20sI20s", 2, 1795000000, 0, b"\0" * 20, change_number, b"\0" * 20
)
payload = header + kv
body += struct.pack("<II", appid, len(payload)) + payload
body += struct.pack("<I", 0)
table_offset = 16 + len(body)
table = struct.pack("<I", len(strings)) + b"".join(
key.encode() + b"\x00" for key in strings
)
return struct.pack("<IIq", MAGIC, 1, table_offset) + bytes(body) + table

View File

@ -1,43 +0,0 @@
"""Stubs shared by the CLI flow tests (plain functions, not fixtures)."""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_installer import appinfo, depotdl, recognize
if TYPE_CHECKING:
from pathlib import Path
import pytest
ARGV = ["--appid", "1771300", "--username", "u", "--language", "english"]
def _stub_download(monkeypatch: pytest.MonkeyPatch, returncode: int = 0) -> None:
monkeypatch.setattr(depotdl, "download", lambda appid, pull, logger: returncode)
def proven_plan(
monkeypatch: pytest.MonkeyPatch,
install_dir: Path,
shared_owner: dict[str, str] | None = None,
shared: set[str] | None = None,
) -> str:
"""Stub the depot plan so the cached manifest proves the public build.
*shared* defaults to the depots *shared_owner* names. Returns the gid.
"""
gid = next(iter(recognize.discover_cached_depot_manifests(install_dir).values()))
shared_depots = set(shared_owner or ()) if shared is None else shared
monkeypatch.setattr(
appinfo,
"get_depot_plan",
lambda appid, language: appinfo.DepotPlan(
{"1771303"},
shared_depots,
manifests={"1771303": gid},
shared_owner=dict(shared_owner or {}),
),
)
return gid

View File

@ -1,31 +0,0 @@
"""Shared data for the map-installed tests."""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_installer import compat_map, proton_pkg
if TYPE_CHECKING:
from pathlib import Path
LOCKED = proton_pkg.read_lock().version
CONFIG = (
'"InstallConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n'
'\t\t\t"Steam"\n\t\t\t{\n\t\t\t}\n\t\t}\n\t}\n}\n'
)
PLAIN = {
"common": {"name": "Plain", "oslist": "windows", "type": "Game"},
"depots": {"11": {"config": {"oslist": "windows"}}},
}
NATIVE = {"common": {"name": "Native", "oslist": "windows,linux", "type": "Game"}}
SHARED = {
"common": {"name": "Shared", "oslist": "windows", "type": "Game"},
"depots": {"31": {"depotfromapp": "228980"}},
}
CS = {"common": {"name": "CS", "oslist": "windows,linux", "type": "Game"}}
TOOL = {"common": {"name": "Proton Experimental", "type": "Tool"}}
def _mapped(root: Path, appid: int) -> tuple[str, str] | None:
return compat_map.current(root / "config" / "config.vdf", appid)

View File

@ -1,157 +0,0 @@
"""A tiny fake CachyOS repo: a signed proton package, its db and the signing key.
Built for real (zstd tars, a gzip .MTREE, a gpg detached signature from a
throwaway ed25519 key) so the fetcher's checks run against the same formats
the real mirror serves.
"""
from __future__ import annotations
from dataclasses import dataclass
import gzip
import hashlib
import io
import shutil
import subprocess
import tarfile
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
from steam_installer.proton_pkg import Lock
type Setup = tuple[Path, Lock, Callable[..., str]]
PREFIX = "usr/share/steam/compatibilitytools.d/proton-cachyos-native/"
VERSION = "1:11.0.20261015-1"
FILENAME = f"proton-cachyos-native-{VERSION}-x86_64.pkg.tar.zst"
FILES = {
"toolmanifest.vdf": b'"manifest"\n{\n "commandline" "/proton %verb%"\n}\n',
"proton": b"#!/usr/bin/env python3\n",
"files/bin/wine": b"\x7fELF wine",
"user settings.py": b"# a name with a space\n",
}
LINKS = {"files/bin/msidb": "wine"}
GPG = shutil.which("gpg") or "gpg"
GPGCONF = shutil.which("gpgconf") or "gpgconf"
@dataclass
class Repo:
"""Repo."""
root: Path # served as the mirror: holds cachyos.db, the package, the .sig
key: Path
fingerprint: str
sha256: str
gpg_home: Path
@property
def db_url(self) -> str:
"""Db url."""
return (self.root / "cachyos.db").as_uri()
@property
def package(self) -> Path:
"""Package."""
return self.root / FILENAME
def _mtree() -> bytes:
lines = ["#mtree", "/set type=file uid=0 gid=0 mode=644"]
lines.append("./.INSTALL time=1.0 size=3 sha256digest=00")
lines.append(f"./{PREFIX.rstrip('/')} time=1.0 mode=755 type=dir")
for name, data in FILES.items():
digest = hashlib.sha256(data).hexdigest()
path = (PREFIX + name).replace(" ", "\\040")
lines.append(f"./{path} time=1.0 size={len(data)} sha256digest={digest}")
for name, target in LINKS.items():
lines.append(f"./{PREFIX}{name} time=1.0 mode=777 type=link link={target}")
return gzip.compress(("\n".join(lines) + "\n").encode())
def _add(tar: tarfile.TarFile, name: str, data: bytes) -> None:
info = tarfile.TarInfo(name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
def build_package(path: Path, files: dict[str, bytes] | None = None) -> None:
"""Build package."""
files = FILES if files is None else files
with tarfile.open(path, "w:zst") as tar:
_add(tar, ".INSTALL", b"rm -rf /\n") # never run, never extracted
_add(tar, ".MTREE", _mtree())
_add(tar, "usr/bin/stray", b"outside the tool folder")
for name, data in files.items():
_add(tar, PREFIX + name, data)
for name, target in LINKS.items():
info = tarfile.TarInfo(PREFIX + name)
info.type = tarfile.SYMTYPE
info.linkname = target
tar.addfile(info)
def build_db(
path: Path, version: str, sha256: str, name: str = "proton-cachyos-native"
) -> None:
"""Build db."""
desc = (
f"%FILENAME%\n{name}-{version}-x86_64.pkg.tar.zst\n\n%NAME%\n{name}\n\n"
f"%VERSION%\n{version}\n\n%SHA256SUM%\n{sha256}\n\n"
).encode()
other = b"%NAME%\nproton-cachyos-native-v3\n\n%VERSION%\n9:9-9\n\n"
with tarfile.open(path, "w:zst") as tar:
_add(tar, "proton-cachyos-native-v3-9:9-9/desc", other)
_add(tar, f"{name}-{version}/desc", desc)
def gpg(home: Path, *args: str) -> None:
"""Gpg."""
subprocess.run(
[GPG, "--homedir", str(home), "--batch", "--passphrase", "", *args],
check=True,
capture_output=True,
)
def build_repo(tmp: Path) -> Repo:
"""Build repo."""
root = tmp / "mirror"
root.mkdir()
home = tmp / "signer"
home.mkdir(mode=0o700)
gpg(
home,
"--quick-gen-key",
"Fake CachyOS <fake@example.invalid>",
"ed25519",
"sign",
"never",
)
listing = subprocess.run(
[GPG, "--homedir", str(home), "--with-colons", "--fingerprint"],
check=True,
capture_output=True,
text=True,
).stdout
fingerprint = next(
line.split(":")[9] for line in listing.splitlines() if line.startswith("fpr")
)
key = tmp / "key.asc"
gpg(home, "--armor", "--output", str(key), "--export", fingerprint)
package = root / FILENAME
build_package(package)
gpg(home, "--output", f"{package}.sig", "--detach-sign", str(package))
sha256 = hashlib.sha256(package.read_bytes()).hexdigest()
build_db(root / "cachyos.db", VERSION, sha256)
return Repo(root, key, fingerprint, sha256, home)
def stop_agent(home: Path) -> None:
"""Stop agent."""
subprocess.run([GPGCONF, "--homedir", str(home), "--kill", "all"], check=False)

View File

@ -1,36 +0,0 @@
"""Fixtures-as-functions shared by the recognize/manifest test files."""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_installer import vdf
if TYPE_CHECKING:
from pathlib import Path
def _write_partial_manifest(steamapps: Path, appid: int) -> None:
steamapps.mkdir(parents=True, exist_ok=True)
data = {
"appid": str(appid),
"StateFlags": "1026",
"buildid": "23914554",
"SharedDepots": {"228989": "228980"},
}
(steamapps / f"appmanifest_{appid}.acf").write_text(vdf.dumps("AppState", data))
def _fake_proc(tmp_path: Path, entries: dict[str, str | None]) -> Path:
"""Build a /proc-shaped tree: {pid: exe_target_path_or_None}."""
proc = tmp_path / "proc"
proc.mkdir()
for name, target in entries.items():
entry = proc / name
entry.mkdir()
if target is not None:
real = tmp_path / "bin" / target
real.parent.mkdir(parents=True, exist_ok=True)
real.write_text("")
(entry / "exe").symlink_to(real)
return proc

View File

@ -1,19 +0,0 @@
"""Run a command in a test and capture its text output."""
from __future__ import annotations
import subprocess
def run_captured(
argv: list[str], env: dict[str, str], timeout: float = 30
) -> subprocess.CompletedProcess[str]:
"""Run *argv* under *env*, text output captured, never raising on exit code."""
return subprocess.run(
argv,
capture_output=True,
text=True,
env=env,
timeout=timeout,
check=False,
)

View File

@ -1,49 +0,0 @@
"""A fake Steam root for the map-installed tests: config, app cache, manifests."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from steam_installer import anticheat, compat_apply, vdf
from steam_installer.tests._acf_helpers import stamp_native_tool
from steam_installer.tests._appinfo_blob import encode
from steam_installer.tests._map_data import CONFIG, LOCKED
if TYPE_CHECKING:
from collections.abc import Iterable
from pathlib import Path
import pytest
def build_root(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
*,
cached: dict[int, dict[str, Any]],
installed: Iterable[int],
anticheat_json: bytes,
) -> Path:
"""A Steam root with the stamped tool, an app cache and installed manifests.
*cached* is the app cache's content; *installed* the appids that get an
``appmanifest`` (named ``Game<appid>``), cached or not.
"""
root = tmp_path / "Steam"
(root / "config").mkdir(parents=True)
(root / "config" / "config.vdf").write_text(CONFIG)
stamp_native_tool(root, LOCKED)
cache = tmp_path / "appinfo.vdf"
cache.write_bytes(encode(cached))
monkeypatch.setattr(
compat_apply.appinfo.appinfo_cache, "default_path", lambda: cache
)
monkeypatch.setattr(anticheat, "_download", lambda: anticheat_json)
steamapps = root / "steamapps"
steamapps.mkdir()
for appid in installed:
state = {"appid": str(appid), "name": f"Game{appid}", "InstalledDepots": {}}
(steamapps / f"appmanifest_{appid}.acf").write_text(
vdf.dumps("AppState", state)
)
return root

View File

@ -1,236 +0,0 @@
"""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.
"""
from __future__ import annotations
import logging
import os
import pathlib
from pathlib import Path
import shutil
from typing import TYPE_CHECKING, Never
import pytest
from steam_installer import (
anticheat,
appinfo,
appinfo_cache,
cli,
config,
depotdl,
deps,
proton_native,
proton_pkg,
recognize,
runlog,
steamctl,
vdf,
)
from steam_installer.library import SteamLibrary
from steam_installer.tests._proton_fixture import VERSION, Repo, build_repo, stop_agent
if TYPE_CHECKING:
from collections.abc import Iterator
from steam_installer.tests._proton_fixture import Setup
@pytest.fixture
def coverage_subprocess_env() -> dict[str, str]:
"""Env for a child process that should also record coverage."""
env = os.environ.copy()
root = pathlib.Path(__file__).resolve().parents[2]
env["COVERAGE_PROCESS_START"] = str(root / "pyproject.toml")
env["PYTHONPATH"] = str(root) + os.pathsep + env.get("PYTHONPATH", "")
return env
@pytest.fixture(name="library")
def _library(tmp_path: Path) -> SteamLibrary:
"""The library fixture."""
lib = SteamLibrary(tmp_path / "Steam")
lib.steamapps.mkdir(parents=True)
lib.common.mkdir(parents=True)
return lib
@pytest.fixture
def isolated_cli(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest
) -> None:
"""The isolated cli fixture."""
# Requested by name: pylint rejects an argument that is only there for its effect.
request.getfixturevalue("cli_logs")
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)
@pytest.fixture
def cli_steam(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest
) -> SteamLibrary:
"""A fake Steam library with the cli isolated from this machine's state."""
# Requested by name: pylint rejects an argument that is only there for its effect.
request.getfixturevalue("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 *a, **kw: pytest.fail("must not download")
)
return library
@pytest.fixture(autouse=True)
def _no_host_depotdownloader(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Never let this machine's ~/.local/bin decide which binary a test sees."""
monkeypatch.setattr(deps, "MANAGED_DEPOTDOWNLOADER", tmp_path / "absent")
@pytest.fixture
def cli_logs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""The cli logs fixture."""
monkeypatch.setattr(runlog, "LOG_DIR", tmp_path / "state")
yield
logger = logging.getLogger(runlog.LOGGER_NAME)
for handler in list(logger.handlers):
logger.removeHandler(handler)
handler.close()
@pytest.fixture
def steam(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[SteamLibrary, Path]:
"""A Steam tree with KCD2 downloaded but its manifest not yet finished."""
root = tmp_path / "Steam"
library = SteamLibrary(root)
install_dir = library.common / "KingdomComeDeliverance2"
cache = install_dir / ".DepotDownloader"
cache.mkdir(parents=True)
(cache / "1771303_1999516201078544527.manifest").write_bytes(b"x")
(install_dir / "game.pak").write_bytes(b"x" * 1000)
library.steamapps.mkdir(parents=True, exist_ok=True)
(library.steamapps / "appmanifest_1771300.acf").write_text(
vdf.dumps(
"AppState",
{
"appid": "1771300",
"StateFlags": "1026",
"buildid": "23914554",
"BytesToDownload": "92009052960",
"BytesDownloaded": "22129058224",
},
)
)
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(deps.shutil, "which", lambda name: f"/usr/bin/{name}")
monkeypatch.setattr(
appinfo,
"get_metadata",
lambda appid: appinfo.AppMetadata(appid, "KCD2", "KingdomComeDeliverance2"),
)
monkeypatch.setattr(
appinfo,
"get_depot_plan",
lambda appid, language: appinfo.DepotPlan({"1771303"}, {"228989"}),
)
monkeypatch.setattr(appinfo, "get_build_id", lambda appid: "23914554")
# No DLC unless a test says so: the real lookup is a steamcmd call.
monkeypatch.setattr(appinfo, "get_dlc_plans", lambda appid, language: {})
monkeypatch.setattr(recognize, "steam_client_pids", list)
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
@pytest.fixture(autouse=True)
def _no_live_compat_side_effects(
request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""No test may fetch the anti-cheat list or read the real app cache.
The modules that test those seams themselves (with their own fakes) are
exempt from the part they cover.
"""
def offline() -> Never:
msg = "tests are offline"
raise OSError(msg)
module = request.node.module.__name__.rsplit(".", 1)[-1]
if not request.node.name.startswith("test_anticheat_download"):
monkeypatch.setattr(anticheat, "_download", offline)
monkeypatch.setattr(anticheat, "CACHE", tmp_path / "no-anticheat-cache.json")
if module != "test_appinfo_cache":
monkeypatch.setattr(
appinfo_cache, "default_path", lambda: tmp_path / "no-appinfo.vdf"
)
# The live Steam client is never seen, stopped or started by a test: an
# unstubbed --apply run once shut down and relaunched kuhy's real Steam.
if module in ("test_steamctl", "test_recognize"):
return # these fake subprocess and /proc themselves
monkeypatch.setattr(recognize, "steam_client_pids", list)
monkeypatch.setattr(
steamctl, "stop", lambda *a, **k: pytest.fail("real steam stop")
)
monkeypatch.setattr(
steamctl, "start", lambda *a, **k: pytest.fail("real steam start")
)
@pytest.fixture(name="repo", scope="module")
def _repo(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Repo]:
"""The repo fixture."""
built = build_repo(tmp_path_factory.mktemp("repo"))
yield built
stop_agent(built.gpg_home)
@pytest.fixture(name="mirror")
def _mirror(repo: Repo, tmp_path: Path) -> Path:
"""A private copy of the fake mirror a test may tamper with."""
root = tmp_path / "mirror"
shutil.copytree(repo.root, root)
return root
@pytest.fixture
def setup(
repo: Repo, mirror: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> Setup:
"""The setup fixture."""
tools = tmp_path / "compatibilitytools.d"
tools.mkdir()
lock = proton_pkg.Lock(
"proton-cachyos-native", (mirror / "cachyos.db").as_uri(), VERSION, repo.sha256
)
monkeypatch.setattr(proton_native, "in_use", lambda tool: [])
def run(**kw: object) -> str:
return proton_native.ensure(
tools, lock, key=repo.key, fingerprint=repo.fingerprint, **kw
)
return tools, lock, run

View File

@ -1,199 +0,0 @@
"""Tests for appinfo."""
from __future__ import annotations
import pytest
from steam_installer import appinfo
def _app_block(monkeypatch: pytest.MonkeyPatch, block: dict[str, object]) -> None:
monkeypatch.setattr(appinfo, "fetch_app_block", lambda appid: block)
# Every real depot that has content ships a manifest on the public branch.
_PUB = {"manifests": {"public": {"gid": "1"}}}
# Shape taken from a real `app_info_print 1771300`: 12 depots, of which an
# english/windows install only ever fetches three.
KCD2_DEPOTS = {
"228989": {"depotfromapp": "228980", "config": {"oslist": "windows"}, **_PUB},
"1771302": {"config": {"oslist": "windows"}, **_PUB},
"1771303": {"config": {"oslist": "windows"}, **_PUB},
"1771304": {"dlcappid": "3406020", "config": {"oslist": "windows"}, **_PUB},
"1771305": {"config": {"oslist": "windows", "language": "czech"}, **_PUB},
"1771306": {"config": {"oslist": "windows", "language": "english"}, **_PUB},
"1771307": {"config": {"oslist": "windows", "language": "french"}, **_PUB},
"4075290": {"dlcappid": "4075290", **_PUB},
"branches": {"public": {"buildid": "23914554"}},
}
def test_get_depot_plan_selects_only_this_language_and_os(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get depot plan selects only this language and os."""
_app_block(monkeypatch, {"depots": KCD2_DEPOTS})
plan = appinfo.get_depot_plan(1771300, language="english", os_name="windows")
assert plan.required == {"1771302", "1771303", "1771306"}
assert plan.shared == {"228989"}
assert plan.all_expected == {"1771302", "1771303", "1771306", "228989"}
def test_get_depot_plan_switches_language(monkeypatch: pytest.MonkeyPatch) -> None:
"""Get depot plan switches language."""
_app_block(monkeypatch, {"depots": KCD2_DEPOTS})
plan = appinfo.get_depot_plan(1771300, language="czech")
assert "1771305" in plan.required
assert "1771306" not in plan.required
def test_get_depot_plan_excludes_other_os(monkeypatch: pytest.MonkeyPatch) -> None:
"""Get depot plan excludes other os."""
_app_block(
monkeypatch,
{
"depots": {
"10": {"config": {"oslist": "linux"}, **_PUB},
"11": {"config": {}, **_PUB},
}
},
)
plan = appinfo.get_depot_plan(1771300, os_name="windows")
assert plan.required == {"11"}
def test_get_depot_plan_skips_optional_depots(monkeypatch: pytest.MonkeyPatch) -> None:
"""Get depot plan skips optional depots."""
_app_block(monkeypatch, {"depots": {"10": {"optional": "1", **_PUB}, "11": _PUB}})
assert appinfo.get_depot_plan(1771300).required == {"11"}
def test_get_depot_plan_rejects_malformed_depots_section(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get depot plan rejects malformed depots section."""
_app_block(monkeypatch, {"depots": "not-a-dict"})
with pytest.raises(appinfo.AppInfoError, match="depots"):
appinfo.get_depot_plan(1771300)
def test_get_depot_plan_with_no_depots_is_empty(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""An app with no depot list yields nothing required -- callers must not
read that as "everything downloaded fine"."""
_app_block(monkeypatch, {})
plan = appinfo.get_depot_plan(1771300)
assert plan.required == set()
assert plan.shared == set()
def test_get_build_id_reads_public_branch(monkeypatch: pytest.MonkeyPatch) -> None:
"""Get build id reads public branch."""
_app_block(monkeypatch, {"depots": KCD2_DEPOTS})
assert appinfo.get_build_id(1771300) == "23914554"
def test_get_build_id_missing_branch_returns_none(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get build id missing branch returns none."""
_app_block(monkeypatch, {"depots": {"branches": {}}})
assert appinfo.get_build_id(1771300) is None
def test_get_build_id_without_depots_returns_none(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get build id without depots returns none."""
_app_block(monkeypatch, {})
assert appinfo.get_build_id(1771300) is None
def test_get_metadata_reads_name_and_installdir(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get metadata reads name and installdir."""
_app_block(
monkeypatch,
{
"common": {
"name": "Kingdom Come: Deliverance II",
"installdir": "KingdomComeDeliverance2",
}
},
)
metadata = appinfo.get_metadata(1771300)
assert metadata.name == "Kingdom Come: Deliverance II"
assert metadata.installdir == "KingdomComeDeliverance2"
def test_get_metadata_falls_back_to_config_installdir(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get metadata falls back to config installdir."""
_app_block(
monkeypatch,
{"common": {"name": "Game"}, "config": {"installdir": "GameDir"}},
)
assert appinfo.get_metadata(1).installdir == "GameDir"
def test_get_metadata_requires_name(monkeypatch: pytest.MonkeyPatch) -> None:
"""Get metadata requires name."""
_app_block(monkeypatch, {"common": {"installdir": "GameDir"}})
with pytest.raises(appinfo.AppInfoError, match="no name field"):
appinfo.get_metadata(1)
def test_get_metadata_requires_installdir(monkeypatch: pytest.MonkeyPatch) -> None:
"""Get metadata requires installdir."""
_app_block(monkeypatch, {"common": {"name": "Game"}})
with pytest.raises(appinfo.AppInfoError, match="no installdir"):
appinfo.get_metadata(1)
def test_get_metadata_rejects_malformed_common_section(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get metadata rejects malformed common section."""
_app_block(monkeypatch, {"common": "not-a-dict"})
with pytest.raises(appinfo.AppInfoError, match="no 'common' section"):
appinfo.get_metadata(1)
def test_get_build_id_handles_non_dict_sections(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get build id handles non dict sections."""
for block in (
{"depots": "scalar"},
{"depots": {"branches": "scalar"}},
{"depots": {"branches": {"public": "x"}}},
):
_app_block(monkeypatch, block)
assert appinfo.get_build_id(1) is None
def test_get_build_id_returns_none_when_buildid_not_a_string(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Get build id returns none when buildid not a string."""
_app_block(monkeypatch, {"depots": {"branches": {"public": {"buildid": {}}}}})
assert appinfo.get_build_id(1) is None
def test_a_shared_install_without_an_owner_is_still_shared(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A shared install without an owner is still shared."""
_app_block(
monkeypatch,
{"depots": {"5": {"sharedinstall": "1"}, "6": {"depotfromapp": "228980"}}},
)
plan = appinfo.get_depot_plan(1)
assert plan.shared == {"5", "6"}
assert plan.shared_owner == {"6": "228980"}

View File

@ -1,115 +0,0 @@
"""Steam's local binary app-info cache, read without steamcmd."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import pytest
from steam_installer import appinfo_cache
from steam_installer.appinfo_cache import _parse
from steam_installer.tests._appinfo_blob import encode
if TYPE_CHECKING:
from pathlib import Path
def _write(tmp_path: Path, apps: dict[int, Any]) -> Path:
path = tmp_path / "appinfo.vdf"
path.write_bytes(encode(apps))
return path
def test_reads_every_app_and_unwraps_appinfo(tmp_path: Path) -> None:
"""Reads every app and unwraps appinfo."""
path = _write(tmp_path, {10: {"common": {"name": "A"}}, 20: {"common": {}}})
apps = appinfo_cache.load(path)
assert set(apps) == {10, 20}
assert apps[10] == {"common": {"name": "A"}}
def test_scalars_come_back_as_strings_like_app_info_print(tmp_path: Path) -> None:
"""The rest of the tool compares `== "1"` and `!= str(appid)`; an int here
would silently drop a DLC app's own depots."""
data = {
"depots": {
"5": {
"dlcappid": 7,
"optional": 1,
"f": 1.5,
"gid": (7, 2**63 + 5),
"neg": (10, -3),
}
}
}
apps = appinfo_cache.load(_write(tmp_path, {7: data}))
assert apps[7]["depots"]["5"] == {
"dlcappid": "7",
"optional": "1",
"f": "1.5",
"gid": str(2**63 + 5),
"neg": "-3",
}
def test_parse_is_cached_until_the_file_changes(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Parse is cached until the file changes."""
path = _write(tmp_path, {1: {"common": {"name": "old"}}})
assert appinfo_cache.load(path)[1]["common"]["name"] == "old"
calls = []
real = _parse
def counting(buf: bytes) -> dict[int, dict[str, Any]]:
calls.append(1)
return real(buf)
monkeypatch.setattr(appinfo_cache, "_parse", counting)
appinfo_cache.load(path)
assert calls == []
path.write_bytes(encode({1: {"common": {"name": "newer"}}}))
assert appinfo_cache.load(path)[1]["common"]["name"] == "newer"
assert calls == [1]
def test_wrong_magic_is_refused(tmp_path: Path) -> None:
"""Wrong magic is refused."""
path = tmp_path / "appinfo.vdf"
path.write_bytes(b"\x28\x44\x56\x07" + b"\0" * 20)
with pytest.raises(appinfo_cache.CacheError, match="unsupported"):
appinfo_cache.load(path)
def test_unknown_value_type_is_refused(tmp_path: Path) -> None:
"""Unknown value type is refused."""
blob = bytearray(encode({1: {"common": {"name": "A"}}}))
blob[16 + 8 + 60] = 9 # first KV type byte
path = tmp_path / "appinfo.vdf"
path.write_bytes(bytes(blob))
with pytest.raises(appinfo_cache.CacheError, match="value type 9"):
appinfo_cache.load(path)
def test_missing_file_names_the_fix(tmp_path: Path) -> None:
"""Missing file names the fix."""
with pytest.raises(appinfo_cache.CacheError, match="start Steam once"):
appinfo_cache.load(tmp_path / "nope.vdf")
def test_entry_without_appinfo_wrapper_is_taken_as_is(tmp_path: Path) -> None:
"""Entry without appinfo wrapper is taken as is."""
blob = encode({3: {"x": "y"}})
# Rename the "appinfo" wrapper key in the string table.
blob = blob.replace(b"appinfo\x00", b"appinfX\x00")
path = tmp_path / "appinfo.vdf"
path.write_bytes(blob)
assert appinfo_cache.load(path)[3] == {"appinfX": {"x": "y"}}
def test_default_path_is_under_the_steam_root(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""Default path is under the steam root."""
monkeypatch.setattr(appinfo_cache, "find_steam_root", lambda: tmp_path)
assert appinfo_cache.default_path() == tmp_path / "appcache" / "appinfo.vdf"

View File

@ -1,96 +0,0 @@
"""get_metadata/get_build_id/get_dlc_plans answered from Steam's binary cache."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import pytest
from steam_installer import appinfo
from steam_installer.tests._appinfo_blob import encode
if TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
# The block steamcmd's app_info_print used to return for KCD2, now as Steam
# keeps it in its binary cache. The differential tests below pin that the
# cache gives the same answers the steamcmd text did.
KCD2: dict[str, Any] = {
"common": {
"name": "Kingdom Come: Deliverance II",
"installdir": "KingdomComeDeliverance2",
},
"depots": {
"1771303": {"config": {"oslist": "windows"}},
"branches": {"public": {"buildid": 23914554}},
},
}
@pytest.fixture(name="cache")
def _cache(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> Callable[[dict[int, Any]], None]:
"""Point appinfo at a fixture cache; returns a writer for its apps."""
path = tmp_path / "appinfo.vdf"
monkeypatch.setattr(appinfo.appinfo_cache, "default_path", lambda: path)
def write(apps: dict[int, Any]) -> None:
path.write_bytes(encode(apps))
return write
def test_metadata_comes_from_steams_cache(
cache: Callable[[dict[int, Any]], None],
) -> None:
"""Metadata comes from Steam's cache."""
cache({1771300: KCD2})
metadata = appinfo.get_metadata(1771300)
assert metadata.name == "Kingdom Come: Deliverance II"
assert metadata.installdir == "KingdomComeDeliverance2"
def test_get_build_id_through_the_real_parser(
cache: Callable[[dict[int, Any]], None],
) -> None:
# Stored as an int32 in the binary cache; still a string like steamcmd's.
"""Get build id through the real parser."""
cache({1771300: KCD2})
assert appinfo.get_build_id(1771300) == "23914554"
def test_app_missing_from_the_cache_fails_with_the_fix(
cache: Callable[[dict[int, Any]], None],
) -> None:
"""App missing from the cache fails with the fix."""
cache({1771300: KCD2})
with pytest.raises(
appinfo.AppInfoError, match="start Steam once, let it sync, rerun"
):
appinfo.get_metadata(999999999)
def test_unreadable_cache_fails_with_the_fix(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Unreadable cache fails with the fix."""
monkeypatch.setattr(
appinfo.appinfo_cache, "default_path", lambda: tmp_path / "missing.vdf"
)
with pytest.raises(appinfo.AppInfoError, match="start Steam once"):
appinfo.get_metadata(1)
def test_dlc_missing_from_the_cache_counts_as_not_owned(
cache: Callable[[dict[int, Any]], None],
) -> None:
"""Steam caches app info for what the account owns; on 2026-11-22 only 1828
of 7102 listed DLC ids were in the cache. Refusing on a missing one would
block installs that worked with steamcmd."""
game = {**KCD2, "extended": {"listofdlc": "500,600"}}
dlc = {"depots": {"501": {"manifests": {"public": {"gid": "9"}}}}}
cache({1771300: game, 500: dlc})
assert appinfo.get_dlc_plans(1771300) == {500: {"501": "9"}}

Some files were not shown because too many files have changed in this diff Show More