Skip to content

Commit

Permalink
Add support to config for setting and writing blank values (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
samcoe authored Oct 27, 2023
1 parent 47a83ee commit debe718
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
7 changes: 7 additions & 0 deletions internal/yamlmap/yaml_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ func MapValue() *Map {
}}
}

func NullValue() *Map {
return &Map{&yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!null",
}}
}

func Unmarshal(data []byte) (*Map, error) {
var root yaml.Node
err := yaml.Unmarshal(data, &root)
Expand Down
13 changes: 11 additions & 2 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,12 @@ func (c *Config) Remove(keys []string) error {
// Set a string value in a Config.
// The keys argument is a sequence of key values so that nested
// entries can be set. If any of the keys do not exist they will
// be created.
// be created. If the string value to be set is empty it will be
// represented as null not an empty string when written.
//
// var c *Config
// c.Set([]string{"key"}, "")
// Write(c) // writes `key: ` not `key: ""`
func (c *Config) Set(keys []string, value string) {
c.mu.Lock()
defer c.mu.Unlock()
Expand All @@ -116,7 +121,11 @@ func (c *Config) Set(keys []string, value string) {
}
m = entry
}
m.SetEntry(keys[len(keys)-1], yamlmap.StringValue(value))
val := yamlmap.StringValue(value)
if value == "" {
val = yamlmap.NullValue()
}
m.SetEntry(keys[len(keys)-1], val)
}

func (c *Config) deepCopy() *Config {
Expand Down
17 changes: 17 additions & 0 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,18 @@ func TestWrite(t *testing.T) {
}
}

func TestWriteEmptyValues(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("GH_CONFIG_DIR", tempDir)
cfg := ReadFromString(testFullConfig())
cfg.Set([]string{"editor"}, "")
err := Write(cfg)
assert.NoError(t, err)
data, err := os.ReadFile(generalConfigFile())
assert.NoError(t, err)
assert.Equal(t, "git_protocol: ssh\neditor:\nprompt: enabled\npager: less\n", string(data))
}

func TestGet(t *testing.T) {
tests := []struct {
name string
Expand Down Expand Up @@ -595,6 +607,11 @@ func TestSet(t *testing.T) {
keys: []string{"johnny", "test"},
value: "dukey",
},
{
name: "set empty value",
keys: []string{"empty"},
value: "",
},
}

for _, tt := range tests {
Expand Down

0 comments on commit debe718

Please sign in to comment.