74 lines
2.1 KiB
Python
74 lines
2.1 KiB
Python
"""Dev runner: restart the server when Python changes.
|
|
|
|
The page reloads itself when static files change, and again after the
|
|
server comes back from a Python restart.
|
|
|
|
pipenv run pattern
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
PKG = Path(__file__).resolve().parent
|
|
ROOT = PKG.parent
|
|
|
|
|
|
def stamp(root: Path, suffix: str) -> dict[str, int]:
|
|
found: dict[str, int] = {}
|
|
for path in root.rglob(f"*{suffix}"):
|
|
if "__pycache__" in path.parts or not path.is_file():
|
|
continue
|
|
found[str(path)] = path.stat().st_mtime_ns
|
|
return found
|
|
|
|
|
|
def stop_child(proc: subprocess.Popen) -> None:
|
|
if proc.poll() is not None:
|
|
return
|
|
proc.send_signal(signal.SIGINT)
|
|
try:
|
|
proc.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
proc.kill()
|
|
proc.wait()
|
|
|
|
|
|
def main() -> int:
|
|
os.chdir(ROOT)
|
|
cmd = [sys.executable, "-m", "pattern_pad.server", *sys.argv[1:]]
|
|
print("pattern editor — reload on Python and page changes", flush=True)
|
|
while True:
|
|
py = stamp(PKG, ".py")
|
|
parent = Path(__file__).stat().st_mtime_ns
|
|
proc = subprocess.Popen(cmd)
|
|
try:
|
|
while proc.poll() is None:
|
|
time.sleep(0.25)
|
|
if Path(__file__).stat().st_mtime_ns != parent:
|
|
stop_child(proc)
|
|
os.execv(sys.executable, [sys.executable, "-m", "pattern_pad", *sys.argv[1:]])
|
|
if stamp(PKG, ".py") != py:
|
|
print("reload backend", flush=True)
|
|
stop_child(proc)
|
|
break
|
|
else:
|
|
code = proc.returncode or 0
|
|
if code not in (0, -signal.SIGINT, 128 + signal.SIGINT):
|
|
print(f"server exited ({code})", flush=True)
|
|
return code
|
|
return 0
|
|
except KeyboardInterrupt:
|
|
print("\nstopped", flush=True)
|
|
stop_child(proc)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|