Debian Codegraph @

cmd/atomdns/internal/dnszone/watch.go

raw
1 package dnszone
2
3 import (
4 "context"
5 "fmt"
6 "math"
7 "path"
8 "path/filepath"
9 "time"
10
11 "github.com/fsnotify/fsnotify"
12 )
13
14 // Watch watches the containing directory of file, and executes fn once a write event happens that matches file.
15 // Specifically it performs fn() after fsnotify.Write, fsnotify.Rename, and fsnotify.Create.
16 func Watch(ctx context.Context, file string, fn func()) error {
17 watcher, err := fsnotify.NewWatcher()
18 if err != nil {
19 return fmt.Errorf("failed to set up watcher for %s: %w", file, err)
20 }
21 file = path.Clean(file)
22 timer := time.AfterFunc(math.MaxInt64, fn)
23
24 go func() {
25 for {
26 select {
27 case event, ok := <-watcher.Events:
28 if !ok {
29 continue
30 }
31 switch {
32 default:
33
34 case event.Has(fsnotify.Write):
35 fallthrough
36 case event.Has(fsnotify.Create):
37 fallthrough
38 case event.Has(fsnotify.Rename):
39 if file == path.Clean(event.Name) {
40 timer.Reset(2 * time.Second)
41 }
42 }
43 case _, ok := <-watcher.Errors:
44 if !ok {
45 continue
46 }
47 case <-ctx.Done():
48 watcher.Close()
49 return
50 }
51 }
52 }()
53
54 if err = watcher.Add(filepath.Dir(file)); err != nil {
55 return fmt.Errorf("failed to set up watcher for %s: %w", file, err)
56 }
57 return nil
58 }