diff --git a/docs/launcher.md b/docs/launcher.md index 238983db8..995d80b81 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -34,7 +34,12 @@ Standard library only (`tools/leonida_launcher.py`). first), duplicate a container under a new name, delete (the folder is moved to `save-backups\deleted`, not erased), export and import a single blob, and a read-only hex and strings viewer. All of them are refused while the game is running. -- **Tools**: fetch NVIDIA's DLSS files (`d3d12\Get-NVIDIA-DLSS.cmd`, after a confirmation: about 70 MB from NVIDIA's +- **Updates**: at start (unless **Check for updates at start** is off in Settings) the launcher runs `git fetch` in + its own folder and, when the clone is behind the branch it follows, says how many new commits there are on the + Play page with an **Update** button. Update runs `git pull --ff-only` (it stops, changing nothing, if local + changes or another branch are in the way), then rebuilds the runtime when `d3d12/` changed. A copy downloaded as + a zip has no `.git`: the launcher says so, and updating means a `git clone` of the repository instead. +- **Tools**: update Leonida (as above), fetch NVIDIA's DLSS files (`d3d12\Get-NVIDIA-DLSS.cmd`, after a confirmation: about 70 MB from NVIDIA's GitHub), rebuild the runtime (`d3d12\scripts\build-nvidia.ps1`), open the logs folder (`%LOCALAPPDATA%\Leonida\logs`) and the screenshots folder. The two scripts are Windows only. - **About**: what the port is, that it runs your own copy, the credits (see `d3d12/README.md`) and the licence. diff --git a/tests/test_leonida_launcher.py b/tests/test_leonida_launcher.py index 82c4d5d8b..1cbd9a5ee 100644 --- a/tests/test_leonida_launcher.py +++ b/tests/test_leonida_launcher.py @@ -178,5 +178,79 @@ class ModsAndPicturesTests(unittest.TestCase): self.assertIsNone(launcher.newest_picture([os.path.join(tmp, "none")])) +class FakeGit: + """`git -C repo ` answered from a table of the first argument; records each call.""" + + def __init__(self, answers): + self.answers = answers + self.calls = [] + + def __call__(self, repo, *args, timeout=60): + self.calls.append(args) + code, out = self.answers.get(args[0], (0, "")) + if callable(out): + out = out(args) + return launcher.subprocess.CompletedProcess(["git", *args], code, out, "") + + +class UpdateTests(unittest.TestCase): + def repo(self, tmp, git=True): + if git: + os.mkdir(os.path.join(tmp, ".git")) + return tmp + + def test_a_zip_copy_is_told_to_clone(self): + with tempfile.TemporaryDirectory() as tmp: + status = launcher.update_status(self.repo(tmp, git=False), FakeGit({})) + self.assertEqual(status["kind"], "zip") + self.assertIn("git clone", launcher.update_note(status)) + + def test_behind_counts_the_new_commits_after_a_fetch(self): + git = FakeGit({"rev-list": (0, "3\n")}) + with tempfile.TemporaryDirectory() as tmp: + status = launcher.update_status(self.repo(tmp), git) + self.assertEqual((status["kind"], status["behind"]), ("behind", 3)) + self.assertIn(("fetch", "--quiet"), git.calls) + self.assertIn("3 new commits", launcher.update_note(status)) + self.assertEqual(launcher.update_note({"kind": "current", "behind": 0}), "") + + def test_a_failed_fetch_or_no_upstream_is_said_not_raised(self): + with tempfile.TemporaryDirectory() as tmp: + repo = self.repo(tmp) + self.assertEqual(launcher.update_status(repo, FakeGit({"rev-parse": (128, "")}))["kind"], "noupstream") + failed = launcher.update_status(repo, FakeGit({"fetch": (128, "no network")})) + self.assertEqual(failed["kind"], "error") + self.assertIn("no network", launcher.update_note(failed)) + + def test_update_rebuilds_only_when_d3d12_moved(self): + heads = iter(["aaa", "bbb", "aaa", "bbb"]) + for d3d12_changed in (False, True): + built = [] + git = FakeGit({"rev-list": (0, "2"), "rev-parse": (0, lambda a: "origin/main" if "@{u}" in a else next(heads)), + "diff": (1 if d3d12_changed else 0, "")}) + with tempfile.TemporaryDirectory() as tmp: + code = launcher.run_update(self.repo(tmp), git, build=lambda: built.append(1) or 0, windows=True) + self.assertEqual(code, 0) + self.assertIn(("pull", "--ff-only"), git.calls) + self.assertEqual(built, [1] if d3d12_changed else []) + + def test_a_pull_that_cannot_fast_forward_stops_without_a_build(self): + built = [] + git = FakeGit({"rev-list": (0, "1"), "pull": (128, "Not possible to fast-forward")}) + with tempfile.TemporaryDirectory() as tmp: + code = launcher.run_update(self.repo(tmp), git, build=lambda: built.append(1) or 0, windows=True) + self.assertNotEqual(code, 0) + self.assertEqual(built, []) + + def test_the_update_command_is_this_file_in_isolated_mode(self): + command = launcher.update_command("C:/mandy") + self.assertEqual(command[1:2] + command[3:], ["-I", "--update", "C:/mandy"]) + self.assertTrue(command[2].endswith("leonida_launcher.py")) + + def test_the_check_can_be_turned_off(self): + self.assertTrue(launcher.DEFAULTS["check_updates"]) + self.assertFalse(launcher.normalise({"check_updates": False})["check_updates"]) + + if __name__ == "__main__": unittest.main() diff --git a/tools/leonida_launcher.py b/tools/leonida_launcher.py index 7937fad4d..8220f98cd 100644 --- a/tools/leonida_launcher.py +++ b/tools/leonida_launcher.py @@ -60,6 +60,7 @@ DEFAULTS: dict = { "present_scale": "", # -PresentScale, with -Aspect; empty = the script's default (fit) "adapter": "", # -Adapter "background": "", # the picture behind PLAY in launcher/; "" = background.* in config_dir() + "check_updates": True, # at start: is the clone behind its upstream (git fetch) } # The options with a fixed set of values, and the others whose text has to match a pattern. CHOICES: dict = {"resolution": RESOLUTIONS, "dlss_mode": DLSS_MODES, "frame_gen": FRAME_GEN, @@ -210,6 +211,95 @@ def state_for_line(state: str, line: str) -> str: return state +# ---------------------------------------------------------------- updates + +def _git(repo: str, *args: str, timeout: float = 60) -> subprocess.CompletedProcess: + kwargs: dict = {} + if WINDOWS: + kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW + return subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True, timeout=timeout, + stdin=subprocess.DEVNULL, check=False, **kwargs) + + +def update_status(repo: str = REPO, git=_git, fetch: bool = True) -> dict: + """Whether this copy can be updated and how far behind it is. + + `kind` is "zip" (no .git: downloaded as an archive), "nogit" (git is not installed), "noupstream" (the branch + follows nothing), "error" (the fetch failed, `detail` says why), "behind" (`behind` new commits upstream) or + "current". `git` runs `git -C repo ` and returns a CompletedProcess (replaced in the tests). + """ + if not os.path.exists(os.path.join(repo, ".git")): + return {"kind": "zip", "behind": 0} + try: + if git(repo, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}").returncode != 0: + return {"kind": "noupstream", "behind": 0} + if fetch: + done = git(repo, "fetch", "--quiet") + if done.returncode != 0: + return {"kind": "error", "behind": 0, "detail": (done.stderr or done.stdout).strip()[:300]} + count = git(repo, "rev-list", "--count", "HEAD..@{u}") + except FileNotFoundError: + return {"kind": "nogit", "behind": 0} + except subprocess.TimeoutExpired: + return {"kind": "error", "behind": 0, "detail": "git took too long"} + if count.returncode != 0 or not count.stdout.strip().isdigit(): + return {"kind": "error", "behind": 0, "detail": (count.stderr or count.stdout).strip()[:300]} + behind = int(count.stdout.strip()) + return {"kind": "behind" if behind else "current", "behind": behind} + + +def update_note(status: dict) -> str: + """The line the launcher shows for an update status ("" when there is nothing to say).""" + kind = status.get("kind") + if kind == "behind": + n = status["behind"] + return f"Update available: {n} new commit{'s' if n != 1 else ''}. Tools > Update Leonida, or the button above." + if kind == "zip": + return "This copy was downloaded as a zip: to update from the launcher, use a git clone (docs/launcher.md)." + if kind == "nogit": + return "Git is not installed: the launcher cannot check for updates." + if kind == "error": + return "Could not check for updates: " + (status.get("detail") or "git failed") + return "" + + +def update_command(repo: str = REPO) -> list[str]: + """The Update button's command: this file's own --update (git pull --ff-only, then a rebuild if d3d12/ moved), + so its output streams into the launcher like the other tools.""" + return [sys.executable, "-I", os.path.abspath(__file__), "--update", repo] + + +def run_update(repo: str, git=_git, build=None, windows: bool = WINDOWS) -> int: + """`--update`: fast-forward the clone to its upstream, then rebuild the runtime when d3d12/ changed. Prints what + it does; returns the exit code. `build` runs the build (the tests replace it).""" + status = update_status(repo, git) + if status["kind"] not in ("behind", "current"): + print(update_note(status) or f"Cannot update ({status['kind']}).", flush=True) + return 1 + before = git(repo, "rev-parse", "HEAD").stdout.strip() + if status["kind"] == "current": + print("Already up to date.", flush=True) + return 0 + print(f"Updating: {status['behind']} new commit(s) ...", flush=True) + pulled = git(repo, "pull", "--ff-only", timeout=600) + print((pulled.stdout + pulled.stderr).strip(), flush=True) + if pulled.returncode != 0: + print("The update stopped: git could not fast-forward (local changes or another branch?). " + "Nothing was changed.", flush=True) + return pulled.returncode + after = git(repo, "rev-parse", "HEAD").stdout.strip() + if git(repo, "diff", "--quiet", before, after, "--", "d3d12").returncode == 0: + print("Updated. The runtime did not change: no rebuild needed.", flush=True) + return 0 + if not windows: + print("Updated. d3d12/ changed: rebuild the runtime (docs/linux.md).", flush=True) + return 0 + print("Updated. d3d12/ changed: rebuilding the runtime (a few minutes) ...", flush=True) + if build is None: + build = lambda: subprocess.call(tool_command("build", repo)) + return build() + + # ---------------------------------------------------------------- folders def local_data_dir() -> str: @@ -417,6 +507,8 @@ def run_gui() -> int: self.build_about() self.show("Play") self.pump() + if self.settings["check_updates"]: + self.check_updates() # ---- look def style(self): @@ -502,6 +594,11 @@ def run_gui() -> int: anchor="w").pack(side="left", padx=18, pady=9) self.hint_var = tk.StringVar() tk.Label(bar, textvariable=self.hint_var, bg=PANEL, fg=MUTED, anchor="e").pack(side="right", padx=18) + # What the update check found (update_note); the button shows only when the clone is behind. + self.update_var = tk.StringVar() + self.update_button = ttk.Button(bar, text="Update", command=self.update) + tk.Label(bar, textvariable=self.update_var, bg=PANEL, fg=ACCENT, anchor="w", + wraplength=520, justify="left").pack(side="left", padx=(0, 8)) box = tk.Frame(page, bg=BG) box.grid(row=1, column=0, sticky="nsew", padx=24, pady=(16, 12)) box.columnconfigure(0, weight=1) @@ -614,6 +711,9 @@ def run_gui() -> int: try: while True: kind, process, value = self.lines.get_nowait() + if kind == "update": + self.show_update(value) + continue if process is not self.process: continue if kind == "line": @@ -623,6 +723,8 @@ def run_gui() -> int: else: self.append(f"\nExited with code {value}.\n") self.set_state(f"Exited with code {value}") + if self.what == "the update": + self.check_updates(fetch=False) self.process = None self.play_button.state(["!disabled"]) self.hero.itemconfigure(self.hero_window, window=self.play_button) @@ -632,6 +734,30 @@ def run_gui() -> int: pass self.root.after(100, self.pump) + # ---- updates + def check_updates(self, fetch=True): + def work(): + try: + status = update_status(REPO, fetch=fetch) + except Exception as exc: # a broken git must not take the launcher down + status = {"kind": "error", "behind": 0, "detail": str(exc)[:300]} + self.lines.put(("update", None, status)) + threading.Thread(target=work, daemon=True).start() + + def show_update(self, status): + self.update_var.set(update_note(status)) + if status.get("kind") == "behind": + self.update_button.pack(side="left", padx=(0, 12), pady=5) + else: + self.update_button.pack_forget() + + def update(self): + if not messagebox.askokcancel("Update Leonida", "This runs git pull in the launcher's folder, then " + "rebuilds the runtime if it changed (a few minutes).\n\nContinue?"): + return + self.show("Play") + self.run(update_command(), "the update", "Updating") + def stop(self): if self.process is None: return @@ -687,7 +813,8 @@ def run_gui() -> int: ("quality", "Quality (-Quality, slower)"), ("capture", "Capture: F9 saves a frame (-Capture)"), ("log", "Log to a file (-Log)"), - ("precompile_all", "Precompile every pipeline (-PrecompileAll, very long the first time)")) + ("precompile_all", "Precompile every pipeline (-PrecompileAll, very long the first time)"), + ("check_updates", "Check for updates at start (git fetch)")) for index, (key, text) in enumerate(checks): var = tk.BooleanVar(value=self.settings[key]) self.vars[key] = var @@ -1021,7 +1148,8 @@ def run_gui() -> int: inner.grid(row=0, column=0, sticky="nsew") ttk.Label(inner, text="Tools", font=("Segoe UI", 20, "bold")).grid(row=0, column=0, columnspan=2, sticky="w", pady=(0, 10)) - items = (("Fetch NVIDIA DLSS files", "Downloads about 70 MB from NVIDIA's GitHub, once.", + items = (("Update Leonida", "git pull, then a rebuild if the runtime changed.", self.update), + ("Fetch NVIDIA DLSS files", "Downloads about 70 MB from NVIDIA's GitHub, once.", self.fetch_dlss), ("Rebuild the runtime", "d3d12\\scripts\\build-nvidia.ps1 (a few minutes).", self.rebuild), ("Open the logs folder", logs_dir(), lambda: self.open(logs_dir())), @@ -1076,6 +1204,8 @@ def run_gui() -> int: def main() -> int: + if len(sys.argv) >= 2 and sys.argv[1] == "--update": + return run_update(sys.argv[2] if len(sys.argv) > 2 else REPO) return run_gui()