From 4040373cfd677dfddb44241c198a96adfcda1653 Mon Sep 17 00:00:00 2001 From: Thomas Pelletier Date: Mon, 28 Aug 2023 09:52:11 -0400 Subject: [PATCH] Encode: fix ignored indent of array tables (#889) Fixes #888 --- marshaler.go | 4 ++++ marshaler_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/marshaler.go b/marshaler.go index 83875260..1f3bec9b 100644 --- a/marshaler.go +++ b/marshaler.go @@ -983,6 +983,10 @@ func (enc *Encoder) encodeSliceAsArrayTable(b []byte, ctx encoderCtx, v reflect. scratch = append(scratch, "]]\n"...) ctx.skipTableHeader = true + if enc.indentTables { + ctx.indent++ + } + b = enc.encodeComment(ctx.indent, ctx.options.comment, b) for i := 0; i < v.Len(); i++ { diff --git a/marshaler_test.go b/marshaler_test.go index 506c7238..b4b8e28a 100644 --- a/marshaler_test.go +++ b/marshaler_test.go @@ -1201,6 +1201,44 @@ randomize = true require.Equal(t, expected, buf.String()) } +func TestMarhsalIssue888(t *testing.T) { + type Thing struct { + FieldA string `comment:"my field A"` + FieldB string `comment:"my field B"` + } + + type Cfg struct { + Custom []Thing + } + + buf := new(bytes.Buffer) + + config := Cfg{ + Custom: []Thing{ + {FieldA: "field a 1", FieldB: "field b 1"}, + {FieldA: "field a 2", FieldB: "field b 2"}, + }, + } + + encoder := toml.NewEncoder(buf).SetIndentTables(true) + encoder.Encode(config) + + expected := `[[Custom]] + # my field A + FieldA = 'field a 1' + # my field B + FieldB = 'field b 1' + +[[Custom]] + # my field A + FieldA = 'field a 2' + # my field B + FieldB = 'field b 2' +` + + require.Equal(t, expected, buf.String()) +} + func TestMarshalNestedAnonymousStructs(t *testing.T) { type Embedded struct { Value string `toml:"value" json:"value"`