Skip to content

Commit

Permalink
updated watcher (added a global close method)
Browse files Browse the repository at this point in the history
  • Loading branch information
AspieSoft committed Dec 20, 2022
1 parent ff0d747 commit 482cef0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ go 1.18

require (
github.com/AspieSoft/go-regex/v4 v4.1.0
github.com/alphadose/haxmap v1.2.0
github.com/fsnotify/fsnotify v1.6.0
)

require (
github.com/AspieSoft/go-syncterval v1.0.3 // indirect
github.com/AspieSoft/go-ttlcache v1.2.0 // indirect
github.com/GRbit/go-pcre v1.0.0 // indirect
github.com/alphadose/haxmap v1.2.0 // indirect
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
golang.org/x/exp v0.0.0-20221204150635-6dcec336b2bb // indirect
golang.org/x/sys v0.3.0 // indirect
Expand Down
37 changes: 37 additions & 0 deletions goutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"strings"

"github.com/AspieSoft/go-regex/v4"
"github.com/alphadose/haxmap"
"github.com/fsnotify/fsnotify"
)

Expand Down Expand Up @@ -1020,6 +1021,13 @@ type Watcher struct {
Any func(path string, op string)
}

type watcherObj struct {
root string
watcher *fsnotify.Watcher
}

var watcherList *haxmap.Map[string, watcherObj] = haxmap.New[string, watcherObj]()

// WatchDir watches the files in a directory and its subdirectories for changes
func WatchDir(root string, cb *Watcher) {
watcher, err := fsnotify.NewWatcher()
Expand All @@ -1028,6 +1036,21 @@ func WatchDir(root string, cb *Watcher) {
}
defer watcher.Close()

rand := root + "." + string(RandBytes(64))
if _, ok := watcherList.Get(rand); ok {
loops := 10000
for loops > 0 {
loops--
if _, ok := watcherList.Get(rand); !ok {
break
}
rand = root + "." + string(RandBytes(64))
}
}
if _, ok := watcherList.Get(rand); !ok {
watcherList.Set(rand, watcherObj{root, watcher})
}

done := make(chan bool)
go func() {
defer close(done)
Expand Down Expand Up @@ -1083,6 +1106,20 @@ func watchDirSub(watcher *fsnotify.Watcher, dir string){
}
}

// CloseWatchers will close all the watchers with the given root if they were created by goutil
//
// @root pass a file path for a specific watcher or "*" for all watchers that exist
//
// note: this method may include other modules that are using goutil as a dependency
func CloseWatchers(root string) {
watcherList.ForEach(func(id string, cache watcherObj) bool {
if root == "*" || cache.root == root {
cache.watcher.Close()
}
return true
})
}


// InstallLinuxPkg attempts to install a linux package
//
Expand Down

0 comments on commit 482cef0

Please sign in to comment.