all repos — erl @ c8ab7c849959313a035bf9e448d110e794190a4f

Execute Reload Loop

watcher/watcher.go (view raw)

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package watcher

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"slices"

	"github.com/fsnotify/fsnotify"
)

type Event fsnotify.Event

type Watcher interface {
	AddRecursive(pathname string) error
	Monitor() (<-chan Event, <-chan error)
	WatchList() []string
	Remove(pathname string) error
	Close() error
}

// FSWatcher implements the Watcher interface using fsnotify.
type FSWatcher struct {
	watcher fsnotify.Watcher
}

var IgnoredDirs = []string{
	".git",
}

func New() (*FSWatcher, error) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, fmt.Errorf("failed to create watcher: %v", err)
	}

	return &FSWatcher{
		watcher: *watcher,
	}, nil
}

func (w *FSWatcher) AddRecursive(pathname string) error {
	stat, err := os.Stat(pathname)
	if err != nil {
		return fmt.Errorf("failed to stat %s: %v", pathname, err)
	}
	if !stat.IsDir() {
		pathname = filepath.Dir(pathname)
	}

	return w.addDirRecursive(pathname)
}

func (w *FSWatcher) Remove(pathname string) error {
	return w.watcher.Remove(pathname)
}

func (w *FSWatcher) Monitor() (<-chan Event, <-chan error) {
	events := make(chan Event, 1)
	errors := make(chan error, 1)

	go func() {
		for {
			select {
			case event := <-w.watcher.Events:
				events <- Event(event)
			case err := <-w.watcher.Errors:
				errors <- err
			}
		}
	}()

	return events, errors
}

func (w *FSWatcher) WatchList() []string {
	return w.watcher.WatchList()
}

func (w *FSWatcher) Close() error {
	return w.watcher.Close()
}

func (w *FSWatcher) addDirRecursive(dir string) error {
	err := filepath.Walk(dir, func(path string, entry fs.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if entry.IsDir() {
			if slices.Contains(IgnoredDirs, entry.Name()) {
				return fs.SkipDir
			}

			err = w.watcher.Add(path)
			if err != nil {
				return fmt.Errorf("failed to add directory to watcher: %v", err)
			}
		}

		return nil
	})
	if err != nil {
		return fmt.Errorf("failed to walk directory: %v", err)
	}

	return nil
}