-
Notifications
You must be signed in to change notification settings - Fork 37
/
config_attribute.go
109 lines (97 loc) · 2.3 KB
/
config_attribute.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
package config
import (
"fmt"
"os"
"reflect"
"strconv"
)
type Source struct {
Type SourceType `json:"type"`
Name string `json:"name,omitempty"`
}
func (s *Source) String() string {
if s.Name == "" {
return string(s.Type)
}
return fmt.Sprintf("%s %s", s.Name, s.Type)
}
type SourceType string
const (
SourceEnv SourceType = "environment variable"
SourceFile SourceType = "config file"
SourceDynamicConfig SourceType = "dynamic configuration"
)
// ConfigAttribute provides generic way to work with Config configuration
// attributes and parses `name`, `env`, and `auth` field tags.
//
// Internal: this field can become unexported in the future
type ConfigAttribute struct {
Name string
Kind reflect.Kind
EnvVars []string
Auth string
AuthTypes []string
Sensitive bool
Internal bool
num int
}
func (a *ConfigAttribute) ReadEnv() (string, string) {
for _, envName := range a.EnvVars {
v := os.Getenv(envName)
if v == "" {
continue
}
return v, envName
}
return "", ""
}
func (a *ConfigAttribute) SetS(cfg *Config, v string) error {
switch a.Kind {
case reflect.String:
return a.Set(cfg, v)
case reflect.Bool:
vv, err := strconv.ParseBool(v)
if err != nil {
return err
}
return a.Set(cfg, vv)
case reflect.Int:
vv, err := strconv.Atoi(v)
if err != nil {
return err
}
return a.Set(cfg, vv)
default:
return fmt.Errorf("cannot set %s of unknown type %s",
a.Name, reflectKind(a.Kind))
}
}
func (a *ConfigAttribute) Set(cfg *Config, i interface{}) error {
rv := reflect.ValueOf(cfg)
field := rv.Elem().Field(a.num)
switch a.Kind {
case reflect.String:
field.SetString(i.(string))
case reflect.Bool:
field.SetBool(i.(bool))
case reflect.Int:
field.SetInt(int64(i.(int)))
default:
// must extensively test with providerFixture to avoid this one
return fmt.Errorf("cannot set %s of unknown type %s", a.Name, reflectKind(a.Kind))
}
return nil
}
func (a *ConfigAttribute) IsZero(cfg *Config) bool {
rv := reflect.ValueOf(cfg)
field := rv.Elem().Field(a.num)
return field.IsZero()
}
func (a *ConfigAttribute) GetString(cfg *Config) string {
rv := reflect.ValueOf(cfg)
field := rv.Elem().Field(a.num)
return fmt.Sprintf("%v", field.Interface())
}
func (a *ConfigAttribute) HasAuthAttribute() bool {
return a.Auth != ""
}