Skip to content

Commit

Permalink
fix: add a timer to support that files are changing at a high speed (#33
Browse files Browse the repository at this point in the history
)
  • Loading branch information
yusukebe authored Apr 15, 2022
1 parent aa20288 commit 00d46b3
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions cmd/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package cmd

import (
"regexp"
"time"

"github.com/fsnotify/fsnotify"
)

const ignorePattern = `\.swp$|~$|^\.DS_Store$|^4913$`
const lockTime = 100 * time.Millisecond

func createWatcher(dir string) (*fsnotify.Watcher, error) {
watcher, err := fsnotify.NewWatcher()
Expand All @@ -19,16 +21,26 @@ func createWatcher(dir string) (*fsnotify.Watcher, error) {
}

func watch(done <-chan interface{}, errorChan chan<- error, reload chan<- bool, watcher *fsnotify.Watcher) {
isLocked := false
for {
select {
case event := <-watcher.Events:
if isLocked {
break
}
if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
r := regexp.MustCompile(ignorePattern)
if r.MatchString(event.Name) {
logDebug("Debug [ignore]: `%s`", event.Name)
} else {
logInfo("Change detected in %s, refreshing", event.Name)
isLocked = true
reload <- true
timer := time.NewTimer(lockTime)
go func() {
<-timer.C
isLocked = false
}()
}
}
case err := <-watcher.Errors:
Expand Down

0 comments on commit 00d46b3

Please sign in to comment.