Enable reading from and writing to empty config files
This commit is contained in:
parent
d6f58fb448
commit
bad138e448
4 changed files with 34 additions and 2 deletions
|
|
@ -76,8 +76,11 @@ func parseConfigFile(fn string) ([]byte, *yaml.Node, error) {
|
|||
if err != nil {
|
||||
return data, nil, err
|
||||
}
|
||||
if len(root.Content) < 1 {
|
||||
return data, &root, fmt.Errorf("malformed config")
|
||||
if len(root.Content) == 0 {
|
||||
return data, &yaml.Node{
|
||||
Kind: yaml.DocumentNode,
|
||||
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
|
||||
}, nil
|
||||
}
|
||||
if root.Content[0].Kind != yaml.MappingNode {
|
||||
return data, &root, fmt.Errorf("expected a top level map")
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package config
|
|||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
|
|
@ -94,3 +95,16 @@ github.com:
|
|||
|
||||
eq(t, buf.String(), expected)
|
||||
}
|
||||
|
||||
func Test_parseConfigFile(t *testing.T) {
|
||||
fileContents := []string{"", " ", "\n"}
|
||||
for _, contents := range fileContents {
|
||||
t.Run(fmt.Sprintf("contents: %q", contents), func(t *testing.T) {
|
||||
defer StubConfig(contents, "")()
|
||||
_, yamlRoot, err := parseConfigFile("config.yml")
|
||||
eq(t, err, nil)
|
||||
eq(t, yamlRoot.Content[0].Kind, yaml.MappingNode)
|
||||
eq(t, len(yamlRoot.Content[0].Content), 0)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
|
|
@ -172,6 +173,10 @@ func (c *fileConfig) Write() error {
|
|||
return err
|
||||
}
|
||||
|
||||
if bytes.Equal(marshalled, []byte("{}\n")) {
|
||||
marshalled = []byte{}
|
||||
}
|
||||
|
||||
return WriteConfigFile(ConfigFile(), marshalled)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -27,3 +27,13 @@ hosts:
|
|||
editor: vim
|
||||
`, cb.String())
|
||||
}
|
||||
|
||||
func Test_fileConfig_Write(t *testing.T) {
|
||||
cb := bytes.Buffer{}
|
||||
StubWriteConfig(&cb, nil)
|
||||
|
||||
c := NewBlankConfig()
|
||||
assert.NoError(t, c.Write())
|
||||
|
||||
assert.Equal(t, "", cb.String())
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue