aboutsummaryrefslogtreecommitdiff
path: root/internal/watcher/fsnotify.go
blob: 72519075d30e5fa664730af8f7ae919fc1295548 (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
package watcher

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/fsnotify/fsnotify"
)

// Run starts watching the configured roots.
//
// Filesystem events are currently logged for debugging.
// Future commits will debounce these events and invoke OnChange.
func (w *Watcher) Run(ctx context.Context) error {
	fswatcher, err := fsnotify.NewWatcher()
	if err != nil {
		return fmt.Errorf("create watcher: %w", err)
	}
	defer func() {
		_ = fswatcher.Close()
	}()

	for _, root := range w.config.Roots {
		if err := watchTree(fswatcher, root); err != nil {
			return err
		}
	}

	for {
		select {
		case <-ctx.Done():
			return nil

		case event, ok := <-fswatcher.Events:
			if !ok {
				return nil
			}

			log.Printf("watcher: %v %s", event.Op, event.Name)

			if !event.Has(fsnotify.Create) {
				continue
			}

			info, err := os.Stat(event.Name)
			if err != nil {
				continue
			}

			if !info.IsDir() {
				continue
			}

			if err := watchTree(fswatcher, event.Name); err != nil {
				log.Printf("watch new directory: %v", err)
			}

		case err, ok := <-fswatcher.Errors:
			if !ok {
				return nil
			}

			log.Printf("watcher error: %v", err)
		}
	}
}