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.

127 lines
2.5 KiB

  1. package utils
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/fsnotify/fsnotify"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. )
  10. // Watch: 监控对象
  11. type Watch struct {
  12. *fsnotify.Watcher
  13. }
  14. func NewWatch() *Watch {
  15. obj, _ := fsnotify.NewWatcher()
  16. return &Watch{obj}
  17. }
  18. // Watch: 监控对象
  19. func (w *Watch) Watch(path string, t *T) error {
  20. // 先转化为绝对路径
  21. path, err := filepath.Abs(path)
  22. if err != nil {
  23. return err
  24. }
  25. // 判断是单个文件还是目录文件
  26. fileInfo, err := os.Stat(path)
  27. if err != nil {
  28. return err
  29. }
  30. // 判断是否是目录 添加监控
  31. if fileInfo.IsDir() {
  32. // dir
  33. err = w.watchDir(path)
  34. } else {
  35. err = w.watchFile(path)
  36. }
  37. if err != nil {
  38. return err
  39. }
  40. c := make(chan error)
  41. // 启动监控
  42. go func() {
  43. for {
  44. select {
  45. case even, ok := <-w.Events:
  46. if !ok {
  47. // close
  48. fmt.Println("Errors close")
  49. c <- errors.New("errors close")
  50. return
  51. }
  52. // 判断时间
  53. fmt.Println("even", even)
  54. switch {
  55. // todo 待处理
  56. case even.Op&fsnotify.Create == fsnotify.Create:
  57. //这里获取新创建文件的信息,如果是目录,则加入监控中
  58. fmt.Println("创建文件 : ", even.Name)
  59. //t.AddTask()
  60. _ = w.Add(even.Name)
  61. case even.Op&fsnotify.Write == fsnotify.Write:
  62. fmt.Println("修改 : ", even.Name)
  63. fmt.Println(filepath.Ext(even.Name))
  64. if filepath.Ext(even.Name) == ".go" {
  65. fmt.Println("send addtask:", even.Name)
  66. t.AddTask()
  67. }
  68. case even.Op&fsnotify.Remove == fsnotify.Remove:
  69. fmt.Println("删除 : ", even.Name)
  70. //t.AddTask()
  71. _ = w.Remove(even.Name)
  72. case even.Op&fsnotify.Rename == fsnotify.Rename:
  73. fmt.Println("重命名 : ", even.Name)
  74. //t.AddTask()
  75. _ = w.Remove(even.Name)
  76. }
  77. case err = <-w.Errors:
  78. fmt.Println("79", err)
  79. c <- err
  80. return
  81. }
  82. }
  83. }()
  84. return <-c
  85. }
  86. // watchDir: 处理监控目录
  87. func (w *Watch) watchDir(path string) error {
  88. // 先将自己添加到监控
  89. err := w.Add(path)
  90. if err != nil {
  91. return err
  92. }
  93. fileSlice, err := ioutil.ReadDir(path)
  94. if err != nil {
  95. return err
  96. }
  97. for _, f := range fileSlice {
  98. fPath := filepath.Join(path, f.Name())
  99. if !f.IsDir() {
  100. // todo 这里加一些条件筛选添加监控的内容
  101. err = w.watchFile(fPath)
  102. if err != nil {
  103. return err
  104. }
  105. } else {
  106. err := w.watchDir(fPath)
  107. if err != nil {
  108. return err
  109. }
  110. }
  111. }
  112. return err
  113. }
  114. // watchDir: 处理监控单文件
  115. func (w *Watch) watchFile(path string) error {
  116. return w.Add(path)
  117. }