Skip to content

Instantly share code, notes, and snippets.

@gustavohenrique
Created June 1, 2023 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavohenrique/2599ce9b0f8d4f191480262c0a843dab to your computer and use it in GitHub Desktop.
Save gustavohenrique/2599ce9b0f8d4f191480262c0a843dab to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
var watcher *fsnotify.Watcher
// main
func main() {
var err error
watcher, err = fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
// starting at the root of the project, walk each file/directory searching for
// directories
dir := os.Getenv("MYSYNC_DIR")
fmt.Println("MYSYNC_DIR=", dir)
if err := filepath.Walk(dir, watchDir); err != nil {
fmt.Println("ERROR", err)
}
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("event:", event)
if event.Has(fsnotify.Write) {
log.Println("modified file:", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Println("ERROR", err)
}
}
}()
<-make(chan struct{})
}
// 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 err != nil {
log.Fatalln("ERROR", err)
}
if fi.Mode().IsDir() {
return watcher.Add(path)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment