[monitor] 规范watcher代码
This commit is contained in:
parent
c9a5a40645
commit
99eb6c2aed
|
|
@ -87,7 +87,7 @@ var StartCmd = &cobra.Command{
|
|||
// ====== 启动文件监听 ======
|
||||
logger.Log.Info("正在启动文件监听...")
|
||||
|
||||
mon, err := watcher.NewWatcher(cfg.Scanner.File.IncludePaths, cfg.Scanner.File.ExcludePaths)
|
||||
mon, err := watcher.NewWatcher(cfg)
|
||||
if err != nil {
|
||||
logger.Log.Error("启动文件监听失败", zap.Error(err))
|
||||
os.Exit(1)
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sysmonitord/internal/config"
|
||||
"sysmonitord/pkg/logger"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
|
|
@ -13,8 +14,7 @@ import (
|
|||
|
||||
type Watcher struct {
|
||||
fsnWatcher *fsnotify.Watcher
|
||||
paths []string
|
||||
ignore []string
|
||||
cfg *config.Config
|
||||
eventChan chan EventMsg
|
||||
}
|
||||
|
||||
|
|
@ -24,7 +24,7 @@ type EventMsg struct {
|
|||
FileInfo os.FileInfo
|
||||
}
|
||||
|
||||
func NewWatcher(paths []string, ignore []string) (*Watcher, error) {
|
||||
func NewWatcher(cfg *config.Config) (*Watcher, error) {
|
||||
fsnW, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[monitor] 创建文件监听失败: %w", err)
|
||||
|
|
@ -32,14 +32,15 @@ func NewWatcher(paths []string, ignore []string) (*Watcher, error) {
|
|||
|
||||
return &Watcher{
|
||||
fsnWatcher: fsnW,
|
||||
paths: paths,
|
||||
ignore: ignore,
|
||||
cfg: cfg,
|
||||
eventChan: make(chan EventMsg, 100),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (w *Watcher) Start() {
|
||||
for _, path := range w.paths {
|
||||
paths := w.cfg.Scanner.File.IncludePaths
|
||||
|
||||
for _, path := range paths {
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
fmt.Printf("[monitor] 路径不存在: %s\n", path)
|
||||
continue
|
||||
|
|
@ -48,7 +49,7 @@ func (w *Watcher) Start() {
|
|||
w.addPath(path)
|
||||
}
|
||||
|
||||
logger.Log.Info("[monitor] 已启用文件监听", zap.Strings("paths", w.paths))
|
||||
logger.Log.Info("[monitor] 已启用文件监听", zap.Strings("paths", paths))
|
||||
|
||||
go w.eventLoop()
|
||||
}
|
||||
|
|
@ -113,7 +114,7 @@ func (w *Watcher) addPath(path string) {
|
|||
}
|
||||
|
||||
if d.IsDir() {
|
||||
for _, ignorePath := range w.ignore {
|
||||
for _, ignorePath := range w.cfg.Scanner.File.ExcludePaths {
|
||||
if strings.HasPrefix(subPath, ignorePath) {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user