基于fsnotify的文件监控模块,为eSync自动编译加载提供更改监听功能!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.2 KiB

4 years ago
  1. package main
  2. import (
  3. "github.com/fsnotify/fsnotify"
  4. "fmt"
  5. "path/filepath"
  6. "os"
  7. )
  8. type Watch struct {
  9. watch *fsnotify.Watcher
  10. }
  11. //监控目录
  12. func (w *Watch) watchDir(dir string) {
  13. //通过Walk来遍历目录下的所有子目录
  14. filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  15. //这里判断是否为目录,只需监控目录即可
  16. //目录下的文件也在监控范围内,不需要我们一个一个加
  17. if info.IsDir() {
  18. path, err := filepath.Abs(path)
  19. if err != nil {
  20. return err
  21. }
  22. err = w.watch.Add(path)
  23. if err != nil {
  24. return err
  25. }
  26. fmt.Println("监控 : ", path)
  27. }
  28. return nil
  29. })
  30. go func() {
  31. for {
  32. select {
  33. case ev := <-w.watch.Events:
  34. {
  35. if ev.Op&fsnotify.Create == fsnotify.Create {
  36. fmt.Println("创建文件 : ", ev.Name)
  37. //这里获取新创建文件的信息,如果是目录,则加入监控中
  38. fi, err := os.Stat(ev.Name)
  39. if err == nil && fi.IsDir() {
  40. w.watch.Add(ev.Name)
  41. fmt.Println("添加监控 : ", ev.Name)
  42. }
  43. }
  44. if ev.Op&fsnotify.Write == fsnotify.Write {
  45. fmt.Println("写入文件 : ", ev.Name)
  46. }
  47. if ev.Op&fsnotify.Remove == fsnotify.Remove {
  48. fmt.Println("删除文件 : ", ev.Name)
  49. //如果删除文件是目录,则移除监控
  50. fi, err := os.Stat(ev.Name)
  51. if err == nil && fi.IsDir() {
  52. w.watch.Remove(ev.Name)
  53. fmt.Println("删除监控 : ", ev.Name)
  54. }
  55. }
  56. if ev.Op&fsnotify.Rename == fsnotify.Rename {
  57. fmt.Println("重命名文件 : ", ev.Name)
  58. //如果重命名文件是目录,则移除监控
  59. //注意这里无法使用os.Stat来判断是否是目录了
  60. //因为重命名后,go已经无法找到原文件来获取信息了
  61. //所以这里就简单粗爆的直接remove好了
  62. w.watch.Remove(ev.Name)
  63. }
  64. if ev.Op&fsnotify.Chmod == fsnotify.Chmod {
  65. fmt.Println("修改权限 : ", ev.Name)
  66. }
  67. }
  68. case err := <-w.watch.Errors:
  69. {
  70. fmt.Println("error : ", err)
  71. return
  72. }
  73. }
  74. }
  75. }()
  76. }
  77. func main() {
  78. watch, _ := fsnotify.NewWatcher()
  79. w := Watch{
  80. watch: watch,
  81. }
  82. w.watchDir("./")
  83. select {}
  84. }