-
Notifications
You must be signed in to change notification settings - Fork 1
/
configurer.go
268 lines (222 loc) · 6.55 KB
/
configurer.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
// MIT License
//
// Copyright (c) 2022 Spiral Scout
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package config
import (
"bytes"
"errors"
"fmt"
"github.com/spf13/viper"
"os"
"path/filepath"
"strings"
"time"
)
const (
OpNew = "configurer: new ->"
OpUnmarshalKey = "configurer: unmarshal key ->"
OpUnmarshal = "configurer: unmarshal ->"
OpOverwrite = "configurer: overwrite ->"
OpParseFlag = "configurer: parse flag ->"
)
type Configurer interface {
// UnmarshalKey takes a single key and unmarshal it into a Struct.
UnmarshalKey(name string, out any) error
// Unmarshal the config into a Struct. Make sure that the tags
// on the fields of the structure are properly set.
Unmarshal(out any) error
// Overwrite used to overwrite particular values in the unmarshalled config
Overwrite(values map[string]any) error
// Get used to get config section
Get(name string) any
// Has checks if config section exists.
Has(name string) bool
GracefulTimeout() time.Duration
// Version returns current version
Version() string
}
type Option func(*configurer)
type configurer struct {
viper *viper.Viper
path string
prefix string
tp string
readInCfg []byte
// user defined Flags in the form of <option>.<key> = <value>
// which overwrites initial config key
flags []string
// Timeout ...
timeout time.Duration
version string
}
func WithPath(path string) Option {
return func(c *configurer) {
c.path = path
}
}
func WithPrefix(prefix string) Option {
return func(c *configurer) {
c.prefix = prefix
}
}
func WithConfigType(tp string) Option {
return func(c *configurer) {
c.tp = tp
}
}
func WithReadInCfg(readInCfg []byte) Option {
return func(c *configurer) {
c.readInCfg = readInCfg
}
}
func WithFlags(flags []string) Option {
return func(c *configurer) {
c.flags = flags
}
}
func NewConfigurer(version string, timeout time.Duration, options ...Option) (Configurer, error) {
c := &configurer{viper: viper.New(), timeout: timeout, version: version}
for _, opt := range options {
opt(c)
}
// If user provided []byte data with config, read it and ignore Path and Prefix
if c.readInCfg != nil && c.tp != "" {
c.viper.SetConfigType(c.tp)
err := c.viper.ReadConfig(bytes.NewBuffer(c.readInCfg))
return c, err
}
// read in environment variables that match
c.viper.AutomaticEnv()
if c.prefix == "" {
return nil, fmt.Errorf("%s prefix should be set", OpNew)
}
c.viper.SetEnvPrefix(c.prefix)
c.viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
if c.path == "" {
ex, err := os.Executable()
if err != nil {
return nil, fmt.Errorf("%s %w", OpNew, err)
}
c.viper.AddConfigPath(filepath.Dir(ex))
c.viper.AddConfigPath(filepath.Join("/", "etc", filepath.Base(ex)))
} else {
c.viper.SetConfigFile(c.path)
}
err := c.viper.ReadInConfig()
if err != nil {
return nil, fmt.Errorf("%s %w", OpNew, err)
}
// automatically inject ENV variables using ${ENV} pattern
for _, key := range c.viper.AllKeys() {
val := c.viper.Get(key)
switch t := val.(type) {
case string:
// for string just expand it
c.viper.Set(key, parseEnvDefault(t))
case []any:
// for slice -> check if it's slice of strings
strArr := make([]string, 0, len(t))
for i := 0; i < len(t); i++ {
if valStr, ok := t[i].(string); ok {
strArr = append(strArr, parseEnvDefault(valStr))
continue
}
c.viper.Set(key, val)
}
// we should set the whole array
if len(strArr) > 0 {
c.viper.Set(key, strArr)
}
default:
c.viper.Set(key, val)
}
}
// override config flags
if len(c.flags) > 0 {
for _, f := range c.flags {
key, val, errP := parseFlag(f)
if errP != nil {
return nil, fmt.Errorf("%s %w", OpNew, errP)
}
c.viper.Set(key, parseEnvDefault(val))
}
}
return c, nil
}
func (cfg *configurer) UnmarshalKey(name string, out any) error {
if err := cfg.viper.UnmarshalKey(name, out); err != nil {
return fmt.Errorf("%s %w", OpUnmarshalKey, err)
}
return nil
}
func (cfg *configurer) Unmarshal(out any) error {
if err := cfg.viper.Unmarshal(out); err != nil {
return fmt.Errorf("%s %w", OpUnmarshal, err)
}
return nil
}
func (cfg *configurer) Overwrite(values map[string]any) error {
for key, value := range values {
cfg.viper.Set(key, value)
}
return nil
}
func (cfg *configurer) Get(name string) any {
return cfg.viper.Get(name)
}
func (cfg *configurer) Has(name string) bool {
return cfg.viper.IsSet(name)
}
func (cfg *configurer) Version() string {
return cfg.version
}
func (cfg *configurer) GracefulTimeout() time.Duration {
return cfg.timeout
}
func parseFlag(flag string) (string, string, error) {
if !strings.Contains(flag, "=") {
return "", "", fmt.Errorf("%s invalid flag `%s`", OpParseFlag, flag)
}
parts := strings.SplitN(strings.TrimLeft(flag, " \"'`"), "=", 2)
if len(parts) < 2 {
return "", "", errors.New("usage: -o key=value")
}
if parts[0] == "" {
return "", "", errors.New("key should not be empty")
}
if parts[1] == "" {
return "", "", errors.New("value should not be empty")
}
return strings.Trim(parts[0], " \n\t"), parseValue(strings.Trim(parts[1], " \n\t")), nil
}
func parseValue(value string) string {
escape := []rune(value)[0]
if escape == '"' || escape == '\'' || escape == '`' {
value = strings.Trim(value, string(escape))
value = strings.ReplaceAll(value, fmt.Sprintf("\\%s", string(escape)), string(escape))
}
return value
}
func parseEnvDefault(val string) string {
// tcp://127.0.0.1:${RPC_PORT:-36643}
// for envs like this, part would be tcp://127.0.0.1:
return ExpandVal(val, os.Getenv)
}