2018-06-16 19:22:21 -05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Watcher ...
|
|
|
|
type Watcher struct {
|
2018-06-18 21:21:43 -05:00
|
|
|
PollInterval int
|
2018-06-16 19:22:21 -05:00
|
|
|
WatchItems []string
|
|
|
|
IgnoreItems []string
|
|
|
|
AllowedExtensions map[string]bool
|
|
|
|
Events chan string
|
|
|
|
Errors chan error
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewWatcher ...
|
2018-06-18 21:21:43 -05:00
|
|
|
func NewWatcher(pollInterval int, watchItems []string, ignoreItems []string, extensions []string) *Watcher {
|
2018-06-16 19:22:21 -05:00
|
|
|
allowedExts := make(map[string]bool)
|
|
|
|
for _, ext := range extensions {
|
|
|
|
allowedExts["."+ext] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Watcher{
|
|
|
|
Events: make(chan string),
|
|
|
|
Errors: make(chan error),
|
2018-06-18 21:21:43 -05:00
|
|
|
PollInterval: pollInterval,
|
2018-06-16 19:22:21 -05:00
|
|
|
WatchItems: watchItems,
|
|
|
|
IgnoreItems: ignoreItems,
|
|
|
|
AllowedExtensions: allowedExts,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var startTime = time.Now()
|
|
|
|
var errDetectedChange = errors.New("done")
|
|
|
|
|
|
|
|
// Watch ...
|
|
|
|
func (w *Watcher) Watch() { // nolint: gocyclo
|
|
|
|
for {
|
|
|
|
err := filepath.Walk(w.WatchItems[0], func(path string, info os.FileInfo, err error) error {
|
|
|
|
if path == ".git" && info.IsDir() {
|
|
|
|
return filepath.SkipDir
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, x := range w.IgnoreItems {
|
|
|
|
if x == path {
|
|
|
|
return filepath.SkipDir
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ignore hidden files
|
|
|
|
if filepath.Base(path)[0] == '.' {
|
|
|
|
return nil
|
|
|
|
}
|
2018-06-18 21:21:43 -05:00
|
|
|
time.Sleep(time.Duration(w.PollInterval) * time.Millisecond)
|
2018-06-16 19:22:21 -05:00
|
|
|
|
|
|
|
ext := filepath.Ext(path)
|
|
|
|
if _, ok := w.AllowedExtensions[ext]; ok && info.ModTime().After(startTime) {
|
|
|
|
w.Events <- path
|
|
|
|
startTime = time.Now()
|
|
|
|
return errDetectedChange
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil && err != errDetectedChange {
|
|
|
|
w.Errors <- err
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|