inotify/example/main.go

77 lines
1.5 KiB
Go
Raw Normal View History

2020-05-26 10:47:00 +08:00
package main
import (
"fmt"
2020-12-05 10:53:58 +08:00
"git.lovezsh.com/go-kit/inotify"
2020-05-26 10:47:00 +08:00
"log"
"os"
"path/filepath"
"time"
)
func main() {
watcher, err := inotify.NewWatcher()
if err != nil {
log.Println(err)
}
name := os.Args[1]
paths := make([]string, 0)
if !isExistDir(name) {
paths = append(paths, name)
} else {
var err error
paths, err = dirs(name)
if err != nil {
log.Fatal(err)
}
}
for _, v := range paths {
err = watcher.AddWatch(v)
if err != nil {
log.Fatalf("failed to add watch %s, error: %v\n", os.Args[1], err)
}
}
ticker := time.NewTicker(3 * time.Second)
for {
select {
case err := <-watcher.Errors:
log.Println(err)
os.Exit(1)
case event := <-watcher.Events:
if event.IsDir {
if event.Name == inotify.EventCreate {
err = watcher.AddWatch(event.Path)
if err != nil {
2020-05-26 10:48:34 +08:00
log.Fatalf("failed to add watch %s, error: %v\n", event.Path, err)
2020-05-26 10:47:00 +08:00
}
}
fmt.Println("Directory:", event.Path, "event:", event.Name)
} else {
fmt.Println("File:", event.Path, "event:", event.Name)
}
case <-ticker.C:
fmt.Println(watcher.Path())
}
}
}
func isExistDir(name string) bool {
f, err := os.Stat(name)
return err == nil && f.IsDir()
}
func dirs(name string) ([]string, error) {
matchs := make([]string, 0)
err := filepath.Walk(name, func(root string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
matchs = append(matchs, root)
}
return nil
})
return matchs, err
}