From 896b5d75c17602ebf22514674518698e45ba2149 Mon Sep 17 00:00:00 2001
From: Volker Schukai <volker.schukai@schukai.com>
Date: Sun, 23 Oct 2022 10:21:27 +0200
Subject: [PATCH] fix monitor directories not files

---
 import.go   |  6 +++---
 settings.go |  2 +-
 watch.go    | 21 ++++++++++++++++++++-
 3 files changed, 24 insertions(+), 5 deletions(-)

diff --git a/import.go b/import.go
index b0963ad..70be576 100644
--- a/import.go
+++ b/import.go
@@ -95,7 +95,7 @@ func (s *Settings[C]) importFiles() {
 	s.fileWatch.Lock()
 
 	// new files may have been added
-	tmpWatchList := make(map[string]string)
+	tmpWatchList := make(map[string]bool)
 
 	defer func() {
 		s.fileWatch.watchList = tmpWatchList
@@ -123,7 +123,7 @@ func (s *Settings[C]) importFiles() {
 		s.importStream(reader{s.files.format, r})
 		f.Close()
 
-		tmpWatchList[fn] = fn
+		tmpWatchList[fn] = true
 
 	}
 
@@ -138,7 +138,7 @@ func (s *Settings[C]) importFiles() {
 		s.importStream(reader{f.format, r})
 
 		r.Close()
-		tmpWatchList[f.path] = f.path
+		tmpWatchList[f.path] = true
 	}
 
 }
diff --git a/settings.go b/settings.go
index 15f66f6..62a9d09 100644
--- a/settings.go
+++ b/settings.go
@@ -13,7 +13,7 @@ import (
 type fileWatch struct {
 	sync.Mutex
 	watcher     *fsnotify.Watcher
-	watchList   map[string]string
+	watchList   map[string]bool
 	cancelWatch chan bool
 	onWatch     bool
 }
diff --git a/watch.go b/watch.go
index 9503048..52967e7 100644
--- a/watch.go
+++ b/watch.go
@@ -5,6 +5,8 @@ package configuration
 
 import (
 	"github.com/fsnotify/fsnotify"
+	"os"
+	"path"
 )
 
 func (s *Settings[C]) initWatch() *Settings[C] {
@@ -97,7 +99,19 @@ func (s *Settings[C]) Watch() *Settings[C] {
 
 	// add all files to the watch list
 	for file := range s.fileWatch.watchList {
-		err := s.fileWatch.watcher.Add(file)
+
+		fileInfo, err := os.Stat(file)
+		if err != nil {
+			s.errors = append(s.errors, err)
+			continue
+		}
+
+		if fileInfo.IsDir() {
+			err = s.fileWatch.watcher.Add(file)
+		} else {
+			err = s.fileWatch.watcher.Add(path.Dir(file))
+		}
+
 		if err != nil {
 			s.errors = append(s.errors, err)
 		}
@@ -119,6 +133,11 @@ func (s *Settings[C]) Watch() *Settings[C] {
 					return
 				}
 
+				_, exist := s.fileWatch.watchList[event.Name]
+				if !exist {
+					continue
+				}
+
 				if event.Op&fsnotify.Write == fsnotify.Write {
 					s.Import()
 				} else if event.Op&fsnotify.Remove == fsnotify.Remove {
-- 
GitLab