Skip to content

Instantly share code, notes, and snippets.

@ColinSullivan1
Created May 21, 2019 16:09
Show Gist options
  • Save ColinSullivan1/7c8880ed722273deb34ac4644cfb431c to your computer and use it in GitHub Desktop.
Save ColinSullivan1/7c8880ed722273deb34ac4644cfb431c to your computer and use it in GitHub Desktop.
Watches a directory, and periodically checks for changes in dir structure
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
var (
dir string
watcher *fsnotify.Watcher
done chan bool
)
func watch(dir string) {
// creates a new file watcher
watcher, _ = fsnotify.NewWatcher()
defer watcher.Close()
// starting at the root of the project, walk each file/directory searching for
// directories
if err := filepath.Walk(dir, watchDir); err != nil {
fmt.Printf("error walking directory: %v", err)
}
done = make(chan bool)
//
go func() {
for {
select {
// watch for events
case event := <-watcher.Events:
fmt.Printf("EVENT! %#v\n", event)
// watch for errors
case err := <-watcher.Errors:
fmt.Println("ERROR", err)
case <-time.After(2 * time.Second):
if err := filepath.Walk(dir, watchDir); err != nil {
fmt.Printf("error walking directory: %v", err)
}
}
}
}()
<-done
}
// main
func main() {
args := os.Args
if len(args) != 2 {
fmt.Printf("args: %v", args)
log.Print("Usage: fwatch <directory>")
os.Exit(1)
}
dir = args[1]
watch(args[1])
}
// watchDir gets run as a walk func, searching for directories to add watchers to
func watchDir(path string, fi os.FileInfo, err error) error {
// since fsnotify can watch all the files in a directory, watchers only need
// to be added to each nested directory
if fi.Mode().IsDir() {
fmt.Printf("Adding path %s\n", path)
return watcher.Add(path)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment