diff --git a/cmd/config_set.go b/cmd/config_set.go index be82c54..bbcccbd 100644 --- a/cmd/config_set.go +++ b/cmd/config_set.go @@ -44,7 +44,7 @@ func newConfigSetCmd(h *pkg.Hctl, _ io.Writer) *cobra.Command { return compListConfig(toComplete, args, h) }, Run: func(_ *cobra.Command, args []string) { - if err := h.SetConfigValue(args[0], args[1]); err != nil { + if err := h.SetConfigValueWrite(args[0], args[1]); err != nil { o.PrintError(err) } o.PrintSuccess(args[0]) diff --git a/pkg/config/config.go b/pkg/config/config.go index 965a317..2de0fa9 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -227,6 +227,38 @@ func (c *Config) GetValueByPath(p string) (string, error) { } } +// Same as SetValueByPath, but also writes to config file +func (c *Config) SetValueByPathWrite(p string, val any) error { + if err := c.SetValueByPath(p, val); err != nil { + return err + } + if err := c.WriteConfig(); err != nil { + return err + } + return nil +} + +func (c *Config) WriteConfig() error { + // convert current config to byte slice + b, err := json.Marshal(c) + if err != nil { + return err + } + // create new io.Reader from byte slice config + reader := bytes.NewReader(b) + + // read in the byte slice config to viper instance + if err := c.Viper.ReadConfig(reader); err != nil { + return err + } + + // finally write updated viper instance to file + if err := c.Viper.WriteConfig(); err != nil { + return err + } + return nil +} + func (c *Config) SetValueByPath(p string, val any) error { // set config element by path p and value v log.Info().Msgf("Setting `%v` to `%v`", p, val) @@ -268,25 +300,5 @@ func (c *Config) SetValueByPath(p string, val any) error { default: return fmt.Errorf("unexpected type: %v", v.Type()) } - - log.Debug().Caller().Msgf("Config after change: %+v", c) - - // convert current config to byte slice - b, err := json.Marshal(c) - if err != nil { - return err - } - // create new io.Reader from byte slice config - reader := bytes.NewReader(b) - - // read in the byte slice config to viper instance - if err := c.Viper.ReadConfig(reader); err != nil { - return err - } - - // finally write updated viper instance to file - if err := c.Viper.WriteConfig(); err != nil { - return err - } return nil } diff --git a/pkg/hctl.go b/pkg/hctl.go index c404816..f3b4de1 100644 --- a/pkg/hctl.go +++ b/pkg/hctl.go @@ -74,6 +74,11 @@ func (h *Hctl) SetConfigValue(p string, v string) error { return err } +func (h *Hctl) SetConfigValueWrite(p string, v string) error { + err := h.cfg.SetValueByPathWrite(p, v) + return err +} + func (h *Hctl) GetConfigOptionsAsPaths() []string { return h.cfg.GetOptionsAsPaths() }