-
Notifications
You must be signed in to change notification settings - Fork 0
/
flags.go
101 lines (85 loc) · 1.61 KB
/
flags.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
package flags
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"io"
"log"
"strings"
"testing"
"github.com/jageros/goctl/util"
)
//go:embed default_en.json
var defaultEnFlagConfig []byte
type ConfigLoader struct {
conf map[string]any
}
func (cl *ConfigLoader) ReadConfig(in io.Reader) error {
return json.NewDecoder(in).Decode(&cl.conf)
}
func (cl *ConfigLoader) GetString(key string) string {
keyList := strings.FieldsFunc(key, func(r rune) bool {
return r == '.'
})
var conf = cl.conf
for idx, k := range keyList {
val, ok := conf[k]
if !ok {
return ""
}
if idx < len(keyList)-1 {
conf, ok = val.(map[string]any)
if !ok {
return ""
}
continue
}
return fmt.Sprint(val)
}
return ""
}
type Flags struct {
loader *ConfigLoader
}
func MustLoad() *Flags {
loader := &ConfigLoader{
conf: map[string]any{},
}
if err := loader.ReadConfig(bytes.NewBuffer(defaultEnFlagConfig)); err != nil {
log.Fatal(err)
}
return &Flags{
loader: loader,
}
}
func setTestData(t *testing.T, data []byte) {
origin := defaultEnFlagConfig
defaultEnFlagConfig = data
t.Cleanup(func() {
defaultEnFlagConfig = origin
})
}
func (f *Flags) Get(key string) (string, error) {
value := f.loader.GetString(key)
for util.IsTemplateVariable(value) {
value = util.TemplateVariable(value)
if value == key {
return "", fmt.Errorf("the variable can not be self: %q", key)
}
return f.Get(value)
}
return value, nil
}
var flags *Flags
func Get(key string) string {
if flags == nil {
flags = MustLoad()
}
v, err := flags.Get(key)
if err != nil {
log.Fatal(err)
return ""
}
return v
}