From 14536c0da07233a7a4deddf8c73305ce918af3a7 Mon Sep 17 00:00:00 2001 From: Raghuram Subramani Date: Thu, 31 Jul 2025 11:15:37 +0530 Subject: main: add -w (watch) option instead of using watch.sh --- src/main.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 4 deletions(-) (limited to 'src/main.c') diff --git a/src/main.c b/src/main.c index 703c584..2fb2d2b 100644 --- a/src/main.c +++ b/src/main.c @@ -18,18 +18,24 @@ #define _GNU_SOURCE +#include #include +#include #include #include +#include #include +#define BUFFER_SIZE ((sizeof(struct inotify_event) + NAME_MAX + 1) * 1024) + msg_t *msg; void usage(char *program) { - printf("Usage: %s [-o ] [-h] \n", program); + printf("Usage: %s [-h] [-w] [-o ] \n", program); printf("\t-h : Help\n"); + printf("\t-w : Watch working directory for changes\n"); printf("\t-o : Output directory\n"); printf("\t: Working directory\n"); } @@ -46,16 +52,21 @@ main(int argc, char **argv) { printf("msg: The Minimal Static Site Generator\n\n"); + bool watch = false; + int opt; msg = malloc(sizeof(msg_t)); msg->base_directory = "."; msg->output_directory = "dist"; - while ((opt = getopt(argc, argv, "o:h")) != -1) { + while ((opt = getopt(argc, argv, "o:hw")) != -1) { switch (opt) { case 'o': msg->output_directory = optarg; break; + case 'w': + watch = true; + break; case 'h': default: usage(argv[0]); @@ -69,6 +80,55 @@ main(int argc, char **argv) config(); int r = run(); - free(msg); - return r; + if (!watch) { + free(msg); + return r; + } + + int fd = inotify_init1(IN_NONBLOCK); + if (fd < 0) { + perror("inotify"); + return EXIT_FAILURE; + } + + int wd = inotify_add_watch( + fd, msg->base_directory, IN_MODIFY | IN_CREATE | IN_DELETE); + if (wd < 0) { + perror("inotify_add_watch"); + return EXIT_FAILURE; + } + + char *buffer = malloc(BUFFER_SIZE); + + while (true) { + size_t i = 0; + size_t length = read(fd, buffer, BUFFER_SIZE); + if (length == 0) { + } + + if (length < 0) { + perror("read"); + return EXIT_FAILURE; + } + + char *p; + for (p = buffer; p < buffer + length;) { + struct inotify_event *event = (struct inotify_event *) p; + + if (event->len) { + switch (event->mask) { + case IN_MODIFY: + case IN_CREATE: + case IN_DELETE: + printf("\n\n"); + run(); + break; + + default: + break; + } + } + p += sizeof(struct inotify_event) + event->len; + } + } } -- cgit v1.2.3