From 098b590c5a4b89e1df5635e1c8e3d3ec7f03afe4 Mon Sep 17 00:00:00 2001 From: Arne Groskurth Date: Fri, 25 Jun 2021 22:47:09 +0200 Subject: [PATCH] Added test and implemented working fix --- integration_test.go | 54 +++++++++++++++++++++++++++++++++++++++++++++ windows.go | 8 ++++--- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/integration_test.go b/integration_test.go index fefae5ea..cd3738eb 100644 --- a/integration_test.go +++ b/integration_test.go @@ -14,6 +14,7 @@ import ( "path" "path/filepath" "runtime" + "strings" "sync" "sync/atomic" "testing" @@ -1259,6 +1260,59 @@ func TestCloseRace(t *testing.T) { } } +func TestMoveWatchedDirectory(t *testing.T) { + testDir := tempMkdir(t) + defer os.RemoveAll(testDir) + + watcher := newWatcher(t) + + // event recording + var events []Event + go func() { + for { + event, ok := <-watcher.Events + if !ok { + return + } + events = append(events, event) + } + }() + + addWatch(t, watcher, testDir) + + dir1 := filepath.Join(testDir, "dir") + dir2 := filepath.Join(testDir, "dir2") + + if err := os.Mkdir(dir1, 0o775); err != nil { + t.Fatal(err) + } + time.Sleep(10 * time.Millisecond) + addWatch(t, watcher, dir1) + if err := os.Rename(dir1, dir2); err != nil { + t.Fatal(err) + } + + time.Sleep(10 * time.Millisecond) + err := ioutil.WriteFile(filepath.Join(dir2, "file.ext"), []byte(""), 0o664) + if err != nil { + t.Fatal(err) + } + + if err := watcher.Close(); err != nil { + t.Fatal(err) + } + + time.Sleep(10 * time.Millisecond) + if len(events) != 4 { + t.Fatalf("Expected 4 events. Got: %d", len(events)) + } + + expectedSuffix := filepath.Join("dir2", "file.ext") + if !strings.HasSuffix(events[3].Name, expectedSuffix) { + t.Fatalf("Expected suffix %s, Got: %s", expectedSuffix, events[3].Name) + } +} + func testRename(file1, file2 string) error { switch runtime.GOOS { case "windows", "plan9": diff --git a/windows.go b/windows.go index a033fa5b..f5196a00 100644 --- a/windows.go +++ b/windows.go @@ -504,9 +504,11 @@ func (w *Watcher) readEvents() { // update saved path of all sub-watches oldFullName := filepath.Join(watch.path, watch.rename) - for _, otherWatch := range w.watches { - if strings.HasPrefix(otherWatch.path, oldFullName) { - otherWatch.path = filepath.Join(watch.path, strings.TrimPrefix(otherWatch.path, oldFullName)) + for _, watchMap := range w.watches { + for _, otherWatch := range watchMap { + if strings.HasPrefix(otherWatch.path, oldFullName) { + otherWatch.path = filepath.Join(fullname, strings.TrimPrefix(otherWatch.path, oldFullName)) + } } }