From 8a072c4cc8f48258337930d00a218ceb0d99ac74 Mon Sep 17 00:00:00 2001
From: Volker Schukai <volker.schukai@schukai.com>
Date: Sun, 29 Oct 2023 18:00:02 +0100
Subject: [PATCH] fix: debouncing work wrong #6

---
 watching.go      | 16 +++++++++++-----
 watching_test.go |  6 +++---
 2 files changed, 14 insertions(+), 8 deletions(-)

diff --git a/watching.go b/watching.go
index d896c54..7002db9 100644
--- a/watching.go
+++ b/watching.go
@@ -38,7 +38,7 @@ func (l *lighthouse) StartWatching() error {
 	go func() {
 		eventChannel := make(chan fsnotify.Event, 100)
 		errorChannel := make(chan error, 100)
-		debounceTimers := make(map[string]*time.Timer)
+		debounceTimers := make(map[string]map[fsnotify.Op]*time.Timer)
 
 		var debounceMutex sync.Mutex
 
@@ -72,14 +72,20 @@ func (l *lighthouse) StartWatching() error {
 			case event := <-eventChannel:
 
 				debounceMutex.Lock()
-				if timer, ok := debounceTimers[event.Name]; ok {
+				if _, ok := debounceTimers[event.Name]; !ok {
+					debounceTimers[event.Name] = make(map[fsnotify.Op]*time.Timer)
+				}
+
+				if timer, ok := debounceTimers[event.Name][event.Op]; ok {
 					timer.Stop()
 				}
 
-				debounceTimers[event.Name] = time.AfterFunc(l.debounce, func() {
-					//debounceTimers[event.Name] = time.AfterFunc(l.debounce, func() {
+				debounceTimers[event.Name][event.Op] = time.AfterFunc(l.debounce, func() {
 					debounceMutex.Lock()
-					delete(debounceTimers, event.Name)
+					delete(debounceTimers[event.Name], event.Op)
+					if len(debounceTimers[event.Name]) == 0 {
+						delete(debounceTimers, event.Name)
+					}
 					debounceMutex.Unlock()
 
 					var watch *Watch
diff --git a/watching_test.go b/watching_test.go
index 8e176ea..675fbed 100644
--- a/watching_test.go
+++ b/watching_test.go
@@ -97,7 +97,7 @@ func TestRecreateEvent(t *testing.T) {
 		t.Fatalf("Failed to add watch: %v", err)
 	}
 
-	l.StartWatching()
+	_ = l.StartWatching()
 
 	timer := time.NewTimer(20 * time.Second)
 	go func() {
@@ -135,8 +135,8 @@ func TestRecreateEvent(t *testing.T) {
 	case <-ch:
 		timer.Stop()
 
-		assert.Equal(t, 0, callCounterCreate)
-		assert.Equal(t, 2, callCounterChange)
+		assert.Equal(t, 1, callCounterCreate)
+		assert.Equal(t, 1, callCounterChange)
 
 	case <-timeout:
 		t.Log("Timeout 2")
-- 
GitLab