/
cliconfig_env.go
105 lines (100 loc) · 2.13 KB
/
cliconfig_env.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
package config
import (
"os"
"path/filepath"
"github.com/admpub/godotenv"
"github.com/admpub/log"
"github.com/admpub/nging/v5/application/library/common"
"github.com/webx-top/com"
"github.com/webx-top/echo"
)
func findEnvFile() []string {
var envFiles []string
envFile := filepath.Join(echo.Wd(), `.env`)
if fi, err := os.Stat(envFile); err == nil && !fi.IsDir() {
envFiles = append(envFiles, envFile)
}
return envFiles
}
func (c *CLIConfig) InitEnviron(needFindEnvFile ...bool) (err error) {
c.envLock.Lock()
defer c.envLock.Unlock()
if len(needFindEnvFile) > 0 && needFindEnvFile[0] {
c.envFiles = findEnvFile()
}
var newEnvVars map[string]string
if len(c.envFiles) > 0 {
log.Infof(`Loading env file: %#v`, c.envFiles)
newEnvVars, err = godotenv.Read(c.envFiles...)
if err != nil {
return
}
}
if len(newEnvVars) == 0 {
if c.envVars == nil {
return
}
for k := range c.envVars {
log.Infof(`Unset env var: %s`, k)
os.Unsetenv(k)
}
c.envVars = nil
return
}
if c.envVars != nil {
for k, v := range c.envVars {
newV, ok := newEnvVars[k]
if !ok {
log.Infof(`Unset env var: %s`, k)
os.Unsetenv(k)
delete(c.envVars, k)
continue
}
if v != newV {
log.Infof(`Set env var: %s`, k)
os.Setenv(k, v)
c.envVars[k] = newV
}
delete(newEnvVars, k)
}
} else {
c.envVars = map[string]string{}
}
for k, v := range newEnvVars {
log.Infof(`Set env var: %s`, k)
os.Setenv(k, v)
c.envVars[k] = v
}
return
}
func (c *CLIConfig) WatchEnvConfig() {
if c.envMonitor != nil {
c.envMonitor.Close()
c.envMonitor = nil
}
if len(c.envFiles) == 0 {
return
}
c.envMonitor = &com.MonitorEvent{
Modify: func(file string) {
log.Info(`Start reloading env file: ` + file)
err := c.InitEnviron()
if err == nil {
log.Info(`Succcessfully reload the env file: ` + file)
return
}
if err == common.ErrIgnoreConfigChange {
log.Info(`No need to reload the env file: ` + file)
return
}
log.Error(err)
},
}
for _, envFile := range c.envFiles {
err := c.envMonitor.AddFile(envFile)
if err != nil {
log.Error(err)
}
}
c.envMonitor.Watch()
}