-
Notifications
You must be signed in to change notification settings - Fork 1
/
watch.go
74 lines (70 loc) · 1.73 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
package watch
import (
"fmt"
"os"
"strconv"
"github.com/fsnotify/fsnotify"
"github.com/reenphygeorge/servette/internal/config-handle"
"github.com/reenphygeorge/servette/internal/logger"
"github.com/reenphygeorge/servette/internal/path"
"github.com/reenphygeorge/servette/internal/server"
)
/*
Watch all files in the provided path for changes.
If a new directory is created then it's path is added to watcher.
*/
func WatchFiles(pathList []string, htmlFiles *[]string, configObject config.Config, rootPath string) {
for _,htmlFile := range(*htmlFiles) {
fmt.Println("\033[33m\t",htmlFile,"\n\033[0m")
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
logger.Error("")
}
defer watcher.Close()
for _, path := range pathList {
err = watcher.Add(path)
if err != nil {
logger.Error("")
}
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
*htmlFiles = path.GetFilePaths(rootPath, configObject.SkipDirectories,1)
if event.Op&fsnotify.Create == fsnotify.Create {
isDir, _ := isDirectory(event.Name)
if isDir == true {
watcher.Add(event.Name)
}
} else if event.Op&fsnotify.Remove == fsnotify.Remove {
isDir, _ := isDirectory(event.Name)
if isDir == true {
watcher.Remove(event.Name)
}
}
logger.Reloading()
if server.GlobalConn != nil {
server.ReloadRequest()
} else {
logger.StartAndReload(strconv.Itoa(configObject.Port),htmlFiles)
}
case _, ok := <-watcher.Errors:
if !ok {
return
}
logger.Error("")
}
}
}
// Checks whether the newly created item is a directory or a file.
func isDirectory(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err != nil {
return false, err
}
return fileInfo.IsDir(), nil
}