Skip to content

Instantly share code, notes, and snippets.

@Xnuvers007
Created October 3, 2025 19:01
Show Gist options
  • Save Xnuvers007/c0c27e3a81911e26b3b043b98e463314 to your computer and use it in GitHub Desktop.
Save Xnuvers007/c0c27e3a81911e26b3b043b98e463314 to your computer and use it in GitHub Desktop.
import time
import subprocess
import os
from sys import platform
try:
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
except (ModuleNotFoundError, ImportError):
print("watchdog module not found. Installing...")
subprocess.check_call([os.sys.executable, "-m", "pip", "install", "watchdog"])
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
finally:
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
WATCH_PATH = os.path.join(os.getcwd())
class LaravelServer:
def __init__(self):
self.process = None
def start(self):
print("Clear & re-cache Laravel config/routes/view...")
commands = [
["php", "artisan", "config:clear"],
["php", "artisan", "config:cache"],
["php", "artisan", "route:clear"],
["php", "artisan", "route:cache"],
["php", "artisan", "view:clear"],
["php", "artisan", "optimize:clear"]
]
for cmd in commands:
subprocess.run(cmd, cwd=WATCH_PATH)
print("Starting Laravel server...")
self.process = subprocess.Popen(["php", "artisan", "serve"], cwd=WATCH_PATH)
self.process.wait()
def restart(self):
if self.process:
print("Stopping Laravel server...")
self.process.terminate()
self.process.wait()
self.start()
class ChangeHandler(PatternMatchingEventHandler):
def __init__(self, server):
super().__init__(
patterns=["*.php", "*.env", "*.blade.php", "*.js", "*.css"],
ignore_patterns=[
"*/vendor/*",
"*/storage/*",
"*/node_modules/*",
"*/venv/*",
],
ignore_directories=False
)
self.server = server
self.last_restart = 0
def on_any_event(self, event):
path = event.src_path.lower().replace("\\", "/")
if any(x in path for x in ["/vendor/", "/storage/", "/node_modules/", "/venv/"]):
return
if time.time() - self.last_restart < 2:
return
print(f"Detected change: {event.src_path} ({event.event_type})")
self.server.restart()
self.last_restart = time.time()
if __name__ == "__main__":
server = LaravelServer()
server.start()
event_handler = ChangeHandler(server)
observer = Observer()
observer.schedule(event_handler, path=WATCH_PATH, recursive=True)
observer.start()
print(f"Watching changes in {WATCH_PATH}...")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
if server.process:
server.process.terminate()
observer.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment