-
Notifications
You must be signed in to change notification settings - Fork 108
/
util.go
106 lines (93 loc) · 2.64 KB
/
util.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
package fs
import (
"errors"
"os"
"path"
"github.com/fsnotify/fsnotify"
"github.com/kardianos/osext"
"github.com/missdeer/avege/common"
)
// IsFileExists check if the file exists
func IsFileExists(path string) (bool, error) {
stat, err := os.Stat(path)
if err == nil {
if stat.Mode()&os.ModeType == 0 {
return true, nil
}
return false, errors.New(path + " exists but is not regular file")
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// GetConfigPath find the configuration file in some paths
func GetConfigPath(fileName string) (filePath string, err error) {
configFile := fileName
var binDir string
if exists, _ := IsFileExists(configFile); !exists {
if binDir, err = os.Getwd(); err == nil {
oldConfig := configFile
configFile = path.Join(binDir, fileName)
common.Warningf("%s not found, try file %s\n", oldConfig, configFile)
}
}
if exists, _ := IsFileExists(configFile); !exists {
oldConfig := configFile
configFile = path.Join(binDir, "conf", fileName)
common.Warningf("%s not found, try file %s\n", oldConfig, configFile)
}
if exists, _ := IsFileExists(configFile); !exists {
if executable, err := osext.Executable(); err == nil {
binDir = path.Dir(executable)
oldConfig := configFile
configFile = path.Join(binDir, fileName)
common.Warningf("%s not found, try file %s\n", oldConfig, configFile)
}
}
if exists, _ := IsFileExists(configFile); !exists {
oldConfig := configFile
configFile = path.Join(binDir, "conf", fileName)
common.Warningf("%s not found, try file %s\n", oldConfig, configFile)
}
if exists, _ := IsFileExists(configFile); !exists {
if executable, err := osext.Executable(); err == nil {
binDir = path.Dir(executable)
oldConfig := configFile
configFile = path.Join(binDir, "..", "assets", "conf", fileName)
common.Warningf("%s not found, try file %s\n", oldConfig, configFile)
}
}
if exists, _ := IsFileExists(configFile); !exists {
return "", errors.New("File not found")
}
return configFile, nil
}
// MonitorFileChanegs notify the channel if the file has been changed
func MonitorFileChanegs(path string, changed chan bool) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
common.Fatal(err)
return
}
err = watcher.Add(path)
if err != nil {
common.Fatal(err)
return
}
go func() {
defer watcher.Close()
for {
select {
case event := <-watcher.Events:
if (event.Op&fsnotify.Write == fsnotify.Write) ||
(event.Op&fsnotify.Rename == fsnotify.Rename) {
common.Debug("modified file:", event.Name)
changed <- true
}
case err := <-watcher.Errors:
common.Error("error:", err)
}
}
}()
}