Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- // https://medium.com/@skdomino/watch-this-file-watching-in-go-5b5a247cf71f
- import (
- "fmt"
- "os"
- "path/filepath"
- "github.com/fsnotify/fsnotify"
- "time"
- )
- //
- var watcher *fsnotify.Watcher
- // main
- func main() {
- var err error
- // creates a new file watcher
- watcher, err = fsnotify.NewWatcher()
- if err != nil {
- panic(err)
- }
- defer watcher.Close()
- rootPath := os.Getenv("RP")
- if rootPath == "" {
- panic("rootpath is null, please pass RP=..., even if it's just RP=.")
- }
- filePath := os.Getenv("FP")
- if filePath == "" {
- panic("FP is null, please pass FP=....")
- }
- // starting at the root of the project, walk each file/directory searching for
- // directories
- if err := filepath.Walk(rootPath, watchDir); err != nil {
- fmt.Println("ERROR", err)
- panic(err)
- }
- //
- done := make(chan bool)
- //
- go func() {
- for {
- select {
- // watch for events
- case event := <-watcher.Events:
- fmt.Printf("%s EVENT! %#v\n", time.Now().String(), event)
- // watch for errors
- case err := <-watcher.Errors:
- fmt.Printf("%s ERROR %s\n", time.Now().String(), err.Error())
- }
- }
- }()
- <-done
- }
- // 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 != nil && fi.Mode().IsDir() {
- return watcher.Add(path)
- }
- return nil
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement