forked from sensu/sensu-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
60 lines (46 loc) · 1.56 KB
/
writer.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
package basic
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"github.com/sensu/sensu-go/types"
)
// SaveAPIUrl saves the API URL into a configuration file
func (c *Config) SaveAPIUrl(url string) error {
c.Cluster.APIUrl = url
return write(c.Cluster, filepath.Join(c.path, clusterFilename))
}
// SaveFormat saves the user's format preference into a configuration file
func (c *Config) SaveFormat(format string) error {
c.Profile.Format = format
return write(c.Profile, filepath.Join(c.path, profileFilename))
}
// SaveNamespace saves the user's default namespace to a configuration file
func (c *Config) SaveNamespace(namespace string) error {
c.Profile.Namespace = namespace
return write(c.Profile, filepath.Join(c.path, profileFilename))
}
// SaveTokens saves the JWT into a configuration file
func (c *Config) SaveTokens(tokens *types.Tokens) error {
// Update the configuration loaded in memory
c.Cluster.Tokens = tokens
// Load the configuration from the file so we don't save any configuration
// that was overrided with a configuration flag
savedConfig := &Config{}
_ = savedConfig.open(filepath.Join(c.path, clusterFilename))
savedConfig.Cluster.Tokens = tokens
return write(savedConfig.Cluster, filepath.Join(c.path, clusterFilename))
}
func write(data interface{}, path string) error {
// Make sure the directory exists
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return err
}
bytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(path, bytes, 0644)
}