Skip to content

Commit e3d423e

Browse files
cfergeauanjannath
authored andcommitted
config: Refactor code from commit 73a4b92
The settings API already associates a settings name (CPUs, Memory) with a validation function. This validation function takes into account the current preset. This commit reworks 73a4b92 to take advantage of this validation function. Instead of reparsing the preset, and hardcoding in a new place how to validate a Memory value, or a CPUs value, we can use instead the validationFn from the Settings API.
1 parent deef966 commit e3d423e

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

pkg/crc/config/config.go

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"reflect"
66

77
"github.com/crc-org/crc/pkg/crc/preset"
8-
"github.com/crc-org/crc/pkg/crc/validation"
98
"github.com/spf13/cast"
109
)
1110

@@ -63,16 +62,23 @@ func (c *Config) AddSetting(name string, defValue interface{}, validationFn Vali
6362
}
6463
}
6564

65+
func (c *Config) validate(key string, value interface{}) error {
66+
ok, expectedValue := c.settingsByName[key].validationFn(value)
67+
if !ok {
68+
return fmt.Errorf(invalidProp, value, key, expectedValue)
69+
}
70+
return nil
71+
}
72+
6673
// Set sets the value for a given config key
6774
func (c *Config) Set(key string, value interface{}) (string, error) {
6875
setting, ok := c.settingsByName[key]
6976
if !ok {
7077
return "", fmt.Errorf(configPropDoesntExistMsg, key)
7178
}
7279

73-
ok, expectedValue := c.settingsByName[key].validationFn(value)
74-
if !ok {
75-
return "", fmt.Errorf(invalidProp, value, key, expectedValue)
80+
if err := c.validate(key, value); err != nil {
81+
return "", err
7682
}
7783

7884
var castValue interface{}
@@ -100,15 +106,14 @@ func (c *Config) Set(key string, value interface{}) (string, error) {
100106
// we want to make sure if cpu or memory is less for a preset
101107
// then default is set automatic.
102108
if setting.Name == Preset {
103-
preset := preset.ParsePreset(value.(string))
104109
mem := c.Get(Memory)
105-
if err := validation.ValidateMemory(mem.AsInt(), preset); err != nil {
110+
if err := c.validate(Memory, mem); err != nil {
106111
if _, err := c.Unset(Memory); err != nil {
107112
return "", err
108113
}
109114
}
110115
cpu := c.Get(CPUs)
111-
if err := validation.ValidateCPUs(cpu.AsInt(), preset); err != nil {
116+
if err := c.validate(CPUs, cpu); err != nil {
112117
if _, err := c.Unset(CPUs); err != nil {
113118
return "", err
114119
}

0 commit comments

Comments
 (0)