Fix empty trees line counting (#539)

Refs #450
This commit is contained in:
Mikhail f. Shiryaev
2021-05-11 14:50:05 +02:00
committed by GitHub
parent 2a1df71375
commit c893dbf25c
3 changed files with 53 additions and 1 deletions
+1
View File
@@ -591,6 +591,7 @@ func (e *Encoder) wrapTomlValue(val interface{}, parent *Tree) interface{} {
_, isTree := val.(*Tree) _, isTree := val.(*Tree)
_, isTreeS := val.([]*Tree) _, isTreeS := val.([]*Tree)
if isTree || isTreeS { if isTree || isTreeS {
e.line++
return val return val
} }
+3 -1
View File
@@ -226,7 +226,9 @@ func tomlValueStringRepresentation(v interface{}, commented string, indent strin
} }
func getTreeArrayLine(trees []*Tree) (line int) { func getTreeArrayLine(trees []*Tree) (line int) {
// get lowest line number that is not 0 // Prevent returning 0 for empty trees
line = int(^uint(0) >> 1)
// get lowest line number >= 0
for _, tv := range trees { for _, tv := range trees {
if tv.position.Line < line || line == 0 { if tv.position.Line < line || line == 0 {
line = tv.position.Line line = tv.position.Line
+49
View File
@@ -364,6 +364,55 @@ c = nan`
} }
} }
func TestOrderedEmptyTrees(t *testing.T) {
type val struct {
Key string `toml:"key"`
}
type structure struct {
First val `toml:"first"`
Empty []val `toml:"empty"`
}
input := structure{First: val{Key: "value"}}
buf := new(bytes.Buffer)
err := NewEncoder(buf).Order(OrderPreserve).Encode(input)
if err != nil {
t.Fatal("failed to encode input")
}
expected := `
[first]
key = "value"
`
if expected != buf.String() {
t.Fatal("expected and encoded body aren't equal: ", expected, buf.String())
}
}
func TestOrderedNonIncreasedLine(t *testing.T) {
type NiceMap map[string]string
type Manifest struct {
NiceMap `toml:"dependencies"`
Build struct {
BuildCommand string `toml:"build-command"`
} `toml:"build"`
}
test := &Manifest{}
test.Build.BuildCommand = "test"
buf := new(bytes.Buffer)
if err := NewEncoder(buf).Order(OrderPreserve).Encode(test); err != nil {
panic(err)
}
expected := `
[dependencies]
[build]
build-command = "test"
`
if expected != buf.String() {
t.Fatal("expected and encoded body aren't equal: ", expected, buf.String())
}
}
func TestIssue290(t *testing.T) { func TestIssue290(t *testing.T) {
tomlString := tomlString :=
`[table] `[table]