okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c924d3c9d
main
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.""" 29return (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).""" 36environ = os .environ if environ is None else environ 37if environ .get ("STRATA_COMPONENTS_DIR" ): 38return Path (environ ["STRATA_COMPONENTS_DIR" ]) 39home = Path .home () 40if os .name == "nt" : 41return Path (environ .get ("LOCALAPPDATA" )or str (home / "AppData" / "Local" ))/ "Strata" / "components" 42return Path (environ .get ("XDG_DATA_HOME" )or str (home / ".local" / "share" ))/ "strata" / "components" 43 44 45def version_key (text )-> tuple [int , ...]| None : 46if not isinstance (text ,str )or not _VERSION .fullmatch (text .strip ()): 47return None 48base ,dash ,_pre = text .strip ().partition ("-" ) 49parts = [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 51return 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").""" 56order = {"alpha" :0 ,"a" :0 ,"beta" :1 ,"b" :1 ,"rc" :2 } 57m = re .match (r"([A-Za-z]*)\.?([0-9]*)" ,pre ) 58word ,number = (m .group (1 ).lower (),int (m .group (2 )or 0 ))if m else ("" ,0 ) 59return (order .get (word ,3 ),number ) 60 61 62def _read_json (path :Path ): 63return json .loads (path .read_text (encoding = "utf-8-sig" )) 64 65 66def bundled_python (folder :Path )-> Path : 67return 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).""" 73root = components_dir (environ )if root is None else Path (root ) 74base = root / "control" 75try : 76pointer = _read_json (base / "active.json" ) 77except (OSError ,ValueError ): 78return None ,None ,None 79if not isinstance (pointer ,dict ): 80return None ,None ,None 81name = pointer .get ("folder" ) 82if not isinstance (name ,str )or not _FOLDER .fullmatch (name )or name in ("." ,".." ): 83return None ,None ,"its pointer names a folder outside the control folder" 84folder = base / name 85try : 86if folder .resolve ().parent != base .resolve (): 87return None ,None ,"its pointer names a folder outside the control folder" 88except OSError : 89return None ,None ,None 90# the version that counts is the one in the folder; the pointer's claim is only a fallback 91version = None 92for source in ("VERSION" ,"BUNDLE.json" ): 93try : 94if source == "VERSION" : 95version = (folder / source ).read_text (encoding = "utf-8-sig" ).strip () 96else : 97version = _read_json (folder / source ).get ("version" ) 98except (OSError ,ValueError ,AttributeError ): 99continue 100if version_key (version ): 101break 102version = None 103if version is None : 104version = pointer .get ("version" ) 105have ,want = version_key (running ),version_key (version ) 106if have is None : 107return None ,None ,None # this Control has no readable version (a development tree): nothing to compare 108if want is None : 109return (None ,None ,f"its version ( { version !r } ) cannot be read" )if version else (None ,None ,None ) 110if want <= have : 111return None ,None ,None # never an older or equal Control 112if not (bundled_python (folder ).is_file ()and (folder / "strata.py" ).is_file ()and (folder / "strata_control" ).is_dir ()): 113return None ,version ,f" { folder } is missing its interpreter or entry point" 114return folder ,version ,None 115 116 117def _child_env (environ )-> dict : 118env = dict (environ ) 119env [ENV_GUARD ]= "1" 120env ["PYTHONNOUSERSITE" ]= "1" 121env .pop ("PYTHONHOME" ,None ) 122env .pop ("PYTHONPATH" ,None ) 123return 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).""" 129environ = os .environ if environ is None else environ 130if environ .get (ENV_GUARD )or environ .get (ENV_OFF ): 131return None 132if root is None and not environ .get (ENV_CHECKOUT )and running_from_checkout (): 133return None # a source checkout runs its own code, never an installed Control 134if running is None : 135import strata_cli 136running = strata_cli .version () 137warn = warn or (lambda text :sys .stderr .write (text + "\n" )) 138try : 139folder ,version ,problem = find_target (running ,environ ,root ) 140except Exception :# noqa: BLE001 - a hand-over must never be the thing that breaks the CLI 141return None 142if problem : 143what = f"Control { version } " if version else "Control" 144warn (f"strata: a newer { what } was installed but { problem } ; running { running } instead. Run `strata update` again to repair it." ) 145return None 146if folder is None : 147return None 148python ,entry = str (bundled_python (folder )),str (folder / "strata.py" ) 149command = [python ,entry ,* argv ] 150env = _child_env (environ ) 151if os .name != "nt" : 152try : 153 (execv or os .execve )(python ,command ,env ) 154except OSError as exc : 155warn (f"strata: could not start the updated Control { version } ( { exc . strerror or exc } ); running { running } instead." ) 156return None 157try : 158return (run or subprocess .call )(command ,env = env ,cwd = os .getcwd ()) 159except KeyboardInterrupt : 160return 130 161except OSError as exc : 162warn (f"strata: could not start the updated Control { version } ( { exc . strerror or exc } ); running { running } instead." ) 163return 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 176launcher 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 178way 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 179Control and shows the sentence instead of 'updated'. Returns the exit code to use, or None for any other start.""" 180environ = os .environ if environ is None else environ 181if list (argv )!= ["--version" ]or environ .get ("STRATA_NO_ACQUIRE" )!= "1" or environ .get (ENV_GUARD ): 182return None 183tree = Path (__file__ ).resolve ().parents [1 ]if tree is None else Path (tree ) 184if tree .parent .name != _STAGE_FOLDER : 185return None 186sys .stdout .write (OLD_LAUNCHER_TEXT + "\n" ) 187return OLD_LAUNCHER_EXIT