Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. package main
  2.  
  3. // https://medium.com/@skdomino/watch-this-file-watching-in-go-5b5a247cf71f
  4.  
  5. import (
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9.  
  10. "github.com/fsnotify/fsnotify"
  11. "time"
  12. )
  13.  
  14. //
  15. var watcher *fsnotify.Watcher
  16.  
  17. // main
  18. func main() {
  19. var err error
  20.  
  21. // creates a new file watcher
  22. watcher, err = fsnotify.NewWatcher()
  23. if err != nil {
  24. panic(err)
  25. }
  26. defer watcher.Close()
  27.  
  28. rootPath := os.Getenv("RP")
  29. if rootPath == "" {
  30. panic("rootpath is null, please pass RP=..., even if it's just RP=.")
  31. }
  32.  
  33. filePath := os.Getenv("FP")
  34. if filePath == "" {
  35. panic("FP is null, please pass FP=....")
  36. }
  37.  
  38. // starting at the root of the project, walk each file/directory searching for
  39. // directories
  40. if err := filepath.Walk(rootPath, watchDir); err != nil {
  41. fmt.Println("ERROR", err)
  42. panic(err)
  43. }
  44.  
  45. //
  46. done := make(chan bool)
  47.  
  48. //
  49. go func() {
  50. for {
  51. select {
  52. // watch for events
  53. case event := <-watcher.Events:
  54. fmt.Printf("%s EVENT! %#v\n", time.Now().String(), event)
  55.  
  56. // watch for errors
  57. case err := <-watcher.Errors:
  58. fmt.Printf("%s ERROR %s\n", time.Now().String(), err.Error())
  59. }
  60. }
  61. }()
  62.  
  63. <-done
  64. }
  65.  
  66. // watchDir gets run as a walk func, searching for directories to add watchers to
  67. func watchDir(path string, fi os.FileInfo, err error) error {
  68.  
  69. // since fsnotify can watch all the files in a directory, watchers only need
  70. // to be added to each nested directory
  71. if fi != nil && fi.Mode().IsDir() {
  72. return watcher.Add(path)
  73. }
  74.  
  75. return nil
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement