-
Notifications
You must be signed in to change notification settings - Fork 4
/
configs.go
97 lines (85 loc) · 2.56 KB
/
configs.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
package limacharlie
import (
"fmt"
"io/ioutil"
"os/user"
"strings"
"gopkg.in/yaml.v3"
)
// ConfigFile is the actual config file format may seem a bit odd
// but it is structured to maintain backwards compatibility
// with the Python SDK/CLI format.
type ConfigFile struct {
ConfigEnvironment
Environments map[string]ConfigEnvironment `yaml:"env"`
}
// ConfigEnvironment holds the different values parsed from the environment
type ConfigEnvironment struct {
OID string `yaml:"oid"`
UID string `yaml:"uid"`
APIKey string `yaml:"api_key"`
}
// FromConfigFile updates self from the file path
func (o *ClientOptions) FromConfigFile(configFilePath string, environmentName string) error {
cleanPath := configFilePath
if strings.HasPrefix(cleanPath, "~/") {
usr, err := user.Current()
if err != nil {
return err
}
dir := usr.HomeDir
cleanPath = fmt.Sprintf("%s/%s", dir, cleanPath[2:])
}
data, err := ioutil.ReadFile(cleanPath)
if err != nil {
return err
}
return o.FromConfigString(data, environmentName)
}
// FromConfigString updates self from strings
func (o *ClientOptions) FromConfigString(configFileString []byte, environmentName string) error {
cfg := ConfigFile{}
if err := yaml.Unmarshal(configFileString, &cfg); err != nil {
return err
}
if err := yaml.Unmarshal(configFileString, &cfg.ConfigEnvironment); err != nil {
return err
}
return o.FromConfig(cfg, environmentName)
}
// FromConfig updates self from a config file
func (o *ClientOptions) FromConfig(cfg ConfigFile, environmentName string) error {
// An empty environment name defaults.
if environmentName == "" {
environmentName = "default"
}
// Load the relevant environment.
var env ConfigEnvironment
var ok bool
if environmentName == "default" {
env = cfg.ConfigEnvironment
} else if env, ok = cfg.Environments[environmentName]; !ok {
return NewInvalidClientOptionsError(fmt.Sprintf("environment %s not found", environmentName))
}
// Set the values, validation is done by the client itself.
o.OID = env.OID
o.UID = env.UID
o.APIKey = env.APIKey
return nil
}
func (o *ClientOptions) validateMinimumRequirements() error {
if o.OID == "" && o.UID == "" {
return newLCError(lcErrClientMissingRequirements)
}
return nil
}
func (o *ClientOptions) validate() error {
// Validate all the options we ended up with.
if err := validateUUID(o.OID); err != nil {
return NewInvalidClientOptionsError(fmt.Sprintf("invalid OID: %v", err))
}
if err := validateUUID(o.APIKey); err != nil {
return NewInvalidClientOptionsError(fmt.Sprintf("invalid APIKey: %v", err))
}
return nil
}