okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221An old Terminal that cannot hand over to a new Control is told to run the install command once more (TUI stress #4, H03)c924d3c9d

main
9.2 KiB187 linesraw
1"""Hand the Terminal over to a newer Control that `strata update` installed.
2
3`strata update` stages a newer Control in ``<components>/control/<ver>/`` and writes ``<components>/control/active.json``. The
4desktop app follows that pointer; the Terminal on PATH is a different install, so without this it kept running the old one.
5`maybe_hand_over` runs at the very start of ``strata.py``, before any heavy import, and (only when that Control is newer and whole)
6runs the same command line with the newer Control's own interpreter and entry point.
7
8Rules: standard library only; never an older or equal target; never a pointer that leaves the control folder; never a loop
9(``STRATA_HANDOVER`` marks a process that was already handed over); a broken target costs one warning line and the current
10Control keeps running. ``STRATA_NO_HANDOVER=1`` turns it off.
11"""
12
13from __future__ import annotations
14
15import json
16import os
17import re
18import subprocess
19import sys
20from pathlib import Path
21
22ENV_GUARD = "STRATA_HANDOVER"
23ENV_OFF = "STRATA_NO_HANDOVER"
24ENV_CHECKOUT = "STRATA_HANDOVER_IN_CHECKOUT"         # tests only: allow a hand-over from a source checkout
25
26
27def running_from_checkout() -> bool:
28    """True when this Terminal runs from a git checkout (the source route) rather than an installed bundle."""
29    return (Path(__file__).resolve().parents[1] / ".git").exists()
30_FOLDER = re.compile(r"^[\w.+-]+$")
31_VERSION = re.compile(r"^[0-9]+(\.[0-9]+){1,3}(-[0-9A-Za-z][0-9A-Za-z.]*)?$")     # 0.2.2, or a pre-release such as 0.2.2-rc1
32
33
34def components_dir(environ=None) -> Path:
35    """The per-user component folder (same rule as strata_control/engine_component.py components_dir)."""
36    environ = os.environ if environ is None else environ
37    if environ.get("STRATA_COMPONENTS_DIR"):
38        return Path(environ["STRATA_COMPONENTS_DIR"])
39    home = Path.home()
40    if os.name == "nt":
41        return Path(environ.get("LOCALAPPDATA") or str(home / "AppData" / "Local")) / "Strata" / "components"
42    return Path(environ.get("XDG_DATA_HOME") or str(home / ".local" / "share")) / "strata" / "components"
43
44
45def version_key(text) -> tuple[int, ...] | None:
46    if not isinstance(text, str) or not _VERSION.fullmatch(text.strip()):
47        return None
48    base, dash, _pre = text.strip().partition("-")
49    parts = [int(p) for p in base.split(".")]
50    # a pre-release sorts below the same number without the suffix (0.2.2-rc1 < 0.2.2); two pre-releases of one number compare by name
51    return tuple(parts + [0] * (4 - len(parts))) + ((0, _pre_rank(_pre)) if dash else (1, ()))
52
53
54def _pre_rank(pre: str) -> tuple:
55    """alpha < beta < rc < anything else, then the number inside ("rc2" > "rc1")."""
56    order = {"alpha": 0, "a": 0, "beta": 1, "b": 1, "rc": 2}
57    m = re.match(r"([A-Za-z]*)\.?([0-9]*)", pre)
58    word, number = (m.group(1).lower(), int(m.group(2) or 0)) if m else ("", 0)
59    return (order.get(word, 3), number)
60
61
62def _read_json(path: Path):
63    return json.loads(path.read_text(encoding="utf-8-sig"))
64
65
66def bundled_python(folder: Path) -> Path:
67    return folder / "python" / "python.exe" if os.name == "nt" else folder / "python" / "bin" / "python3"
68
69
70def find_target(running: str, environ=None, root: Path | None = None):
71    """(folder, version, problem). folder is a newer, whole Control; or None with problem None (nothing to do) or a reason
72    (a newer Control is named but cannot be used)."""
73    root = components_dir(environ) if root is None else Path(root)
74    base = root / "control"
75    try:
76        pointer = _read_json(base / "active.json")
77    except (OSError, ValueError):
78        return None, None, None
79    if not isinstance(pointer, dict):
80        return None, None, None
81    name = pointer.get("folder")
82    if not isinstance(name, str) or not _FOLDER.fullmatch(name) or name in (".", ".."):
83        return None, None, "its pointer names a folder outside the control folder"
84    folder = base / name
85    try:
86        if folder.resolve().parent != base.resolve():
87            return None, None, "its pointer names a folder outside the control folder"
88    except OSError:
89        return None, None, None
90    # the version that counts is the one in the folder; the pointer's claim is only a fallback
91    version = None
92    for source in ("VERSION", "BUNDLE.json"):
93        try:
94            if source == "VERSION":
95                version = (folder / source).read_text(encoding="utf-8-sig").strip()
96            else:
97                version = _read_json(folder / source).get("version")
98        except (OSError, ValueError, AttributeError):
99            continue
100        if version_key(version):
101            break
102        version = None
103    if version is None:
104        version = pointer.get("version")
105    have, want = version_key(running), version_key(version)
106    if have is None:
107        return None, None, None                          # this Control has no readable version (a development tree): nothing to compare
108    if want is None:
109        return (None, None, f"its version ({version!r}) cannot be read") if version else (None, None, None)
110    if want <= have:
111        return None, None, None                          # never an older or equal Control
112    if not (bundled_python(folder).is_file() and (folder / "strata.py").is_file() and (folder / "strata_control").is_dir()):
113        return None, version, f"{folder} is missing its interpreter or entry point"
114    return folder, version, None
115
116
117def _child_env(environ) -> dict:
118    env = dict(environ)
119    env[ENV_GUARD] = "1"
120    env["PYTHONNOUSERSITE"] = "1"
121    env.pop("PYTHONHOME", None)
122    env.pop("PYTHONPATH", None)
123    return env
124
125
126def maybe_hand_over(argv, environ=None, root=None, running=None, execv=None, run=None, warn=None) -> int | None:
127    """Returns None to carry on with the current Control, or an exit code when a newer Control already ran this command
128    (Windows; on POSIX the process is replaced and this does not return)."""
129    environ = os.environ if environ is None else environ
130    if environ.get(ENV_GUARD) or environ.get(ENV_OFF):
131        return None
132    if root is None and not environ.get(ENV_CHECKOUT) and running_from_checkout():
133        return None                                      # a source checkout runs its own code, never an installed Control
134    if running is None:
135        import strata_cli
136        running = strata_cli.version()
137    warn = warn or (lambda text: sys.stderr.write(text + "\n"))
138    try:
139        folder, version, problem = find_target(running, environ, root)
140    except Exception:                                    # noqa: BLE001 - a hand-over must never be the thing that breaks the CLI
141        return None
142    if problem:
143        what = f"Control {version}" if version else "Control"
144        warn(f"strata: a newer {what} was installed but {problem}; running {running} instead. Run `strata update` again to repair it.")
145        return None
146    if folder is None:
147        return None
148    python, entry = str(bundled_python(folder)), str(folder / "strata.py")
149    command = [python, entry, *argv]
150    env = _child_env(environ)
151    if os.name != "nt":
152        try:
153            (execv or os.execve)(python, command, env)
154        except OSError as exc:
155            warn(f"strata: could not start the updated Control {version} ({exc.strerror or exc}); running {running} instead.")
156        return None
157    try:
158        return (run or subprocess.call)(command, env=env, cwd=os.getcwd())
159    except KeyboardInterrupt:
160        return 130
161    except OSError as exc:
162        warn(f"strata: could not start the updated Control {version} ({exc.strerror or exc}); running {running} instead.")
163        return None
164
165
166#: What a Terminal older than 0.1.46.2 cannot do: its strata.py has no hand-over, so a Control it installs is never used. Its updater
167#: (which cannot be changed any more) test-starts the new Control with `--version` and prints the first 120 characters of the answer
168#: when that fails, so this is the sentence it shows. No quote marks in it: the old updater prints it as a Python string.
169OLD_LAUNCHER_TEXT = "This Terminal cannot switch to the new Control by itself. Run the Strata install command once more to update it."
170OLD_LAUNCHER_EXIT = 7
171_STAGE_FOLDER = ".s"                                 # strata_control.updater.STAGE_DIR: the folder a Control is test-started from
172
173
174def refuse_old_updater(argv, environ=None, tree=None) -> int | None:
175    """0.2.0-beta's Terminal (Control 0.1.45.3) and the other releases before 0.1.46.2 install a newer Control and report success, but their
176    launcher never switches to it (no hand-over code), so the update would change nothing. They test-start the staged Control with
177    `--version`, with STRATA_NO_ACQUIRE=1 and without STRATA_HANDOVER (every updater that can hand over sets it). This Control, started that
178    way from the updater's staging folder, says in one plain sentence what to do and exits non-zero, so the old updater keeps the old
179    Control and shows the sentence instead of 'updated'. Returns the exit code to use, or None for any other start."""
180    environ = os.environ if environ is None else environ
181    if list(argv) != ["--version"] or environ.get("STRATA_NO_ACQUIRE") != "1" or environ.get(ENV_GUARD):
182        return None
183    tree = Path(__file__).resolve().parents[1] if tree is None else Path(tree)
184    if tree.parent.name != _STAGE_FOLDER:
185        return None
186    sys.stdout.write(OLD_LAUNCHER_TEXT + "\n")
187    return OLD_LAUNCHER_EXIT