-
-
Notifications
You must be signed in to change notification settings - Fork 822
/
config.go
393 lines (348 loc) · 9.29 KB
/
config.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package runner
import (
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"time"
"dario.cat/mergo"
"github.com/pelletier/go-toml"
)
const (
dftTOML = ".air.toml"
dftConf = ".air.conf"
airWd = "air_wd"
)
// Config is the main configuration structure for Air.
type Config struct {
Root string `toml:"root"`
TmpDir string `toml:"tmp_dir"`
TestDataDir string `toml:"testdata_dir"`
Build cfgBuild `toml:"build"`
Color cfgColor `toml:"color"`
Log cfgLog `toml:"log"`
Misc cfgMisc `toml:"misc"`
Screen cfgScreen `toml:"screen"`
Proxy cfgProxy `toml:"proxy"`
}
type cfgBuild struct {
PreCmd []string `toml:"pre_cmd"`
Cmd string `toml:"cmd"`
PostCmd []string `toml:"post_cmd"`
Bin string `toml:"bin"`
FullBin string `toml:"full_bin"`
ArgsBin []string `toml:"args_bin"`
Log string `toml:"log"`
IncludeExt []string `toml:"include_ext"`
ExcludeDir []string `toml:"exclude_dir"`
IncludeDir []string `toml:"include_dir"`
ExcludeFile []string `toml:"exclude_file"`
IncludeFile []string `toml:"include_file"`
ExcludeRegex []string `toml:"exclude_regex"`
ExcludeUnchanged bool `toml:"exclude_unchanged"`
FollowSymlink bool `toml:"follow_symlink"`
Poll bool `toml:"poll"`
PollInterval int `toml:"poll_interval"`
Delay int `toml:"delay"`
StopOnError bool `toml:"stop_on_error"`
SendInterrupt bool `toml:"send_interrupt"`
KillDelay time.Duration `toml:"kill_delay"`
Rerun bool `toml:"rerun"`
RerunDelay int `toml:"rerun_delay"`
regexCompiled []*regexp.Regexp
}
func (c *cfgBuild) RegexCompiled() ([]*regexp.Regexp, error) {
if len(c.ExcludeRegex) > 0 && len(c.regexCompiled) == 0 {
c.regexCompiled = make([]*regexp.Regexp, 0, len(c.ExcludeRegex))
for _, s := range c.ExcludeRegex {
re, err := regexp.Compile(s)
if err != nil {
return nil, err
}
c.regexCompiled = append(c.regexCompiled, re)
}
}
return c.regexCompiled, nil
}
type cfgLog struct {
AddTime bool `toml:"time"`
MainOnly bool `toml:"main_only"`
}
type cfgColor struct {
Main string `toml:"main"`
Watcher string `toml:"watcher"`
Build string `toml:"build"`
Runner string `toml:"runner"`
App string `toml:"app"`
}
type cfgMisc struct {
CleanOnExit bool `toml:"clean_on_exit"`
}
type cfgScreen struct {
ClearOnRebuild bool `toml:"clear_on_rebuild"`
KeepScroll bool `toml:"keep_scroll"`
}
type cfgProxy struct {
Enabled bool `toml:"enabled"`
ProxyPort int `toml:"proxy_port"`
AppPort int `toml:"app_port"`
}
type sliceTransformer struct{}
func (t sliceTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
if typ.Kind() == reflect.Slice {
return func(dst, src reflect.Value) error {
if !src.IsZero() {
dst.Set(src)
}
return nil
}
}
return nil
}
// InitConfig initializes the configuration.
func InitConfig(path string) (cfg *Config, err error) {
if path == "" {
cfg, err = defaultPathConfig()
if err != nil {
return nil, err
}
} else {
cfg, err = readConfigOrDefault(path)
if err != nil {
return nil, err
}
}
config := defaultConfig()
// get addr
ret := &config
err = mergo.Merge(ret, cfg, func(config *mergo.Config) {
// mergo.Merge will overwrite the fields if it is Empty
// So need use this to avoid that none-zero slice will be overwritten.
// https://dario.cat/mergo#transformers
config.Transformers = sliceTransformer{}
config.Overwrite = true
})
if err != nil {
return nil, err
}
err = ret.preprocess()
return ret, err
}
func writeDefaultConfig() (string, error) {
confFiles := []string{dftTOML, dftConf}
for _, fname := range confFiles {
fstat, err := os.Stat(fname)
if err != nil && !os.IsNotExist(err) {
return "", fmt.Errorf("failed to check for existing configuration: %w", err)
}
if err == nil && fstat != nil {
return "", errors.New("configuration already exists")
}
}
file, err := os.Create(dftTOML)
if err != nil {
return "", fmt.Errorf("failed to create a new configuration: %w", err)
}
defer file.Close()
config := defaultConfig()
configFile, err := toml.Marshal(config)
if err != nil {
return "", fmt.Errorf("failed to marshal the default configuration: %w", err)
}
_, err = file.Write(configFile)
if err != nil {
return "", fmt.Errorf("failed to write to %s: %w", dftTOML, err)
}
return dftTOML, nil
}
func defaultPathConfig() (*Config, error) {
// when path is blank, first find `.air.toml`, `.air.conf` in `air_wd` and current working directory, if not found, use defaults
for _, name := range []string{dftTOML, dftConf} {
cfg, err := readConfByName(name)
if err == nil {
if name == dftConf {
fmt.Println("`.air.conf` will be deprecated soon, recommend using `.air.toml`.")
}
return cfg, nil
}
}
dftCfg := defaultConfig()
return &dftCfg, nil
}
func readConfByName(name string) (*Config, error) {
var path string
if wd := os.Getenv(airWd); wd != "" {
path = filepath.Join(wd, name)
} else {
wd, err := os.Getwd()
if err != nil {
return nil, err
}
path = filepath.Join(wd, name)
}
cfg, err := readConfig(path)
return cfg, err
}
func defaultConfig() Config {
build := cfgBuild{
Cmd: "go build -o ./tmp/main .",
Bin: "./tmp/main",
Log: "build-errors.log",
IncludeExt: []string{"go", "tpl", "tmpl", "html"},
IncludeDir: []string{},
PreCmd: []string{},
PostCmd: []string{},
ExcludeFile: []string{},
IncludeFile: []string{},
ExcludeDir: []string{"assets", "tmp", "vendor", "testdata"},
ArgsBin: []string{},
ExcludeRegex: []string{"_test.go"},
Delay: 1000,
Rerun: false,
RerunDelay: 500,
}
if runtime.GOOS == PlatformWindows {
build.Bin = `tmp\main.exe`
build.Cmd = "go build -o ./tmp/main.exe ."
}
log := cfgLog{
AddTime: false,
MainOnly: false,
}
color := cfgColor{
Main: "magenta",
Watcher: "cyan",
Build: "yellow",
Runner: "green",
}
misc := cfgMisc{
CleanOnExit: false,
}
return Config{
Root: ".",
TmpDir: "tmp",
TestDataDir: "testdata",
Build: build,
Color: color,
Log: log,
Misc: misc,
Screen: cfgScreen{
ClearOnRebuild: false,
KeepScroll: true,
},
}
}
func readConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
cfg := new(Config)
if err = toml.Unmarshal(data, cfg); err != nil {
return nil, err
}
return cfg, nil
}
func readConfigOrDefault(path string) (*Config, error) {
dftCfg := defaultConfig()
cfg, err := readConfig(path)
if err != nil {
return &dftCfg, err
}
return cfg, nil
}
func (c *Config) preprocess() error {
var err error
cwd := os.Getenv(airWd)
if cwd != "" {
if err = os.Chdir(cwd); err != nil {
return err
}
c.Root = cwd
}
c.Root, err = expandPath(c.Root)
if err != nil {
return err
}
if c.TmpDir == "" {
c.TmpDir = "tmp"
}
if c.TestDataDir == "" {
c.TestDataDir = "testdata"
}
if err != nil {
return err
}
ed := c.Build.ExcludeDir
for i := range ed {
ed[i] = cleanPath(ed[i])
}
adaptToVariousPlatforms(c)
// Join runtime arguments with the configuration arguments
runtimeArgs := flag.Args()
c.Build.ArgsBin = append(c.Build.ArgsBin, runtimeArgs...)
c.Build.ExcludeDir = ed
if len(c.Build.FullBin) > 0 {
c.Build.Bin = c.Build.FullBin
return err
}
// Fix windows CMD processor
// CMD will not recognize relative path like ./tmp/server
c.Build.Bin, err = filepath.Abs(c.Build.Bin)
return err
}
func (c *Config) colorInfo() map[string]string {
return map[string]string{
"main": c.Color.Main,
"build": c.Color.Build,
"runner": c.Color.Runner,
"watcher": c.Color.Watcher,
}
}
func (c *Config) buildLogPath() string {
return filepath.Join(c.tmpPath(), c.Build.Log)
}
func (c *Config) buildDelay() time.Duration {
return time.Duration(c.Build.Delay) * time.Millisecond
}
func (c *Config) rerunDelay() time.Duration {
return time.Duration(c.Build.RerunDelay) * time.Millisecond
}
func (c *Config) killDelay() time.Duration {
// kill_delay can be specified as an integer or duration string
// interpret as milliseconds if less than the value of 1 millisecond
if c.Build.KillDelay < time.Millisecond {
return c.Build.KillDelay * time.Millisecond
}
// normalize kill delay to milliseconds
return time.Duration(c.Build.KillDelay.Milliseconds()) * time.Millisecond
}
func (c *Config) binPath() string {
return filepath.Join(c.Root, c.Build.Bin)
}
func (c *Config) tmpPath() string {
return filepath.Join(c.Root, c.TmpDir)
}
func (c *Config) testDataPath() string {
return filepath.Join(c.Root, c.TestDataDir)
}
func (c *Config) rel(path string) string {
s, err := filepath.Rel(c.Root, path)
if err != nil {
return ""
}
return s
}
// WithArgs returns a new config with the given arguments added to the configuration.
func (c *Config) WithArgs(args map[string]TomlInfo) {
for _, value := range args {
if value.Value != nil && *value.Value != unsetDefault {
v := reflect.ValueOf(c)
setValue2Struct(v, value.fieldPath, *value.Value)
}
}
}