diff --git a/internal/config/config_type.go b/internal/config/config_type.go index 0fd85d7f0..a42ba87c5 100644 --- a/internal/config/config_type.go +++ b/internal/config/config_type.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "sort" + "strings" "github.com/cli/cli/internal/ghinstance" "gopkg.in/yaml.v3" @@ -16,6 +17,10 @@ const ( PromptsEnabled = "enabled" ) +var configValues = map[string][]string{ + "git_protocol": {"ssh", "https"}, +} + // This interface describes interacting with some persistent configuration for gh. type Config interface { Get(string, string) (string, error) @@ -271,7 +276,30 @@ func (c *fileConfig) GetWithSource(hostname, key string) (string, string, error) return value, defaultSource, nil } +func validConfigValues(key string) []string { + return configValues[key] +} + +func validateConfigEntry(key, value string) error { + validValues := validConfigValues(key) + + if len(validValues) == 0 { + return nil + } + + for _, v := range validValues { + if v == value { + return nil + } + } + + return fmt.Errorf("invalid value. Possible values for \"%s\" are: %s", key, strings.Join(validValues, ", ")) +} + func (c *fileConfig) Set(hostname, key, value string) error { + if err := validateConfigEntry(key, value); err != nil { + return err + } if hostname == "" { return c.SetStringValue(key, value) } else { diff --git a/internal/config/config_type_test.go b/internal/config/config_type_test.go index c9f33b45c..9e7fe573d 100644 --- a/internal/config/config_type_test.go +++ b/internal/config/config_type_test.go @@ -28,6 +28,7 @@ func Test_fileConfig_Set(t *testing.T) { example.com: editor: vim `, hostsBuf.String()) + assert.EqualError(t, c.Set("github.com", "git_protocol", "sshpps"), "invalid value. Possible values for \"git_protocol\" are: ssh, https") } func Test_defaultConfig(t *testing.T) { @@ -68,3 +69,17 @@ func Test_defaultConfig(t *testing.T) { expansion, _ := aliases.Get("co") assert.Equal(t, expansion, "pr checkout") } + +func Test_validateConfigEntry(t *testing.T) { + err := validateConfigEntry("git_protocol", "sshpps") + assert.EqualError(t, err, "invalid value. Possible values for \"git_protocol\" are: ssh, https") + + err = validateConfigEntry("git_protocol", "ssh") + assert.Nil(t, err) + + err = validateConfigEntry("editor", "vim") + assert.Nil(t, err) + + err = validateConfigEntry("got", "123") + assert.Nil(t, err) +}