-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevwatch.go
More file actions
273 lines (233 loc) · 7.29 KB
/
devwatch.go
File metadata and controls
273 lines (233 loc) · 7.29 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package devwatch
import (
"path/filepath"
"sync"
"time"
"os"
"slices"
"github.com/fsnotify/fsnotify"
"github.com/tinywasm/depfind"
)
// FilesEventHandlers unifies asset and Go file event handling.
// It allows handlers to specify which file extensions they support and how to process them.
type FilesEventHandlers interface {
MainInputFileRelativePath() string // eg: go => "app/server/main.go" | js =>"app/pwa/public/main.js"
// NewFileEvent handles file events (create, remove, write, rename).
NewFileEvent(fileName, extension, filePath, event string) error
SupportedExtensions() []string // eg: [".go"], [".js",".css"], etc.
UnobservedFiles() []string // eg: main.exe, main.js
}
// event: create, remove, write, rename
type FolderEvent interface {
NewFolderEvent(folderName, path, event string) error
}
type WatchConfig struct {
//AppRootDir string // eg: "home/user/myNewApp"
FilesEventHandlers []FilesEventHandlers // All file event handlers are managed here
FolderEvents FolderEvent // when directories are created/removed for architecture detection
BrowserReload func() error // when change frontend files reload browser
ExitChan chan bool // global channel to signal the exit
UnobservedFiles func() []string // files that are not observed by the watcher eg: ".git", ".gitignore", ".vscode", "examples",
}
type DevWatch struct {
*WatchConfig
shouldWatch func() bool
watcher *fsnotify.Watcher
watcherMu sync.RWMutex
depFinder *depfind.GoDepFind // Dependency finder for Go projects
directories []string // directories to watch
no_add_to_watch map[string]bool
noAddMu sync.RWMutex
// reload timer to debounce browser reloads across multiple events
reloadTimer *time.Timer
reloadMutex sync.Mutex
log func(message ...any)
}
// Watcher returns the current fsnotify.Watcher in a thread-safe way.
func (dw *DevWatch) Watcher() *fsnotify.Watcher {
dw.watcherMu.RLock()
defer dw.watcherMu.RUnlock()
return dw.watcher
}
// SetWatcher sets the fsnotify.Watcher in a thread-safe way.
func (dw *DevWatch) SetWatcher(w *fsnotify.Watcher) {
dw.watcherMu.Lock()
defer dw.watcherMu.Unlock()
dw.watcher = w
}
func New(c *WatchConfig) *DevWatch {
dw := &DevWatch{
WatchConfig: c,
shouldWatch: func() bool { return false },
depFinder: depfind.New(),
directories: []string{},
}
return dw
}
// AddDirectoriesToWatch adds directories to be watched and updates the dependency finder
func (dw *DevWatch) AddDirectoriesToWatch(paths ...string) error {
var addedPaths []string
dw.watcherMu.Lock()
for _, path := range paths {
if path == "" {
continue
}
path, _ = filepath.Abs(path)
// Check for duplicates
exists := false
for _, dir := range dw.directories {
if dir == path {
exists = true
break
}
}
if !exists {
dw.directories = append(dw.directories, path)
// Update depFinder with the new root
dw.depFinder.AddRoot(path)
addedPaths = append(addedPaths, path)
}
}
dw.watcherMu.Unlock()
// If watcher is already running, add to fsnotify
// We do this OUTSIDE the lock to avoid potential deadlocks if scanAndRegisterDirectory acquires locks
if len(addedPaths) > 0 {
for _, path := range addedPaths {
// Check if watcher is initialized
if dw.Watcher() != nil {
if err := dw.scanAndRegisterDirectory(path); err != nil {
dw.Logger("Frontend Error: Failed to watch directory:", path, err)
}
}
}
}
return nil
}
// SetShouldWatch sets a function that determines if the file watcher should start.
func (dw *DevWatch) SetShouldWatch(f func() bool) {
dw.shouldWatch = f
}
func (dw *DevWatch) Name() string {
return "WATCH"
}
func (dw *DevWatch) SetLog(f func(message ...any)) {
dw.log = f
}
func (dw *DevWatch) Logger(messages ...any) {
if dw.log != nil {
dw.log(messages...)
}
}
// RemoveDirectoriesFromWatcher removes directories and their subdirectories from the watcher.
func (h *DevWatch) RemoveDirectoriesFromWatcher(paths ...string) error {
for _, path := range paths {
// Walk and remove all subdirectories recursively
err := filepath.Walk(path, func(subPath string, info os.FileInfo, err error) error {
if err != nil {
return nil // Continue despite errors
}
if info.IsDir() {
_ = h.removeDirectoryFromWatcher(subPath)
}
return nil
})
if err != nil {
return err
}
}
return nil
}
func (h *DevWatch) removeDirectoryFromWatcher(path string) error {
w := h.Watcher()
if w == nil {
return os.ErrInvalid
}
if err := w.Remove(path); err != nil {
// It's common to get errors if the path is not watched, so we might want to suppress some
// or just return it. For now, since this is "best effort" cleanup usually, we return it.
// h.Logger("Failed to remove directory from watcher:", path, err)
return err
}
return nil
}
func (h *DevWatch) addDirectoryToWatcher(path string, reg map[string]struct{}) error {
if _, exists := reg[path]; exists {
return nil // Already registered
}
w := h.Watcher()
if w == nil {
return os.ErrInvalid
}
if err := w.Add(path); err != nil {
h.Logger("Failed to add directory to watcher:", path, err)
return err
}
reg[path] = struct{}{}
//h.Logger("path added:", path)
// Get fileName once and reuse
fileName, err := GetFileName(path)
if err == nil {
// NOTIFY FOLDER EVENTS HANDLER FOR ARCHITECTURE DETECTION
if h.FolderEvents != nil {
err = h.FolderEvents.NewFolderEvent(fileName, path, "create")
if err != nil {
h.Logger("folder event error:", err)
}
}
}
if err != nil {
h.Logger("error addDirectoryToWatcher:", err)
}
return nil
}
// scanAndRegisterDirectory walks a directory, registers subdirectories, and simulates create events for existing files.
func (h *DevWatch) scanAndRegisterDirectory(rootDir string) error {
reg := make(map[string]struct{})
err := filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
h.Logger("accessing path error:", path, err)
return nil
}
if info.IsDir() && !h.Contain(path) {
if err := h.addDirectoryToWatcher(path, reg); err != nil {
// If watcher is closed or invalid, stop walking to prevent log spam
if err == os.ErrInvalid || err.Error() == "fsnotify: watcher already closed" {
return err
}
// For other errors (e.g. permission denied), just skip this dir
return nil
}
} else if !info.IsDir() {
// Check if this file should be ignored before processing
if h.Contain(path) {
return nil // Skip ignored files
}
// Process existing files during initial registration
fileName, ferr := GetFileName(path)
if ferr == nil {
extension := filepath.Ext(path)
for _, handler := range h.FilesEventHandlers {
if slices.Contains(handler.SupportedExtensions(), extension) {
var isMine = true
var herr error
if extension == ".go" {
isMine, herr = h.depFinder.ThisFileIsMine(handler.MainInputFileRelativePath(), path, "create")
if herr != nil {
//h.Logger("InitialRegistration go file error:", herr)
continue // Skip on error
}
}
if isMine {
err = handler.NewFileEvent(fileName, extension, path, "scan")
if err != nil {
h.Logger("InitialRegistration file error:", err)
}
}
}
}
}
}
return nil
})
return err
}