Released code takes plugins/platforms/<name>/ for a bundled platform only when the folder holds __init__.py and plugin.yaml, and loads <name>/gateway_env.py by path only after that. The list kept gateway_env.py for 16 platforms and nothing else, so after plugins moves the scan found no platform and never read those files. An updater that restarts paused gateways itself after the swap reads that scan to strip platform credentials from a served profile's environment (by the code: v0.22.7 and v0.23.0, and v0.23.1 on Windows). Measured with a v0.23.1 process whose checkout was swapped: 24 prefixes with no platform found, 60 with all 26. Each of the 26 platform folders now keeps a marker __init__.py (kind exists) and a byte copy of plugin.yaml (kind copy). The gateway_env.py rows become by-path, which is what a release does with them. An exists file used to be a forwarding shim. It is now a marker that raises ImportError naming the moved module. A gateway that started before the update and loads a platform late would otherwise get the moved adapter, which is not an instance of the adapter base class it holds; it now fails with a message that says to restart.
241 lines
11 KiB
Python
Executable File
241 lines
11 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Write the files that keep old module paths working for releases that update across a move.
|
|
|
|
For each name in ``hermes_agent/compat/required_names.py`` whose module has moved (longest dotted
|
|
prefix in ``hermes_agent/compat/moves.py``), write a file at the old path:
|
|
|
|
- a shim (kinds ``package``, ``module``, ``by-path``). Imported, it installs the compat finder and becomes the moved
|
|
module object. Loaded by path (``runpy.run_path``, ``spec_from_file_location``), it carries the
|
|
moved module's names. Run as a script or with ``-m``, it runs the moved module as ``__main__``.
|
|
When ``hermes_agent`` is not importable (a virtualenv that maps only the old top-level names) or
|
|
the file runs as a script, it first puts the repository root on ``sys.path``. When that forwarding
|
|
fails while Python locates a module under it for ``python -m`` (a killed update left
|
|
``hermes_agent`` torn or moved aside), it imports the root ``hermes_bootstrap``, which repairs the
|
|
tree and relaunches, then forwards once more; a healthy tree never imports the bootstrap. Its body
|
|
is one ``try`` statement, so a file cut short is a SyntaxError, never an empty module.
|
|
- a byte copy of the moved file (kind ``copy``), for a file a release runs without the application
|
|
on the path, or a data file it reads at the old path.
|
|
- a marker (kind ``exists``), for a file a release only checks for. Loading it raises ImportError that
|
|
names the moved module, so an old process fails there instead of running moved code as old code.
|
|
|
|
Nothing for kind ``hand``: that file is hand-written. Both modes report it while it is missing or
|
|
carries the shim header; only ``--check`` fails on it, since a chunk adds it after this script writes.
|
|
|
|
``.gitattributes`` marks every written file as generated. A moved file listed in
|
|
``[tool.hermes] update-startup-files`` at a path the tree lacks is reported in both modes, because an
|
|
updater refuses an update to a tree that lacks one; only ``--check`` fails on it, since the codemod
|
|
that fixes the list runs after this script writes. Git-ignored files (build output such as
|
|
``hermes_cli/web_dist``) are never strays.
|
|
|
|
python scripts/move/generate_shims.py # write files, delete stale shims
|
|
python scripts/move/generate_shims.py --check # exit 1 when the tree differs from what it would write
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import subprocess
|
|
import sys
|
|
import tomllib
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
from hermes_agent.compat.finder import current_name
|
|
from hermes_agent.compat.moves import MOVES
|
|
from hermes_agent.compat.required_names import REQUIRED_NAMES, REQUIRED_TEXT
|
|
|
|
HEADER = "# Generated by scripts/move/generate_shims.py; do not edit."
|
|
ATTRIBUTES = ".gitattributes"
|
|
BLOCK_BEGIN = "# BEGIN shims (generated by scripts/move/generate_shims.py; do not edit)\n"
|
|
BLOCK_END = "# END shims\n"
|
|
PATH_KINDS = ("by-path", "exists", "copy")
|
|
# Names that identify the module object itself; a by-path load keeps the shim's own.
|
|
IDENTITY = ("__name__", "__file__", "__spec__", "__loader__", "__package__", "__path__", "__cached__",
|
|
"__builtins__")
|
|
TEMPLATE = '''try: {header}
|
|
"""``{old}`` moved to ``{new}``."""
|
|
{text} import importlib
|
|
import importlib.util
|
|
import runpy
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
def _forward():
|
|
if __name__ == "__main__" or sys.argv[:1] == ["-m"] or importlib.util.find_spec("hermes_agent") is None:
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[{depth}]))
|
|
from hermes_agent.compat import install
|
|
|
|
install()
|
|
return None if __name__ == "__main__" else importlib.import_module("{new}")
|
|
|
|
try:
|
|
_module = _forward()
|
|
except Exception:
|
|
if sys.argv[:1] != ["-m"] and __name__ != "__main__": # an entry launch; a plain import stays light
|
|
raise
|
|
import hermes_bootstrap # repairs a killed update and relaunches when it restored something
|
|
_module = _forward()
|
|
if __name__ == "__main__":
|
|
runpy.run_module("{new}", run_name="__main__", alter_sys=True)
|
|
else:
|
|
if getattr(sys.modules.get(__name__), "__dict__", None) is globals():
|
|
sys.modules[__name__] = _module
|
|
_identity = {identity}
|
|
globals().update({{k: v for k, v in vars(_module).items() if k not in _identity}})
|
|
finally:
|
|
pass
|
|
'''
|
|
MARKER = '''try: {header}
|
|
"""``{old}`` moved to ``{new}``. A release checks that this file exists; nothing loads it."""
|
|
raise ImportError("{old} moved to {new} when this checkout was updated; restart Hermes to load it")
|
|
finally:
|
|
pass
|
|
'''
|
|
|
|
|
|
def _old_module(name: str, kind: str) -> str:
|
|
if kind in PATH_KINDS:
|
|
parts = Path(name).with_suffix("").parts
|
|
return ".".join(parts[:-1] if parts[-1] == "__init__" else parts)
|
|
return name
|
|
|
|
|
|
def generated() -> dict[str, bytes]:
|
|
"""Repo-relative path -> file bytes, for every required name that has moved."""
|
|
files = {}
|
|
for name, kind in REQUIRED_NAMES.items():
|
|
old = _old_module(name, kind)
|
|
new = current_name(old, MOVES)
|
|
if new is None or kind == "hand":
|
|
continue
|
|
target = ROOT.joinpath(*new.split("."))
|
|
if kind == "copy" and Path(name).suffix != ".py": # a data file a release reads at its old path
|
|
path, source = Path(name), target.with_suffix(Path(name).suffix)
|
|
elif (target / "__init__.py").is_file():
|
|
path, source = Path(*old.split("."), "__init__.py"), target / "__init__.py"
|
|
elif target.with_suffix(".py").is_file():
|
|
path, source = Path(*old.split(".")).with_suffix(".py"), target.with_suffix(".py")
|
|
else:
|
|
raise SystemExit(f"generate_shims: {old} moved to {new}, which is not in the tree")
|
|
if kind in PATH_KINDS:
|
|
path = Path(name)
|
|
if kind == "copy":
|
|
files[path.as_posix()] = source.read_bytes()
|
|
elif kind == "exists":
|
|
files[path.as_posix()] = MARKER.format(header=HEADER, old=old, new=new).encode()
|
|
else:
|
|
text = f" # {REQUIRED_TEXT[name]}\n" if name in REQUIRED_TEXT else ""
|
|
files[path.as_posix()] = TEMPLATE.format(header=HEADER, old=old, new=new, depth=len(path.parts) - 1,
|
|
identity=IDENTITY, text=text).encode()
|
|
return files
|
|
|
|
|
|
def attributes(paths: list[str]) -> bytes:
|
|
text = (ROOT / ATTRIBUTES).read_text(encoding="utf-8-sig")
|
|
head, begin, rest = text.partition(BLOCK_BEGIN)
|
|
_, end, tail = rest.partition(BLOCK_END)
|
|
if not (begin and end):
|
|
raise SystemExit(f"generate_shims: {ATTRIBUTES} has no shim block ({BLOCK_BEGIN.strip()} ... {BLOCK_END.strip()})")
|
|
block = "".join(f"/{p} linguist-generated=true\n" for p in sorted(paths))
|
|
return (head + BLOCK_BEGIN + block + BLOCK_END + tail).encode()
|
|
|
|
|
|
def strays(expected: dict[str, bytes]) -> list[str]:
|
|
"""Files that are not generated but carry the shim header, or sit in a moved package's old folder.
|
|
|
|
Git-ignored files are not listed, so build output inside an old folder is never a stray.
|
|
"""
|
|
listed = subprocess.run(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], cwd=ROOT,
|
|
capture_output=True, text=True, check=True, stdin=subprocess.DEVNULL, timeout=120).stdout
|
|
found = []
|
|
for rel in sorted(set(listed.split("\0")) - set(expected) - {""}):
|
|
path = ROOT / rel
|
|
if not path.is_file():
|
|
continue
|
|
folder = ".".join(Path(rel).parent.parts)
|
|
moved_folder = bool(folder) and current_name(folder, MOVES) is not None
|
|
if moved_folder or (rel.endswith(".py") and _is_shim(path)):
|
|
found.append(rel)
|
|
return found
|
|
|
|
|
|
def _is_shim(path: Path) -> bool:
|
|
with path.open(encoding="utf-8-sig", errors="replace") as handle:
|
|
return HEADER in handle.readline()
|
|
|
|
|
|
def missing_startup_files(files: dict[str, bytes]) -> list[str]:
|
|
"""Moved files that ``[tool.hermes] update-startup-files`` lists at a path the tree will not have."""
|
|
tables = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8-sig"))
|
|
listed = tables.get("tool", {}).get("hermes", {}).get("update-startup-files", [])
|
|
return [rel for rel in listed if rel not in files and not (ROOT / rel).is_file()
|
|
and current_name(_old_module(rel, "by-path"), MOVES) is not None]
|
|
|
|
|
|
def hand_written() -> list[str]:
|
|
"""Old paths that keep a hand-written file (kind ``hand``) once their name has moved."""
|
|
return [Path(*name.split(".")).with_suffix(".py").as_posix() for name, kind in REQUIRED_NAMES.items()
|
|
if kind == "hand" and current_name(name, MOVES) is not None]
|
|
|
|
|
|
def hand_written_problems() -> list[str]:
|
|
"""Kind ``hand`` files of moved names that are missing, are generated shims, or that updaters do not check.
|
|
|
|
A hand-written file runs before ``hermes_agent`` can be imported, so an update must refuse a tree where it
|
|
does not compile: ``[tool.hermes] update-startup-files`` has to list it.
|
|
"""
|
|
tables = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8-sig"))
|
|
listed = tables.get("tool", {}).get("hermes", {}).get("update-startup-files")
|
|
problems = []
|
|
for rel in hand_written():
|
|
if not (ROOT / rel).is_file():
|
|
problems.append(f"{rel}: hand-written file (required_names kind 'hand') is missing")
|
|
elif _is_shim(ROOT / rel):
|
|
problems.append(f"{rel}: must be hand-written (required_names kind 'hand'), not a generated shim")
|
|
elif listed is not None and rel not in listed:
|
|
problems.append(f"{rel}: hand-written file is not in [tool.hermes] update-startup-files, so an update "
|
|
"would accept a tree where it does not compile")
|
|
return problems
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("--check", action="store_true", help="change nothing; exit 1 when the tree differs")
|
|
args = parser.parse_args(argv)
|
|
files = generated()
|
|
stale = strays(files)
|
|
missing = missing_startup_files(files)
|
|
hand = hand_written_problems()
|
|
files[ATTRIBUTES] = attributes([p for p in files if p != ATTRIBUTES])
|
|
changed = [rel for rel, data in files.items() if not (ROOT / rel).is_file() or (ROOT / rel).read_bytes() != data]
|
|
for rel in missing:
|
|
print(f"{rel}: listed in [tool.hermes] update-startup-files but not in the tree, so updaters refuse "
|
|
f"the update; fix the list or add the old path to hermes_agent/compat/required_names.py")
|
|
for line in hand:
|
|
print(line)
|
|
if args.check:
|
|
for rel in changed:
|
|
print(f"{rel}: differs from what scripts/move/generate_shims.py writes; run it")
|
|
for rel in stale:
|
|
print(f"{rel}: stray: has the shim header or sits in a moved folder, but is not generated")
|
|
return 1 if changed or stale or missing or hand else 0
|
|
for rel in changed:
|
|
(ROOT / rel).parent.mkdir(parents=True, exist_ok=True)
|
|
(ROOT / rel).write_bytes(files[rel])
|
|
print(f"wrote {rel}")
|
|
kept = []
|
|
for rel in stale:
|
|
if _is_shim(ROOT / rel):
|
|
(ROOT / rel).unlink()
|
|
print(f"deleted {rel}")
|
|
else:
|
|
kept.append(rel)
|
|
print(f"{rel}: in a moved folder but not generated; move or delete it")
|
|
return 1 if kept else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|