Last active
April 20, 2020 10:09
-
-
Save bachue/68f7494ec5ce2e4c1ad43e3130175401 to your computer and use it in GitHub Desktop.
测试 fsnotify 库
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/fsnotify/fsnotify" | |
"log" | |
"os" | |
"path/filepath" | |
) | |
func main() { | |
watcher, err := fsnotify.NewWatcher() | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer watcher.Close() | |
for _, arg := range os.Args[1:] { | |
addPathToWatcher(watcher, arg) | |
} | |
for { | |
select { | |
case event, ok := <-watcher.Events: | |
if ok { | |
fmt.Printf("** New Event: %s\n", event.String()) | |
if event.Op&fsnotify.Create == fsnotify.Create { | |
addPathToWatcher(watcher, event.Name) | |
} | |
} else { | |
break | |
} | |
case err, ok := <-watcher.Errors: | |
if ok { | |
fmt.Printf("** New Error: %s\n", err) | |
} else { | |
break | |
} | |
} | |
} | |
} | |
func addPathToWatcher(watcher *fsnotify.Watcher, path string) { | |
fileInfo, err := os.Stat(path) | |
if err != nil { | |
fmt.Printf("** Stat %s Error: %s\n", path, err) | |
return | |
} | |
if !fileInfo.Mode().IsRegular() && !fileInfo.Mode().IsDir() { | |
return | |
} | |
if err := watcher.Add(path); err != nil { | |
fmt.Printf("** Add Watcher Error: %s\n", err) | |
} else { | |
fmt.Printf("** Add %s to Watcher\n", path) | |
} | |
if fileInfo.Mode().IsDir() { | |
filepath.Walk(path, func(subPath string, subFileInfo os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} else if path == subPath { | |
return nil | |
} else if !subFileInfo.Mode().IsRegular() && !subFileInfo.Mode().IsDir() { | |
return nil | |
} else if err = watcher.Add(subPath); err != nil { | |
fmt.Printf("** Add %s to Watcher Error: %s\n", subPath, err) | |
return err | |
} else { | |
fmt.Printf("** Add %s to Watcher\n", subPath) | |
return nil | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment