-
Notifications
You must be signed in to change notification settings - Fork 787
/
file_config_saver.go
69 lines (64 loc) · 1.98 KB
/
file_config_saver.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
package auth
import (
"fmt"
"github.com/jenkins-x/jx/pkg/util"
"gopkg.in/yaml.v2"
"io/ioutil"
"path/filepath"
)
// NewFileAuthConfigService
func NewFileAuthConfigService(filename string) (ConfigService, error) {
saver, err := newFileAuthSaver(filename)
return NewAuthConfigService(saver), err
}
// newFileBasedAuthConfigSaver creates a new FileBasedAuthConfigService that stores its data under the given filename
// If the fileName is an absolute path, it will be used. If it is a simple filename, it will be stored in the default
// Config directory
func newFileAuthSaver(fileName string) (ConfigSaver, error) {
svc := &FileAuthConfigSaver{}
// If the fileName is an absolute path, use that. Otherwise treat it as a config filename to be used in
if fileName == filepath.Base(fileName) {
dir, err := util.ConfigDir()
if err != nil {
return svc, err
}
svc.FileName = filepath.Join(dir, fileName)
} else {
svc.FileName = fileName
}
return svc, nil
}
// LoadConfig loads the configuration from the users JX config directory
func (s *FileAuthConfigSaver) LoadConfig() (*AuthConfig, error) {
config := &AuthConfig{}
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 saves the configuration to disk
func (s *FileAuthConfigSaver) SaveConfig(config *AuthConfig) error {
fileName := s.FileName
if fileName == "" {
return fmt.Errorf("no filename defined")
}
data, err := yaml.Marshal(config)
if err != nil {
return err
}
return ioutil.WriteFile(fileName, data, DefaultWritePermissions)
}