X Tutup
Skip to content

Commit bad138e

Browse files
committed
Enable reading from and writing to empty config files
1 parent d6f58fb commit bad138e

File tree

4 files changed

+34
-2
lines changed

4 files changed

+34
-2
lines changed

internal/config/config_file.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,11 @@ func parseConfigFile(fn string) ([]byte, *yaml.Node, error) {
7676
if err != nil {
7777
return data, nil, err
7878
}
79-
if len(root.Content) < 1 {
80-
return data, &root, fmt.Errorf("malformed config")
79+
if len(root.Content) == 0 {
80+
return data, &yaml.Node{
81+
Kind: yaml.DocumentNode,
82+
Content: []*yaml.Node{{Kind: yaml.MappingNode}},
83+
}, nil
8184
}
8285
if root.Content[0].Kind != yaml.MappingNode {
8386
return data, &root, fmt.Errorf("expected a top level map")

internal/config/config_file_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package config
33
import (
44
"bytes"
55
"errors"
6+
"fmt"
67
"reflect"
78
"testing"
89

@@ -94,3 +95,16 @@ github.com:
9495

9596
eq(t, buf.String(), expected)
9697
}
98+
99+
func Test_parseConfigFile(t *testing.T) {
100+
fileContents := []string{"", " ", "\n"}
101+
for _, contents := range fileContents {
102+
t.Run(fmt.Sprintf("contents: %q", contents), func(t *testing.T) {
103+
defer StubConfig(contents, "")()
104+
_, yamlRoot, err := parseConfigFile("config.yml")
105+
eq(t, err, nil)
106+
eq(t, yamlRoot.Content[0].Kind, yaml.MappingNode)
107+
eq(t, len(yamlRoot.Content[0].Content), 0)
108+
})
109+
}
110+
}

internal/config/config_type.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package config
22

33
import (
4+
"bytes"
45
"errors"
56
"fmt"
67

@@ -172,6 +173,10 @@ func (c *fileConfig) Write() error {
172173
return err
173174
}
174175

176+
if bytes.Equal(marshalled, []byte("{}\n")) {
177+
marshalled = []byte{}
178+
}
179+
175180
return WriteConfigFile(ConfigFile(), marshalled)
176181
}
177182

internal/config/config_type_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,13 @@ hosts:
2727
editor: vim
2828
`, cb.String())
2929
}
30+
31+
func Test_fileConfig_Write(t *testing.T) {
32+
cb := bytes.Buffer{}
33+
StubWriteConfig(&cb, nil)
34+
35+
c := NewBlankConfig()
36+
assert.NoError(t, c.Write())
37+
38+
assert.Equal(t, "", cb.String())
39+
}

0 commit comments

Comments
 (0)
X Tutup