增加 自定义事件支持

This commit is contained in:
dengsgo 2019-12-04 11:50:11 +08:00
parent a0af500678
commit aa929ae838
5 changed files with 54 additions and 17 deletions

View File

@ -29,12 +29,21 @@ var (
watcher *fsnotify.Watcher
taskMan *TaskMan
ioeventMapStr = map[fsnotify.Op]string{
fsnotify.Write: "write",
fsnotify.Rename: "rename",
fsnotify.Remove: "remove",
fsnotify.Create: "create",
fsnotify.Chmod: "chmod",
}
)
type changedFile struct {
Name string
Changed int64
Ext string
Event string
}
func parseConfig() {
@ -70,19 +79,18 @@ func eventDispatcher(event fsnotify.Event) {
!keyInMonitorTypesMap(ext, cfg) {
return
}
switch event.Op {
case
fsnotify.Write,
fsnotify.Rename:
log.Println("EVENT", event.Op.String(), ":", event.Name)
taskMan.Put(&changedFile{
Name: relativePath(projectFolder, event.Name),
Changed: time.Now().UnixNano(),
Ext: ext,
})
case fsnotify.Remove:
case fsnotify.Create:
op := ioeventMapStr[event.Op]
if len(cfg.Monitor.Events) != 0 && !inStrArray(op, cfg.Monitor.Events) {
return
}
log.Println("EVENT", event.Op.String(), ":", event.Name)
taskMan.Put(&changedFile{
Name: relativePath(projectFolder, event.Name),
Changed: time.Now().UnixNano(),
Ext: ext,
Event: op,
})
}
func addWatcher() {

View File

@ -8,6 +8,7 @@ type FileGirl struct {
Types []string `yaml:"types"`
IncludeDirs []string `yaml:"includeDirs"`
ExceptDirs []string `yaml:"exceptDirs"`
Events []string `yaml:"events"`
// convert to
TypesMap map[string]bool `yaml:"-"`
IncludeDirsMap map[string]bool `yaml:"-"`

View File

@ -14,6 +14,7 @@ type postParams struct {
File string `json:"file"`
Changed int64 `json:"changed"`
Ext string `json:"ext"`
Event string `json:"event"`
}
type NetNotifier struct {
@ -42,6 +43,7 @@ func (n *NetNotifier) Put(cf *changedFile) {
File: cf.Name,
Changed: cf.Changed,
Ext: cf.Ext,
Event: cf.Event,
})
}

14
raw.go
View File

@ -32,6 +32,20 @@ monitor:
types:
- .go
# 监听的事件类型发生此类事件才执行 command 中的命令
# 没有该配置默认监听所有事件
# write 写入文件事件
# rename 重命名文件事件
# remove 移除文件事件
# create 创建文件事件
# chmod 更新文件权限事件(类unix)
events:
- write
- rename
- remove
- create
- chmod
# 命令
command:
# 监听的文件有更改会执行的命令

22
util.go
View File

@ -25,12 +25,15 @@ func cmdParse2Array(s string, cf *changedFile) []string {
}
func strParseRealStr(s string, cf *changedFile) string {
return strings.Replace(
strings.Replace(
strings.Replace(s, "{{file}}", cf.Name, -1),
"{{ext}}", cf.Ext, -1,
return strings.ReplaceAll(
strings.ReplaceAll(
strings.ReplaceAll(
strings.ReplaceAll(s, "{{file}}", cf.Name),
"{{ext}}", cf.Ext,
),
"{{changed}}", strconv.FormatInt(cf.Changed, 10),
),
"{{changed}}", strconv.FormatInt(cf.Changed, 10), -1,
"{{event}}", cf.Event,
)
}
@ -64,6 +67,15 @@ func relativePath(folder, p string) string {
return s
}
func inStrArray(s string, arr []string) bool {
for _, v := range arr {
if s == v {
return true
}
}
return false
}
func logAndExit(v ...interface{}) {
log.Println(v...)
os.Exit(0)