forked from jenkins-x/jx
/
config_service.go
66 lines (58 loc) · 1.6 KB
/
config_service.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
package auth
import (
"fmt"
"io/ioutil"
"github.com/jenkins-x/jx/pkg/util"
"gopkg.in/yaml.v2"
)
func (s *AuthConfigService) Config() *AuthConfig {
return &s.config
}
func (s *AuthConfigService) SetConfig(c AuthConfig) {
s.config = c
}
// LoadConfig loads the configuration from the users JX config directory
func (s *AuthConfigService) LoadConfig() (*AuthConfig, error) {
config := &s.config
fileName := s.FileName
if fileName != "" {
exists, err := util.FileExists(fileName)
if err != nil {
return config, fmt.Errorf("Could not check if file exists %s due to %s", fileName, err)
}
if exists {
data, err := ioutil.ReadFile(fileName)
if err != nil {
return config, fmt.Errorf("Failed to load file %s due to %s", fileName, err)
}
err = yaml.Unmarshal(data, &config)
if err != nil {
return config, fmt.Errorf("Failed to unmarshal YAML file %s due to %s", fileName, err)
}
}
}
return config, nil
}
// SaveConfig loads the configuration from the users JX config directory
func (s *AuthConfigService) SaveConfig() error {
fileName := s.FileName
if fileName == "" {
return fmt.Errorf("No filename defined!")
}
data, err := yaml.Marshal(s.config)
if err != nil {
return err
}
return ioutil.WriteFile(fileName, data, DefaultWritePermissions)
}
// SaveUserAuth saves the given user auth for the server url
func (s *AuthConfigService) SaveUserAuth(url string, userAuth *UserAuth) error {
config := &s.config
config.SetUserAuth(url, userAuth)
user := userAuth.Username
if user != "" {
config.DefaultUsername = user
}
config.CurrentServer = url
return s.SaveConfig()
}