From e699b3e3e520d088b7ec18835d0d5f51afd82ee1 Mon Sep 17 00:00:00 2001 From: Jessica Tallon Date: Sun, 16 Aug 2020 18:39:44 +0200 Subject: [PATCH] Add support for watching for changes and re-generating --- exhibition/command.py | 14 +++++++++++++- exhibition/utils.py | 17 +++++++++++++++++ setup.py | 1 + 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/exhibition/command.py b/exhibition/command.py index d3d83c2..c28bf07 100644 --- a/exhibition/command.py +++ b/exhibition/command.py @@ -26,6 +26,7 @@ import logging import click +from watchdog.observers import Observer from . import __version__, config, utils @@ -58,7 +59,8 @@ def gen(): @exhibition.command(short_help="Serve site locally") @click.option("-s", "--server", default="localhost", help="Hostname to serve the site at.") @click.option("-p", "--port", default=8000, type=int, help="Port to serve the site at.") -def serve(server, port): +@click.option("--watch/--no-watch", default=True, help="Enables/Disables watching for changes.") +def serve(server, port, watch): """ Serve files from deploy_path as a webserver would """ @@ -66,7 +68,17 @@ def serve(server, port): server_address = (server, port) httpd, thread = utils.serve(settings, server_address) + print("Watch status: %s" % watch) + if watch: + utils.gen(settings) + observer = Observer() + handler = utils.FileSystemChangeHandler(settings) + observer.schedule(handler, settings["content_path"], recursive=True) + observer.schedule(handler, settings["templates"], recursive=True) + observer.start() + try: thread.join() except (KeyboardInterrupt, SystemExit): httpd.shutdown() + observer.join() diff --git a/exhibition/utils.py b/exhibition/utils.py index d4d144f..76114cf 100644 --- a/exhibition/utils.py +++ b/exhibition/utils.py @@ -25,6 +25,8 @@ import shutil import threading +import watchdog + from .node import Node logger = logging.getLogger("exhibition") @@ -44,6 +46,21 @@ def gen(settings): item.render() +class FileSystemChangeHandler(watchdog.events.FileSystemEventHandler): + """ Handler for changes on the file system """ + settings = None + + def __init__(self, settings, *args, **kwargs): + super().__init__(*args, **kwargs) + self.settings = settings + + def on_any_event(self, event): + """ An event has happened, re-generate the site """ + super().on_any_event(event) + print("Regenerating website") + gen(self.settings) + + class ExhibitionBaseHTTPRequestHandler(SimpleHTTPRequestHandler): def _sanitise_path(self, path): """ Strip leading and trailing / as well as base_url, if preset """ diff --git a/setup.py b/setup.py index fcc94c1..218e30d 100644 --- a/setup.py +++ b/setup.py @@ -40,6 +40,7 @@ "ruamel.yaml", "typogrify", "pypandoc", + "watchdog", ], extras_require={ "docs": [