feat: refactored the hot reload

This commit is contained in:
Hazel 2025-04-10 13:32:42 +02:00
parent 6d1ea43089
commit 3503d1d42f
5 changed files with 66 additions and 9 deletions

View File

@ -11,8 +11,8 @@ classifiers = []
version = "0.0.0"
[project.scripts]
stsg_build = "stsg.__main__:build"
stsg_build_on_change = "stsg.__main__:build_on_change"
stsg = "stsg.__main__:build"
stsg_dev = "stsg.__main__:hot_reload"
[build-system]

View File

@ -0,0 +1 @@

View File

@ -0,0 +1 @@

View File

@ -3,18 +3,19 @@ from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
import os
import subprocess
from .config import SOURCE_DIRECTORY
from .config import SOURCE_DIRECTORY, CODE_DIRECTORY
logger = logging.getLogger("stsg")
def build():
print("building")
print("building changed")
class CustomFileSystemEventHandler(FileSystemEventHandler):
class MarkdownChangeHandler(FileSystemEventHandler):
def on_modified(self, event):
if event.is_directory:
return
@ -27,19 +28,69 @@ class CustomFileSystemEventHandler(FileSystemEventHandler):
build()
class PythonChangeHandler(FileSystemEventHandler):
def __init__(self, command):
self.env = os.environ.copy()
self.env["IS_CHILD"] = "true"
self.command = command
self.process = self.start_process()
def start_process(self):
print("[hot reload] Starting process...")
return subprocess.Popen(self.command, env=self.env)
def restart_process(self):
print("[hot reload] Restarting process...")
self.process.kill()
self.process = self.start_process()
def on_modified(self, event):
if event.is_directory:
return
filename = os.path.basename(event.src_path)
if filename.startswith('.') or filename.endswith(('~', '.tmp', '.swp')):
return
if event.src_path.endswith(".py"):
print(f"[hot reload] Detected change: {event.src_path}")
self.restart_process()
def stop_process(self):
if self.process:
self.process.terminate()
def build_on_change():
print("build on change")
build()
observer = Observer()
observer.schedule(CustomFileSystemEventHandler(), path=SOURCE_DIRECTORY, recursive=True)
observer.schedule(MarkdownChangeHandler(), path=SOURCE_DIRECTORY, recursive=True)
observer.start()
try:
while True:
time.sleep(1) # Keeps the thread alive
except KeyboardInterrupt:
observer.stop()
observer.join()
def hot_reload():
if os.environ.get("IS_CHILD") == "true":
build_on_change()
return
observer = Observer()
observer.schedule(PythonChangeHandler(["stsg_build_on_change"]), path=CODE_DIRECTORY, recursive=True)
observer.start()
try:
while True:
time.sleep(1) # Keeps the thread alive
except KeyboardInterrupt:
observer.stop()
observer.join()

View File

@ -1 +1,5 @@
SOURCE_DIRECTORY = "src"
# for development
CODE_DIRECTORY = "stsg"