43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
import dataclasses
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
|
|
RELOAD_FLAG = "--reloaded"
|
|
|
|
|
|
def decode_state(handed, kind):
|
|
try:
|
|
fields = json.loads(handed)
|
|
except ValueError:
|
|
return None
|
|
shape = {field.name: field.type for field in dataclasses.fields(kind)}
|
|
if not isinstance(fields, dict) or fields.keys() != shape.keys():
|
|
return None
|
|
if any(type(fields[name]) is not type_ for name, type_ in shape.items()):
|
|
return None
|
|
return kind(**fields)
|
|
|
|
|
|
def fingerprint(launcher):
|
|
digest = hashlib.sha256()
|
|
for path in [launcher, *sorted((launcher.parent / "loop_claude").glob("*.py"))]:
|
|
try:
|
|
content = path.read_bytes()
|
|
except OSError as failure:
|
|
content = str(failure).encode()
|
|
digest.update(f"{path.name}\0{len(content)}\0".encode() + content)
|
|
return digest.hexdigest()
|
|
|
|
|
|
def reload_if_edited(launcher, baseline, state):
|
|
if fingerprint(launcher) == baseline:
|
|
return
|
|
trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True)
|
|
if trial.returncode != 0:
|
|
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
|
return
|
|
os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))])
|