X Tutup
Skip to content

Commit 09401b3

Browse files
authored
Validate git protocol config before setting it
1 parent 7d317a8 commit 09401b3

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

internal/config/config_type.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"errors"
66
"fmt"
77
"sort"
8+
"strings"
89

910
"github.com/cli/cli/internal/ghinstance"
1011
"gopkg.in/yaml.v3"
@@ -16,6 +17,10 @@ const (
1617
PromptsEnabled = "enabled"
1718
)
1819

20+
var configValues = map[string][]string{
21+
"git_protocol": {"ssh", "https"},
22+
}
23+
1924
// This interface describes interacting with some persistent configuration for gh.
2025
type Config interface {
2126
Get(string, string) (string, error)
@@ -271,7 +276,30 @@ func (c *fileConfig) GetWithSource(hostname, key string) (string, string, error)
271276
return value, defaultSource, nil
272277
}
273278

279+
func validConfigValues(key string) []string {
280+
return configValues[key]
281+
}
282+
283+
func validateConfigEntry(key, value string) error {
284+
validValues := validConfigValues(key)
285+
286+
if len(validValues) == 0 {
287+
return nil
288+
}
289+
290+
for _, v := range validValues {
291+
if v == value {
292+
return nil
293+
}
294+
}
295+
296+
return fmt.Errorf("invalid value. Possible values for \"%s\" are: %s", key, strings.Join(validValues, ", "))
297+
}
298+
274299
func (c *fileConfig) Set(hostname, key, value string) error {
300+
if err := validateConfigEntry(key, value); err != nil {
301+
return err
302+
}
275303
if hostname == "" {
276304
return c.SetStringValue(key, value)
277305
} else {

internal/config/config_type_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ func Test_fileConfig_Set(t *testing.T) {
2828
example.com:
2929
editor: vim
3030
`, hostsBuf.String())
31+
assert.EqualError(t, c.Set("github.com", "git_protocol", "sshpps"), "invalid value. Possible values for \"git_protocol\" are: ssh, https")
3132
}
3233

3334
func Test_defaultConfig(t *testing.T) {
@@ -68,3 +69,17 @@ func Test_defaultConfig(t *testing.T) {
6869
expansion, _ := aliases.Get("co")
6970
assert.Equal(t, expansion, "pr checkout")
7071
}
72+
73+
func Test_validateConfigEntry(t *testing.T) {
74+
err := validateConfigEntry("git_protocol", "sshpps")
75+
assert.EqualError(t, err, "invalid value. Possible values for \"git_protocol\" are: ssh, https")
76+
77+
err = validateConfigEntry("git_protocol", "ssh")
78+
assert.Nil(t, err)
79+
80+
err = validateConfigEntry("editor", "vim")
81+
assert.Nil(t, err)
82+
83+
err = validateConfigEntry("got", "123")
84+
assert.Nil(t, err)
85+
}

0 commit comments

Comments
 (0)
X Tutup