Skip to content

Commit

Permalink
Support recursive watch
Browse files Browse the repository at this point in the history
  • Loading branch information
rnbguy committed Oct 2, 2017
1 parent ea15708 commit 05f71d7
Showing 1 changed file with 76 additions and 5 deletions.
81 changes: 76 additions & 5 deletions wat.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,73 @@ import (
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"

"gopkg.in/fsnotify.v1"
)

type RecursiveWatcher struct {
*fsnotify.Watcher
}

func (w *RecursiveWatcher) RecursiveAdd(name string) error {
fi, err := os.Stat(name)
if err != nil {
return err
} else if fi.IsDir() {
err := filepath.Walk(name, func(newPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
// log.Println("added", newPath)
w.Add(newPath)
}
return nil
})
if err != nil {
return err
}
} else {
err := w.Add(name)
if err != nil {
return err
}
}
return nil
}

func (w *RecursiveWatcher) RecursiveRemove(name string) error {
fi, err := os.Stat(name)
if err != nil {
return err
} else if fi.IsDir() {
err := filepath.Walk(name, func(newPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
// log.Println("removed", newPath)
w.Remove(newPath)
}
return nil
})
if err != nil {
return err
}
} else {
w.Remove(name)
if err != nil {
return err
}
}
return nil
}

type watch struct {
watcher *fsnotify.Watcher
watcher *RecursiveWatcher
}

func (w *watch) close() error {
Expand All @@ -23,11 +83,22 @@ func newWatch(path, command string, args []string, stdout io.Writer) (*watch, er
return nil, err
}

recurWatcher := &RecursiveWatcher{watcher}

fmt.Fprintln(stdout, "Waiting...")
go func(watcher *fsnotify.Watcher, command string) {
go func(watcher *RecursiveWatcher, command string) {
for {
select {
case event := <-watcher.Events:
// log.Println(event)
if event.Op&fsnotify.Create == fsnotify.Create {
if fi, _ := os.Stat(event.Name); fi.IsDir() {
watcher.RecursiveAdd(event.Name)
}
}
if event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename {
watcher.RecursiveRemove(event.Name)
}
if event.Op&fsnotify.Chmod == fsnotify.Chmod {
go func() {
cmd := exec.Command(command, args...)
Expand All @@ -41,11 +112,11 @@ func newWatch(path, command string, args []string, stdout io.Writer) (*watch, er
log.Println("error:", err)
}
}
}(watcher, command)
}(recurWatcher, command)

err = watcher.Add(path)
err = recurWatcher.RecursiveAdd(path)
if err != nil {
return nil, err
}
return &watch{watcher}, nil
return &watch{recurWatcher}, nil
}

0 comments on commit 05f71d7

Please sign in to comment.