Skip to content

Commit

Permalink
Fix empty trees line counting (#539)
Browse files Browse the repository at this point in the history
Refs #450
  • Loading branch information
Felixoid committed May 11, 2021
1 parent 2a1df71 commit c893dbf
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
1 change: 1 addition & 0 deletions marshal.go
Expand Up @@ -591,6 +591,7 @@ func (e *Encoder) wrapTomlValue(val interface{}, parent *Tree) interface{} {
_, isTree := val.(*Tree)
_, isTreeS := val.([]*Tree)
if isTree || isTreeS {
e.line++
return val
}

Expand Down
4 changes: 3 additions & 1 deletion tomltree_write.go
Expand Up @@ -226,7 +226,9 @@ func tomlValueStringRepresentation(v interface{}, commented string, indent strin
}

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 {
if tv.position.Line < line || line == 0 {
line = tv.position.Line
Expand Down
49 changes: 49 additions & 0 deletions tomltree_write_test.go
Expand Up @@ -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) {
tomlString :=
`[table]
Expand Down

0 comments on commit c893dbf

Please sign in to comment.