Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cmd/fsnotify #463

Merged
merged 1 commit into from Jul 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Expand Up @@ -76,6 +76,11 @@ func main() {
}
```

A slightly more expansive example can be found in [cmd/fsnotify](cmd/fsnotify), which can be run with:

# Watch the current directory (not recursive).
$ go run ./cmd/fsnotify .

## Contributing

Please refer to [CONTRIBUTING][] before opening an issue or pull request.
Expand Down
67 changes: 67 additions & 0 deletions cmd/fsnotify/main.go
@@ -0,0 +1,67 @@
package main

import (
"errors"
"fmt"
"os"
"path/filepath"
"time"

"github.com/fsnotify/fsnotify"
)

func fatal(err error) {
if err == nil {
return
}
fmt.Fprintf(os.Stderr, "%s: %s\n", filepath.Base(os.Args[0]), err)
os.Exit(1)
}

func line(s string, args ...interface{}) {
fmt.Printf(time.Now().Format("15:16:05.0000")+" "+s+"\n", args...)
}

func main() {
if len(os.Args) < 2 {
fatal(errors.New("must specify at least one path to watch"))
}

w, err := fsnotify.NewWatcher()
fatal(err)
defer w.Close()

go func() {
i := 0
for {
select {
case e, ok := <-w.Events:
if !ok {
return
}

i++
m := ""
if e.Op&fsnotify.Write == fsnotify.Write {
m = "(modified)"
}
line("%3d %-10s %-10s %q", i, e.Op, m, e.Name)
case err, ok := <-w.Errors:
if !ok {
return
}
line("ERROR: %s", err)
}
}
}()

for _, p := range os.Args[1:] {
err = w.Add(p)
if err != nil {
fatal(fmt.Errorf("%q: %w", p, err))
}
}

line("watching; press ^C to exit")
<-make(chan struct{})
}