Skip to content

Commit

Permalink
feat: add Write() support for cmdx configs (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
spy16 authored Sep 26, 2022
1 parent 069f2c6 commit ba6734b
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions cmdx/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import (
"runtime"

"github.com/mcuadros/go-defaults"
"github.com/odpf/salt/config"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"

"github.com/odpf/salt/config"
)

const (
Expand Down Expand Up @@ -51,17 +52,26 @@ func (c *Config) Defaults(cfg interface{}) {
func (c *Config) Init(cfg interface{}) error {
defaults.SetDefaults(cfg)

if fileExist(c.filename) {
return errors.New("config file already exists")
}

return c.Write(cfg)
}

func (c *Config) Read() (string, error) {
cfg, err := os.ReadFile(c.filename)
return string(cfg), err
}

func (c *Config) Write(cfg interface{}) error {
data, err := yaml.Marshal(cfg)
if err != nil {
return err
}

if fileExist(c.filename) {
return errors.New("config file already exists")
}

if _, err := os.Stat(c.filename); os.IsNotExist(err) {
os.MkdirAll(configDir("odpf"), 0700)
_ = os.MkdirAll(configDir("odpf"), 0700)
}

if err := os.WriteFile(c.filename, data, 0655); err != nil {
Expand All @@ -70,11 +80,6 @@ func (c *Config) Init(cfg interface{}) error {
return nil
}

func (c *Config) Read() (string, error) {
cfg, err := os.ReadFile(c.filename)
return string(cfg), err
}

func (c *Config) Load(cfg interface{}, opts ...ConfigLoaderOpts) error {
for _, opt := range opts {
opt(c)
Expand Down

0 comments on commit ba6734b

Please sign in to comment.