-
Notifications
You must be signed in to change notification settings - Fork 1
/
watcher.go
104 lines (90 loc) · 1.94 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
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
package watcher
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/go-niom/niom/pkg/constants"
"github.com/go-niom/niom/pkg/logger"
"github.com/go-niom/niom/pkg/terminal"
"github.com/go-niom/niom/pkg/utils"
"github.com/gookit/color"
)
var (
WatcherChannel chan string
)
// init initializes the channel to watch changes in the files
func init() {
WatcherChannel = make(chan string, 1000)
}
func rebuildCheck() {
go func() {
for {
eventName := <-WatcherChannel
color.Bluep(constants.AppSign)
color.Greenp("Modified File: ")
println(eventName)
terminal.IsCodeUpdated = true
terminal.KillFunc()
}
}()
}
func watchFolder(path string, ext []string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Has(fsnotify.Write) {
if ext[0] != "*" {
for _, v := range ext {
if strings.HasSuffix(event.Name, v) {
WatcherChannel <- event.String()
}
}
} else {
WatcherChannel <- event.String()
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add(path)
if err != nil {
log.Fatal(err)
}
}
// Watch keep tracks of the files and notify when there are any changes in the files
func Watch(args []string) {
ext := []string{"*"}
if extensions := utils.ReadArgs("-e=", args); extensions != "" {
ext = strings.Split(extensions, ",")
}
logger.Info("watching path(s): *.*")
logger.Info(fmt.Sprintf("watching extensions: %v", ext))
rebuildCheck()
root := "."
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
if len(path) > 1 && strings.HasPrefix(filepath.Base(path), ".") {
println(path)
return filepath.SkipDir
}
watchFolder(path, ext)
}
return err
})
}