Skip to content

Commit

Permalink
Config: Unset the default config value
Browse files Browse the repository at this point in the history
This PR make sure that if user try to set a default value for a
config property then it just unset that property and default value
is used. It will also allow not to have default value in the viper
config file. Also add `UpdateDefaults` to set and get config handler
so API can also make use of it.

Without this Patch
```
$ crc config set preset microshift
$ crc config set cpus 2
$ crc config set preset openshift
$ cat ~/.crc/crc.json
{
  "cpus": 2,
  "preset": "openshift"
}
```

After this patch `~/.crc/crc.json` going to be empty and openshift
preset is going to use default `cpus` as `4`.
  • Loading branch information
praveenkumar committed May 8, 2023
1 parent 31f0f27 commit f9a0a4a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
2 changes: 2 additions & 0 deletions pkg/crc/api/handlers.go
Expand Up @@ -191,6 +191,7 @@ func (h *Handler) SetConfig(c *context) error {
if len(multiError.Errors) != 0 {
return multiError
}
crcConfig.UpdateDefaults(h.Config)
return c.JSON(http.StatusOK, client.SetOrUnsetConfigResult{
Properties: successProps,
})
Expand Down Expand Up @@ -219,6 +220,7 @@ func (h *Handler) UnsetConfig(c *context) error {
if len(multiError.Errors) != 0 {
return multiError
}
crcConfig.UpdateDefaults(h.Config)
return c.JSON(http.StatusOK, client.SetOrUnsetConfigResult{
Properties: successProps,
})
Expand Down
11 changes: 11 additions & 0 deletions pkg/crc/config/config.go
Expand Up @@ -95,6 +95,17 @@ func (c *Config) Set(key string, value interface{}) (string, error) {
return "", fmt.Errorf(invalidType, value, key)
}

// Make sure if user try to set same value which
// is default then just unset the value which
// anyway make it default and don't update it
// ~/.crc/crc.json (viper config) file.
if setting.defaultValue == castValue {
if _, err := c.Unset(key); err != nil {
return "", err
}
return "", nil
}

if setting.isSecret {
if err := c.secretStorage.Set(key, castValue); err != nil {
return "", err
Expand Down
5 changes: 3 additions & 2 deletions pkg/crc/config/viper_config_test.go
Expand Up @@ -115,13 +115,14 @@ func TestViperConfigLoadDefaultValue(t *testing.T) {
Value: 4,
IsDefault: true,
}, config.Get(cpus))

_, err = config.Set(cpus, 4)
assert.NoError(t, err)

bin, err := os.ReadFile(configFile)
assert.NoError(t, err)
assert.JSONEq(t, `{"cpus":4}`, string(bin))
// Setting default value will not update
// write to the config so expected would be {}
assert.JSONEq(t, `{}`, string(bin))

assert.Equal(t, SettingValue{
Value: 4,
Expand Down

0 comments on commit f9a0a4a

Please sign in to comment.