forked from wailsapp/wails
/
watcher.go
67 lines (54 loc) · 1.47 KB
/
watcher.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
package dev
import (
"bufio"
"os"
"path/filepath"
"github.com/frankfang/wails/v2/internal/fs"
"github.com/fsnotify/fsnotify"
gitignore "github.com/sabhiram/go-gitignore"
"github.com/samber/lo"
)
type Watcher interface {
Add(name string) error
}
// initialiseWatcher creates the project directory watcher that will trigger recompile
func initialiseWatcher(cwd string) (*fsnotify.Watcher, error) {
// Ignore dot files, node_modules and build directories by default
ignoreDirs := getIgnoreDirs(cwd)
// Get all subdirectories
dirs, err := fs.GetSubdirectories(cwd)
if err != nil {
return nil, err
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
for _, dir := range processDirectories(dirs.AsSlice(), ignoreDirs) {
err := watcher.Add(dir)
if err != nil {
return nil, err
}
println("watching: " + dir)
}
return watcher, nil
}
func getIgnoreDirs(cwd string) []string {
ignoreDirs := []string{filepath.Join(cwd, "build/*"), ".*", "node_modules"}
// Read .gitignore into ignoreDirs
f, err := os.Open(filepath.Join(cwd, ".gitignore"))
if err == nil {
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
ignoreDirs = append(ignoreDirs, line)
}
}
return lo.Uniq(ignoreDirs)
}
func processDirectories(dirs []string, ignoreDirs []string) []string {
ignorer := gitignore.CompileIgnoreLines(ignoreDirs...)
return lo.Filter(dirs, func(dir string, _ int) bool {
return !ignorer.MatchesPath(dir)
})
}