fix: the first Qodana findings

No behaviour changes; each is what the inspection asked, or the type
information it lacked.

Python (scripts/):
- `return (a, b)` -> `return a, b` (12, steam_client, store_items,
  backfill_discover).
- `log=print` parameters annotated `Callable[[str], None]`: PyCharm could
  not type the overloaded builtin as a default and called every log(...)
  "not callable" (10, budget, purge_unhealthy, refresh_anticheat,
  refresh_peaks).
- fetch_full()'s docstring names all its parameters.
- Nested helpers no longer shadow the loop variables of the function
  around them (purge_unhealthy judge(), update_reviews ask()).
- The leaderboards' bare `except:` catches what a reviews string can
  raise (AttributeError, TypeError, ValueError), not SystemExit and
  KeyboardInterrupt too.
- edit_game.py: unused `import json` dropped; mark_dead_games `[^\d]` ->
  `\D`; the DLC section regex loses a group around the whole pattern
  (only ever used with search()).

TypeScript / Svelte (web/):
- Two comma expressions written as statements (pipeline route's run
  dedupe, CandidateDialog's Reopen button).
- shouldIgnore() returns its last condition instead of if/return.
- Resource's constructor-only private fields are readonly.
- The admin mock seed says HOUR, not 1 * HOUR.

Rust (web/src-tauri/): `serde` dropped - nothing in the crate or in what
generate_context!() expands uses it (only `::serde_json` paths are
generated). serde_json stays, with a comment: Qodana calls it unused
too, but the generated code needs it and the crate does not compile
without it.

Checked: pytest 467, typecheck, vitest 747, knip, cargo test --lib.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-11-17 08:54:28 +07:00
1 parent a956c8e182
commit 11c38dba24
21 files changed
+58 -44

No files matched your search

+1 -1
View File
@@ -80,7 +80,7 @@ def parse_released(text):
m = _RE_Y.match(t)
if m:
# Year-only rows sort with the year's start, so bucket them there.
return (int(m.group(1)), 1)
return int(m.group(1)), 1
return None
+3 -1
View File
@@ -21,6 +21,7 @@ run on a laptop works as it always did.
import math
import os
import time
from collections.abc import Callable
from typing import Optional
ENV = "JOB_BUDGET_MINUTES"
@@ -62,7 +63,8 @@ def expired(deadline: Optional[Deadline]) -> bool:
return deadline is not None and deadline.expired()
def report(desc: str, done: int, total: int, deadline: Optional[Deadline], log=print) -> None:
def report(desc: str, done: int, total: int, deadline: Optional[Deadline],
log: Callable[[str], None] = print) -> None:
"""One line on how a loop used the budget. A run that stopped short, or
came close, gets a ::warning:: - it is how a growing catalogue shows up in
the run's annotations before it costs one."""
+5
View File
@@ -304,6 +304,11 @@ def fetch_full(game: dict, client=None, fetch_players=True,
Fetch all data for one game.
Args:
game: the record to fill; its `link` names the app.
client: the SteamClient to use; None means get_client().
fetch_players: also ask for the current player count (needs STEAM_API_KEY).
scrape: also read the store page, or Steam's JSON API for a gated game:
tags, languages, DLC, the anti-cheat disclosure.
prefetched_details: If health_checker already fetched appdetails,
pass it here to avoid a second API call.
guard: an overrides.OverrideGuard. The anti-cheat fields are written
+1 -1
View File
@@ -28,7 +28,7 @@ _RE_STRIP_HTML = re.compile(r'<[^>]+>')
_RE_CLASS_VALUE = re.compile(r'class\s*=\s*"([^"]*)"', re.IGNORECASE)
_RE_DLC_SECTION_START = re.compile(
r'(?:id\s*=\s*"gameAreaDLCSection"|class\s*=\s*"game_area_dlc_section")',
r'id\s*=\s*"gameAreaDLCSection"|class\s*=\s*"game_area_dlc_section"',
re.IGNORECASE,
)
_RE_DLC_PRICE_ATTR = re.compile(r'data-price-final\s*=\s*"(\d+)"')
+9 -9
View File
@@ -144,16 +144,16 @@ class SteamClient:
throttle_fn=self._throttle_store,
)
if not resp:
return ("network_error", None)
return "network_error", None
if resp.status_code in (404, 410):
return ("not_found", None)
return "not_found", None
try:
entry = resp.json().get(str(appid), {})
if entry.get("success"):
return ("ok", entry["data"])
return ("unavailable", None)
return "ok", entry["data"]
return "unavailable", None
except (ValueError, KeyError):
return ("network_error", None)
return "network_error", None
def fetch_app_details(self, appid: str) -> Optional[dict]:
status, data = self.fetch_app_details_full(appid)
@@ -202,13 +202,13 @@ class SteamClient:
cookies=STORE_AGE_COOKIES,
)
if not resp:
return ("network_error", None)
return "network_error", None
if resp.status_code in (404, 410):
return ("not_found", None)
return "not_found", None
if resp.status_code != 200:
return ("network_error", None)
return "network_error", None
status = store_page_status(appid, resp.url, [h.url for h in resp.history])
return (status, resp.text if status == "ok" else None)
return status, resp.text if status == "ok" else None
def fetch_store_page(self, appid: str) -> Optional[str]:
"""GET full store page HTML. Single request for tags + languages + DLC prices.
+2 -2
View File
@@ -142,11 +142,11 @@ def review_summary(item: Optional[dict]) -> Optional[tuple[int, int, str]]:
if count < 0:
return None
if count == 0:
return (0, 0, "")
return 0, 0, ""
pct = _int(summary.get("percent_positive"))
if not 0 <= pct <= 100:
return None
return (count, pct, str(summary.get("review_score_label") or "").strip())
return count, pct, str(summary.get("review_score_label") or "").strip()
# Why Steam's store says a game may no longer belong in the catalogue
-1
View File
@@ -28,7 +28,6 @@ next pipeline run — or until you pass --apply, which rewrites data/ now.
python scripts/edit_game.py --check # validate them all (CI-friendly)
"""
import argparse
import json
import os
import sys
+1 -1
View File
@@ -52,7 +52,7 @@ def parse_players(s) -> int:
return 0
if isinstance(s, (int, float)):
return int(s)
digits = re.sub(r"[^\d]", "", str(s))
digits = re.sub(r"\D", "", str(s))
return int(digits) if digits else 0
+7 -6
View File
@@ -40,6 +40,7 @@ import os
import sys
import time
from collections import Counter
from collections.abc import Callable
from typing import Optional
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
@@ -82,7 +83,7 @@ def screen(games: list[dict], items: dict, failed: set, blocked: set) -> list[tu
def confirm(candidates: list[tuple[dict, str]], client, deadline: Optional[Deadline] = None,
log=print) -> tuple[list, Counter]:
log: Callable[[str], None] = print) -> tuple[list, Counter]:
"""Ask appdetails about each flagged game. Returns ([(game, HealthResult)]
to remove, tally). An unavailable answer is asked again RECHECK_AFTER
seconds after the first ask; past the deadline nothing more is asked and
@@ -92,12 +93,12 @@ def confirm(candidates: list[tuple[dict, str]], client, deadline: Optional[Deadl
tally: Counter = Counter()
first_ask = None
def judge(game: dict, result) -> None:
if result.should_remove:
removals.append((game, result))
elif result.is_healthy:
def judge(candidate: dict, health) -> None:
if health.should_remove:
removals.append((candidate, health))
elif health.is_healthy:
tally["kept"] += 1
log(f" ✓ kept {result.appid} {result.name[:40]}: appdetails says it is healthy")
log(f" ✓ kept {health.appid} {health.name[:40]}: appdetails says it is healthy")
else:
tally["network"] += 1
+3 -1
View File
@@ -40,6 +40,7 @@ import argparse
import os
import sys
from collections import Counter
from collections.abc import Callable
from typing import Optional
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
@@ -57,7 +58,8 @@ def _kernel(value) -> str:
return {True: "kernel", False: "not kernel"}.get(value, "kernel unknown")
def sweep(targets: list[dict], client, guard, log=print) -> tuple[Counter, list[str]]:
def sweep(targets: list[dict], client, guard,
log: Callable[[str], None] = print) -> tuple[Counter, list[str]]:
"""Apply Steam's disclosures to `targets` in place. Returns a tally -
disclosed, none, unknown, pages, filled, replaced, updated, unnamed - and
the unnamed games, as "appid name"."""
+2 -1
View File
@@ -41,6 +41,7 @@ import argparse
import os
import sys
from collections import Counter
from collections.abc import Callable
from typing import Optional
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
@@ -63,7 +64,7 @@ def raise_from_samples(games: list[dict]) -> int:
return sum(1 for g in games if raise_peak(g, observed_peak(g)))
def raise_from_steamcharts(targets: list[dict], client, log=print,
def raise_from_steamcharts(targets: list[dict], client, log: Callable[[str], None] = print,
deadline: Optional[Deadline] = None) -> Counter:
"""Step 2. Returns a tally of the outcomes: "raised", "unchanged",
"untracked", "error", and "skipped" for games never asked because the run
+1 -1
View File
@@ -44,7 +44,7 @@ _STAR_THRESHOLDS = [(95, "★★★★★"), (80, "★★★★☆"), (70, "★
def _stars(r):
try: p = int(r.split("%")[0])
except: return "—"
except (AttributeError, TypeError, ValueError): return "—"
for thresh, s in _STAR_THRESHOLDS:
if p >= thresh: return s
return "★☆☆☆☆"
+1 -1
View File
@@ -33,7 +33,7 @@ _STAR_THRESHOLDS = [(95,"★★★★★"),(80,"★★★★☆"),(70,"★★★
def _stars(r):
try: p = int(r.split("%")[0])
except: return "—"
except (AttributeError, TypeError, ValueError): return "—"
for thresh, s in _STAR_THRESHOLDS:
if p >= thresh: return s
return "★☆☆☆☆"
+3 -3
View File
@@ -136,12 +136,12 @@ def refresh(games: list[dict], client, deadline: Optional[Deadline] = None,
else:
record(game, value, now, tally)
def ask(game: dict) -> None:
summary = client.fetch_reviews(extract_appid(game["link"]))
def ask(queued: dict) -> None:
summary = client.fetch_reviews(extract_appid(queued["link"]))
if summary is None:
tally["ask_failed"] += 1
else:
record(game, reviews_from_summary(summary), now, tally)
record(queued, reviews_from_summary(summary), now, tally)
asks = daily_order(asks, day_number() if day is None else day)
done = process_batch(asks[:ASK_CAP], ask, "Reviews from appreviews", deadline=deadline) if asks else 0
+6 -6
View File
@@ -149,7 +149,7 @@ export function seed(sqlite: SqliteD1, repo: FakeRepo, records: Rec[], now: Date
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
);
const sha = (k: number) => createFakeSha(k);
job.run("job-1", "approve", "committed", "scripts/temp_info.jsonl", sha(1), null, reviewer, iso(1 * HOUR), iso(1 * HOUR));
job.run("job-1", "approve", "committed", "scripts/temp_info.jsonl", sha(1), null, reviewer, iso(HOUR), iso(HOUR));
job.run("job-2", "approve", "committed", "scripts/temp_info.jsonl", null, "nothing to commit: every link was already queued", reviewer, iso(3 * HOUR), iso(3 * HOUR));
job.run("job-3", "override", "committed", "data/overrides/730.json", sha(3), null, reviewer, iso(8 * HOUR), iso(8 * HOUR));
job.run("job-4", "approve", "failed", "scripts/temp_info.jsonl", null, "graphql HTTP 502", reviewer, iso(26 * HOUR), iso(26 * HOUR));
@@ -200,8 +200,8 @@ export function seed(sqlite: SqliteD1, repo: FakeRepo, records: Rec[], now: Date
state.run(`auto.approve.count:${now.toISOString().slice(0, 10)}`, "25", iso(3 * HOUR));
state.run(
"auto.approve.last",
JSON.stringify({ at: iso(1 * HOUR), outcome: "skipped", detail: "pipeline busy: Update Reviews is in_progress" }),
iso(1 * HOUR),
JSON.stringify({ at: iso(HOUR), outcome: "skipped", detail: "pipeline busy: Update Reviews is in_progress" }),
iso(HOUR),
);
job.run("job-7", "auto.approve", "committed", "scripts/temp_info.jsonl", sha(7), null, "auto-approve", iso(3 * HOUR), iso(3 * HOUR));
audit.run(reviewer, "automation.settings", null, JSON.stringify({ before: { ...settings, dailyLimit: 300 }, after: settings }), iso(10 * HOUR));
@@ -214,7 +214,7 @@ export function seed(sqlite: SqliteD1, repo: FakeRepo, records: Rec[], now: Date
const removedDone = hide(committed[2]);
const entries = [
makeEntry(appidOf(removedDone), removedDone.name ?? "", "not_a_game", "a soundtrack", iso(60 * HOUR).replace(/\.\d{3}Z$/, "Z")),
makeEntry(appidOf(removedNow), removedNow.name ?? "", "duplicate", "", iso(1 * HOUR).replace(/\.\d{3}Z$/, "Z")),
makeEntry(appidOf(removedNow), removedNow.name ?? "", "duplicate", "", iso(HOUR).replace(/\.\d{3}Z$/, "Z")),
];
repo.files.set("data/blocklist.jsonl", appendEntries("", entries));
for (const e of entries) {
@@ -224,8 +224,8 @@ export function seed(sqlite: SqliteD1, repo: FakeRepo, records: Rec[], now: Date
);
decide.run(e.appid, "rejected", `removed:${e.reason}${e.note ? ` - ${e.note}` : ""}`, reviewer, e.blocked_at);
}
job.run("job-8", "remove", "committed", "data/blocklist.jsonl", sha(8), null, reviewer, iso(1 * HOUR), iso(1 * HOUR));
audit.run(reviewer, "remove", "job-8", JSON.stringify({ appids: [entries[1].appid], reason: "duplicate" }), iso(1 * HOUR));
job.run("job-8", "remove", "committed", "data/blocklist.jsonl", sha(8), null, reviewer, iso(HOUR), iso(HOUR));
audit.run(reviewer, "remove", "job-8", JSON.stringify({ appids: [entries[1].appid], reason: "duplicate" }), iso(HOUR));
return { hidden };
}
+1 -2
View File
@@ -44,6 +44,5 @@ export function shouldIgnore(e: Pick<KeyboardEvent, "isComposing" | "keyCode" |
if (field.tagName !== "INPUT") return true;
if (!KEYLESS_INPUTS.has((field.getAttribute("type") ?? "text").toLowerCase())) return true;
}
if (typeof document !== "undefined" && document.querySelector("dialog[open]")) return true;
return false;
return typeof document !== "undefined" && document.querySelector("dialog[open]") !== null;
}
+1 -1
View File
@@ -261,7 +261,7 @@
Reopen
</Button>
{:else}
<Button variant="outline" onclick={() => ((confirming = true), (reopenError = null))}>
<Button variant="outline" onclick={() => { confirming = true; reopenError = null; }}>
<RotateCcw class="size-4" /> Reopen…
</Button>
{/if}
-1
View File
@@ -940,7 +940,6 @@ dependencies = [
name = "f2p-tracker"
version = "2.5.1"
dependencies = [
"serde",
"serde_json",
"tauri",
"tauri-build",
+3 -1
View File
@@ -31,8 +31,10 @@ strip = true
tauri-build = { version = "2", features = [] }
[dependencies]
# Not used by src/ itself but by the code tauri::generate_context!() expands
# (::serde_json::Value for the plugins' configuration): without it the crate
# does not compile, whatever an unused-dependency check says.
serde_json = "1"
serde = { version = "1", features = ["derive"] }
tauri = { version = "2", features = [] }
tauri-plugin-shell = "2"
+3 -3
View File
@@ -40,9 +40,9 @@ export class Resource<T> {
error = $state<Error | undefined>(undefined);
loading = $state(false);
#fetcher: (signal: AbortSignal) => Promise<T>;
#staleTime: number;
#enabled: () => boolean;
readonly #fetcher: (signal: AbortSignal) => Promise<T>;
readonly #staleTime: number;
readonly #enabled: () => boolean;
#loadedAt = 0;
#inFlight: Promise<void> | null = null;
#controller: AbortController | null = null;
+5 -1
View File
@@ -72,7 +72,11 @@ export async function handlePipelineApi(
// One entry per run: the page keys its lists on the run URL, and a duplicate
// key in a keyed {#each} throws (CLAUDE.md).
const seen = new Set<string>();
const all = [...runs, ...extraRuns].filter((r) => !seen.has(r.html_url) && (seen.add(r.html_url), true));
const all = [...runs, ...extraRuns].filter((r) => {
if (seen.has(r.html_url)) return false;
seen.add(r.html_url);
return true;
});
let queue: { tempInfo: number | null; blocklist: number | null } = { tempInfo: null, blocklist: null };
try {