-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatch.go
More file actions
444 lines (383 loc) · 11.5 KB
/
Copy pathwatch.go
File metadata and controls
444 lines (383 loc) · 11.5 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"sync"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
ignore "github.com/sabhiram/go-gitignore"
"github.com/sirupsen/logrus"
)
var version = "0.1.0"
var (
excludeRegexps compiledPatterns
excludeIgnorers []*ignore.GitIgnore
defaultExcludes = []string{
`/\.git(/|$)`, // .git directory
`(^|/)\.[^/]+(/|$)`, // hidden files/directories starting with .
}
defaultEvents = []string{"write", "create"}
monitoredEvents fsnotify.Op
clearScreen bool
quiet bool
noKill bool
noFollowSymlinks bool
logger = logrus.New()
runningCmd *exec.Cmd
runningMutex sync.Mutex
)
func main() {
// Define flags
showVersion := flag.Bool("version", false, "Show version information")
runOnceFirst := flag.Bool("run-once-first", false, "Run command once before starting to monitor files")
clearScreenFlag := flag.Bool("clear-screen", false, "Clear the screen before each command execution")
debugFlag := flag.Bool("debug", false, "Print debug information about watch's file events to stderr")
quietFlag := flag.Bool("quiet-command", false, "Suppress command output")
var excludes excludePatterns
flag.Var(&excludes, "exclude", "Exclude paths matching this regexp (can be specified multiple times). Default excludes: /\\.git(/|$) and (^|/)\\.[^/]+(/|$)")
var excludeFiles excludePatterns
flag.Var(&excludeFiles, "exclude-file", "Read exclude patterns from file in .gitignore format (can be specified multiple times). Default: .gitignore")
noDefaultExclude := flag.Bool("no-default-exclude", false, "Don't use default exclusions (.git, hidden files, and .gitignore)")
var events eventPatterns
flag.Var(&events, "event", "Event types to monitor: write, create, chmod, rename, remove (can be specified multiple times)")
noDefaultEvents := flag.Bool("no-default-events", false, "Don't use default events (write, create)")
noKillFlag := flag.Bool("no-kill", false, "Don't kill running command when new changes detected")
noFollowSymlinksFlag := flag.Bool("no-follow-symlinks", false, "Don't follow symlinks when watching paths")
flag.Parse()
if *showVersion {
fmt.Printf("watch version %s\n", version)
os.Exit(0)
}
clearScreen = *clearScreenFlag
quiet = *quietFlag
noKill = *noKillFlag
noFollowSymlinks = *noFollowSymlinksFlag
// Configure logrus
logger.SetOutput(os.Stderr)
logger.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05.000",
DisableColors: false,
})
if *debugFlag {
logger.SetLevel(logrus.DebugLevel)
} else {
logger.SetLevel(logrus.InfoLevel)
}
// Get remaining arguments after flags
args := flag.Args()
if len(args) < 2 {
fmt.Printf("watch version %s\n", version)
fmt.Println("Usage: watch [--version] [--run-once-first] [--clear-screen] [--debug] [--quiet-command] [--no-kill] [--no-follow-symlinks] [--exclude <pattern>] [--exclude-file <file>] [--no-default-exclude] [--event <type>] [--no-default-events] <path> [<path> ...] <command>")
os.Exit(1)
}
// Build monitored events
var eventList []string
if !*noDefaultEvents {
eventList = append(eventList, defaultEvents...)
}
eventList = append(eventList, events...)
var err error
monitoredEvents, err = parseEvents(eventList)
if err != nil {
log.Fatal(err)
}
logger.Debugf("monitoring events: %s", monitoredEvents)
// Build exclusion patterns
var patterns []string
if !*noDefaultExclude {
patterns = append(patterns, defaultExcludes...)
}
// Add user-specified exclusions
patterns = append(patterns, excludes...)
// Add patterns from default exclude file (.gitignore)
if !*noDefaultExclude {
if _, err := os.Stat(".gitignore"); err == nil {
logger.Debugf("reading exclude patterns from default file: .gitignore")
ignorer, err := ignore.CompileIgnoreFile(".gitignore")
if err != nil {
log.Fatalf("Error reading default exclude file .gitignore: %v", err)
}
excludeIgnorers = append(excludeIgnorers, ignorer)
logger.Debugf("loaded gitignore patterns from .gitignore")
}
}
// Add patterns from exclude files using gitignore library
for _, excludeFile := range excludeFiles {
logger.Debugf("reading exclude patterns from file: %s", excludeFile)
ignorer, err := ignore.CompileIgnoreFile(excludeFile)
if err != nil {
log.Fatalf("Error reading exclude file %s: %v", excludeFile, err)
}
excludeIgnorers = append(excludeIgnorers, ignorer)
logger.Debugf("loaded gitignore patterns from %s", excludeFile)
}
// Compile all exclusion patterns
excludeRegexps, err = compilePatterns(patterns)
if err != nil {
log.Fatal(err)
}
// All args except last are paths
paths := args[0 : len(args)-1]
// Last arg is command
command := args[len(args)-1]
// Create file watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
// Add paths to watcher recursively
for _, path := range paths {
logger.Debugf("adding watch path: %s", path)
err := addPathRecursively(watcher, path)
if err != nil {
log.Printf("Error adding path %s: %v", path, err)
}
}
// Run command initially if flag is set
if *runOnceFirst {
runCommand(command)
}
// Debounce events to avoid running command multiple times for rapid changes
debounceTimer := time.NewTimer(0)
<-debounceTimer.C // Drain the initial timer
var pendingEvent bool
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
logger.Debugf("event: %s %s", event.Op, event.Name)
// Filter out excluded paths and specific event types
if shouldIgnore(event.Name) {
logger.Debugf("ignoring excluded path: %s", event.Name)
continue
}
// Check if this event type should trigger command execution
if shouldTrigger(event.Op) {
logger.Debugf("triggering command due to %s on %s", event.Op, event.Name)
pendingEvent = true
debounceTimer.Reset(100 * time.Millisecond)
} else {
logger.Debugf("ignoring %s event on %s (not in monitored events: %s)", event.Op, event.Name, monitoredEvents)
}
// If a new directory is created, add it to the watcher
if event.Op&fsnotify.Create == fsnotify.Create {
if info, err := os.Stat(event.Name); err == nil && info.IsDir() {
logger.Debugf("adding new directory to watcher: %s", event.Name)
addPathRecursively(watcher, event.Name)
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("Error:", err)
case <-debounceTimer.C:
if pendingEvent {
logger.Debug("running command after debounce")
if noKill {
runCommand(command)
} else {
go runCommand(command)
}
pendingEvent = false
}
}
}
}
func killRunningCommand() {
runningMutex.Lock()
defer runningMutex.Unlock()
if runningCmd == nil || runningCmd.Process == nil {
return
}
logger.Debug("killing running command")
// Kill the process group to include child processes
syscall.Kill(-runningCmd.Process.Pid, syscall.SIGTERM)
runningCmd.Wait()
runningCmd = nil
}
func runCommand(command string) {
// Kill any running command first (unless --no-kill is set)
if !noKill {
killRunningCommand()
}
// Clear the screen if the flag is set
if clearScreen {
fmt.Print("\033[H\033[2J")
}
cmd := exec.Command("sh", "-c", command)
// Set process group so we can kill child processes
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if quiet {
// Discard output when quiet mode is enabled
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
} else {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
cmd.Stdin = os.Stdin
runningMutex.Lock()
runningCmd = cmd
runningMutex.Unlock()
err := cmd.Run()
runningMutex.Lock()
runningCmd = nil
runningMutex.Unlock()
if err != nil {
// Don't log if the command was killed by us
if exitErr, ok := err.(*exec.ExitError); ok {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
if status.Signaled() && status.Signal() == syscall.SIGTERM {
logger.Debug("command was terminated")
return
}
}
}
log.Printf("Command failed: %v", err)
}
}
func addPathRecursively(watcher *fsnotify.Watcher, root string) error {
// Resolve symlinks unless disabled
if !noFollowSymlinks {
resolved, err := filepath.EvalSymlinks(root)
if err == nil && resolved != root {
logger.Debugf("resolved symlink: %s -> %s", root, resolved)
root = resolved
}
}
info, err := os.Stat(root)
if err != nil {
return err
}
// If root is a file, add it directly
if !info.IsDir() {
if shouldIgnore(root) {
return nil
}
err := watcher.Add(root)
if err != nil {
return err
}
logger.Debugf("monitoring: %s", root)
return nil
}
// For directories, walk recursively
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Follow symlinks to directories unless disabled
if !noFollowSymlinks && info.Mode()&os.ModeSymlink != 0 {
resolved, err := filepath.EvalSymlinks(path)
if err == nil {
resolvedInfo, err := os.Stat(resolved)
if err == nil && resolvedInfo.IsDir() {
logger.Debugf("following symlink: %s -> %s", path, resolved)
return addPathRecursively(watcher, resolved)
}
}
}
// Skip excluded directories
if info.IsDir() && shouldIgnore(path) {
return filepath.SkipDir
}
// Watch directories (fsnotify will notify about files in them)
if info.IsDir() {
err := watcher.Add(path)
if err != nil {
return err
}
logger.Debugf("monitoring: %s", path)
}
return nil
})
}
func shouldIgnore(path string) bool {
// Check regex patterns (from --exclude flag and default excludes)
if excludeRegexps.matchesAny(path) {
return true
}
// Check gitignore patterns (from --exclude-file flag)
for _, ignorer := range excludeIgnorers {
if ignorer.MatchesPath(path) {
return true
}
}
return false
}
// excludePatterns holds multiple exclude patterns
type excludePatterns []string
func (e *excludePatterns) String() string {
return fmt.Sprintf("%v", *e)
}
func (e *excludePatterns) Set(value string) error {
*e = append(*e, value)
return nil
}
func compilePatterns(patterns []string) (compiledPatterns, error) {
regexps := make(compiledPatterns, 0, len(patterns))
for _, pattern := range patterns {
re, err := regexp.Compile(pattern)
if err != nil {
return nil, fmt.Errorf("invalid pattern '%s': %w", pattern, err)
}
regexps = append(regexps, re)
}
return regexps, nil
}
// compiledPatterns holds compiled regular expressions
type compiledPatterns []*regexp.Regexp
func (cp compiledPatterns) matchesAny(path string) bool {
for _, re := range cp {
if re.MatchString(path) {
return true
}
}
return false
}
// eventPatterns holds multiple event type patterns
type eventPatterns []string
func (e *eventPatterns) String() string {
return fmt.Sprintf("%v", *e)
}
func (e *eventPatterns) Set(value string) error {
*e = append(*e, value)
return nil
}
// parseEvents converts event type strings to fsnotify.Op bitwise flags
func parseEvents(eventList []string) (fsnotify.Op, error) {
var ops fsnotify.Op
for _, event := range eventList {
switch event {
case "write":
ops |= fsnotify.Write
case "create":
ops |= fsnotify.Create
case "chmod":
ops |= fsnotify.Chmod
case "rename":
ops |= fsnotify.Rename
case "remove":
ops |= fsnotify.Remove
default:
return 0, fmt.Errorf("unknown event type '%s' (valid: write, create, chmod, rename, remove)", event)
}
}
return ops, nil
}
// shouldTrigger checks if the event type should trigger command execution
func shouldTrigger(op fsnotify.Op) bool {
return op&monitoredEvents != 0
}