This repository has been archived by the owner on Jan 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
watch.go
115 lines (101 loc) · 2.59 KB
/
watch.go
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
package main
import (
"errors"
"log"
"os"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
)
type RecursiveWatcher struct {
*fsnotify.Watcher
Files chan string
Folders chan string
}
func NewRecursiveWatcher(path string) (*RecursiveWatcher, error) {
folders := Subfolders(path)
if len(folders) == 0 {
return nil, errors.New("No folders to watch.")
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
rw := &RecursiveWatcher{Watcher: watcher}
rw.Files = make(chan string, 10)
rw.Folders = make(chan string, len(folders))
for _, folder := range folders {
rw.AddFolder(folder)
}
return rw, nil
}
func (watcher *RecursiveWatcher) AddFolder(folder string) {
err := watcher.Add(folder)
if err != nil {
log.Println("Error watching: ", folder, err)
}
watcher.Folders <- folder
}
func (watcher *RecursiveWatcher) Run(debug bool) {
go func() {
for {
select {
case event := <-watcher.Events:
// create a file/directory
if event.Op&fsnotify.Create == fsnotify.Create {
fi, err := os.Stat(event.Name)
if err != nil {
// eg. stat .subl513.tmp : no such file or directory
if debug {
DebugError(err)
}
} else if fi.IsDir() {
if debug {
DebugMessage("Detected new directory %s", event.Name)
}
if !shouldIgnoreFile(filepath.Base(event.Name)) {
watcher.AddFolder(event.Name)
}
} else {
if debug {
DebugMessage("Detected new file %s", event.Name)
}
watcher.Files <- event.Name // created a file
}
}
if event.Op&fsnotify.Write == fsnotify.Write {
// modified a file, assuming that you don't modify folders
if debug {
DebugMessage("Detected file modification %s", event.Name)
}
watcher.Files <- event.Name
}
case err := <-watcher.Errors:
log.Println("error", err)
}
}
}()
}
// Subfolders returns a slice of subfolders (recursive), including the folder provided.
func Subfolders(path string) (paths []string) {
filepath.Walk(path, func(newPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
name := info.Name()
// skip folders that begin with a dot
if shouldIgnoreFile(name) && name != "." && name != ".." {
return filepath.SkipDir
}
paths = append(paths, newPath)
}
return nil
})
return paths
}
// shouldIgnoreFile determines if a file should be ignored.
// File names that begin with "." or "_" are ignored by the go tool.
func shouldIgnoreFile(name string) bool {
return strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_")
}