forked from birdayz/kaf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
117 lines (98 loc) · 2.28 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
package kaf
import (
"fmt"
"os"
"path/filepath"
homedir "github.com/mitchellh/go-homedir"
yaml "gopkg.in/yaml.v2"
)
type SASL struct {
Mechanism string
Username string
Password string
}
type TLS struct {
Cafile string
Clientfile string
Clientkeyfile string
Insecure bool
}
type Cluster struct {
Name string
Brokers []string `yaml:"brokers"`
SASL *SASL `yaml:"SASL"`
TLS *TLS `yaml:"TLS"`
SecurityProtocol string `yaml:"security-protocol"`
SchemaRegistryURL string `yaml:"schema-registry-url"`
}
type Config struct {
CurrentCluster string `yaml:"current-cluster"`
Clusters []*Cluster `yaml:"clusters"`
}
func (c *Config) SetCurrentCluster(name string) error {
var oldCluster string
if c.ActiveCluster() != nil {
oldCluster = c.ActiveCluster().Name
}
for _, cluster := range c.Clusters {
if cluster.Name == name {
c.CurrentCluster = name
if err := c.Write(); err != nil {
// "Revert" change to the cluster struct, either
// everything is successful or nothing.
c.CurrentCluster = oldCluster
return err
}
return nil
}
}
return fmt.Errorf("Could not find cluster with name %v", name)
}
func (c *Config) ActiveCluster() *Cluster {
if c == nil || c.CurrentCluster == "" {
return nil
}
for _, cluster := range c.Clusters {
if cluster.Name == c.CurrentCluster {
return cluster
}
}
return nil
}
func (c *Config) Write() error {
home, err := homedir.Dir()
if err != nil {
return err
}
configDir := filepath.Join(home, ".kaf")
_ = os.MkdirAll(configDir, 0755)
configPath := filepath.Join(configDir, "config")
file, err := os.OpenFile(configPath, os.O_TRUNC|os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
panic(err)
}
encoder := yaml.NewEncoder(file)
return encoder.Encode(&c)
}
func ReadConfig() (c Config, err error) {
file, err := os.OpenFile(getDefaultConfigPath(), os.O_RDONLY, 0644)
if err != nil {
if os.IsNotExist(err) {
return Config{}, nil
}
return Config{}, err
}
decoder := yaml.NewDecoder(file)
err = decoder.Decode(&c)
if err != nil {
return Config{}, err
}
return c, nil
}
func getDefaultConfigPath() string {
home, err := homedir.Dir()
if err != nil {
panic(err)
}
return filepath.Join(home, ".kaf", "config")
}