1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
package main
import "github.com/fsnotify/fsnotify"
// This is the most basic example: it prints events to the terminal as we
// receive them.
func watch(paths ...string) {
if len(paths) < 1 {
exit("must specify at least one path to watch")
}
// Create a new watcher.
w, err := fsnotify.NewWatcher()
if err != nil {
exit("creating a new watcher: %s", err)
}
defer w.Close()
// Start listening for events.
go watchLoop(w)
// Add all paths from the commandline.
for _, p := range paths {
err = w.Add(p)
if err != nil {
exit("%q: %s", p, err)
}
}
printTime("ready; press ^C to exit")
<-make(chan struct{}) // Block forever
}
func watchLoop(w *fsnotify.Watcher) {
i := 0
for {
select {
// Read from Errors.
case err, ok := <-w.Errors:
if !ok { // Channel was closed (i.e. Watcher.Close() was called).
return
}
printTime("ERROR: %s", err)
// Read from Events.
case e, ok := <-w.Events:
if !ok { // Channel was closed (i.e. Watcher.Close() was called).
return
}
// Just print the event nicely aligned, and keep track how many
// events we've seen.
i++
printTime("%3d %s", i, e)
}
}
}
|