From: Tom Wright <935867+TomWright@users.noreply.github.com> Date: Sat, 1 Aug 2026 01:44:34 +0100 Subject: Support go-toml v2.4.3 go-toml v2.4 rejects encoding a bare value as a document root, which the TOML writer relied on when the top level value isn't a table - the result of selecting a scalar or list out of a document. Every *_to_toml case in the cross format tests failed with "cannot encode a X as a document root", as reported in the Debian build. The writer now encodes those values against a placeholder key and strips the " = " prefix back off, so go-toml still owns value formatting and the output is unchanged. Using the inline tag option on the placeholder also fixes a top level list of tables, which previously emitted table headers with an empty key. Fixes #550 Bug: https://github.com/TomWright/dasel/issues/550 Origin: upstream, https://github.com/TomWright/dasel/commit/70fd28f38c0e7eb35ef1a034813daf1976e90485 --- go.mod | 2 +- go.sum | 4 +- parsing/toml/toml_writer.go | 88 ++++++++++++++++++++++++++++------------ parsing/toml/toml_writer_test.go | 74 +++++++++++++++++++++++++++++++++ 4 files changed, 140 insertions(+), 28 deletions(-) diff --git a/go.mod b/go.mod index 71227d8..5cfb3d5 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/goccy/go-json v0.10.6 github.com/google/go-cmp v0.7.0 github.com/hashicorp/hcl/v2 v2.24.0 - github.com/pelletier/go-toml/v2 v2.2.5-0.20250826075308-a0e846496753 + github.com/pelletier/go-toml/v2 v2.4.3 github.com/zclconf/go-cty v1.17.0 go.yaml.in/yaml/v4 v4.0.0-rc.3 gopkg.in/ini.v1 v1.67.0 diff --git a/go.sum b/go.sum index ab1f40e..ce5ca18 100644 --- a/go.sum +++ b/go.sum @@ -66,8 +66,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/pelletier/go-toml/v2 v2.2.5-0.20250826075308-a0e846496753 h1:aTpyfgn3dz2npHl011BHQehdSavqjzhZdE6fJuJlO3A= -github.com/pelletier/go-toml/v2 v2.2.5-0.20250826075308-a0e846496753/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= +github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= diff --git a/parsing/toml/toml_writer.go b/parsing/toml/toml_writer.go index 9108274..fd115ba 100644 --- a/parsing/toml/toml_writer.go +++ b/parsing/toml/toml_writer.go @@ -33,28 +33,6 @@ func (j *tomlWriter) Write(value *model.Value) ([]byte, error) { return nil, fmt.Errorf("nil value") } - var goValue interface{} - var err error - - if value.IsMap() { - goValue, err = buildGoValueForMap(value) - if err != nil { - return nil, fmt.Errorf("failed to construct go value: %w", err) - } - } else { - // handle scalars, slices, etc. Use goTypeAndValue to get a concrete reflect.Value - typ, rv, err := goTypeAndValue(value) - if err != nil { - return nil, fmt.Errorf("failed to convert non-map top-level value: %w", err) - } - // For nil/zero interface, ensure we pass nil interface rather than a typed zero. - if typ.Kind() == reflect.Interface && rv.IsZero() { - goValue = nil - } else { - goValue = rv.Interface() - } - } - // We currently encode the top level value directly. We have little control over nested values. // Perhaps it would be better to implement a custom Encoder that respects metadata on nested values? var buf bytes.Buffer @@ -65,10 +43,25 @@ func (j *tomlWriter) Write(value *model.Value) ([]byte, error) { encoder.SetArraysMultiline(false) } - if err := encoder.Encode(goValue); err != nil { - return nil, fmt.Errorf("toml encode failed: %w", err) + var outBytes []byte + + if value.IsMap() { + goValue, err := buildGoValueForMap(value) + if err != nil { + return nil, fmt.Errorf("failed to construct go value: %w", err) + } + if err := encoder.Encode(goValue); err != nil { + return nil, fmt.Errorf("toml encode failed: %w", err) + } + outBytes = buf.Bytes() + } else { + // handle scalars, slices, etc. + var err error + outBytes, err = encodeRootValue(encoder, &buf, value) + if err != nil { + return nil, err + } } - outBytes := buf.Bytes() // Ensure trailing newline for consistency with other format writers/tests. if len(outBytes) == 0 || outBytes[len(outBytes)-1] != '\n' { @@ -78,6 +71,51 @@ func (j *tomlWriter) Write(value *model.Value) ([]byte, error) { return outBytes, nil } +// rootValueKey is the placeholder key used when encoding a non-table document root. +const rootValueKey = "v" + +// encodeRootValue encodes a top level value that isn't a map, e.g. the result of +// selecting a single scalar or list out of a document. +// A TOML document root must be a table, so go-toml will only encode these values +// as part of a key/value pair. We encode against a placeholder key and strip the +// ` = ` prefix back off, leaving go-toml in charge of formatting the value. +func encodeRootValue(encoder *pkg.Encoder, buf *bytes.Buffer, value *model.Value) ([]byte, error) { + typ, rv, err := goTypeAndValue(value) + if err != nil { + return nil, fmt.Errorf("failed to convert non-map top-level value: %w", err) + } + + // A null root has no TOML representation at all. Pass the nil interface + // through so go-toml reports it rather than silently writing nothing. + if typ.Kind() == reflect.Interface && rv.IsZero() { + if err := encoder.Encode(nil); err != nil { + return nil, fmt.Errorf("toml encode failed: %w", err) + } + return buf.Bytes(), nil + } + + // The inline option keeps maps and lists of maps as inline tables, rather than + // go-toml emitting table headers built from the placeholder key. + wrapperType := reflect.StructOf([]reflect.StructField{{ + Name: "F0", + Type: typ, + Tag: reflect.StructTag(fmt.Sprintf(`toml:"%s,inline"`, rootValueKey)), + }}) + wrapper := reflect.New(wrapperType).Elem() + wrapper.Field(0).Set(rv) + + if err := encoder.Encode(wrapper.Interface()); err != nil { + return nil, fmt.Errorf("toml encode failed: %w", err) + } + + prefix := []byte(rootValueKey + " = ") + out := buf.Bytes() + if !bytes.HasPrefix(out, prefix) { + return nil, fmt.Errorf("toml encode failed: unexpected encoding of top-level value: %s", string(out)) + } + return out[len(prefix):], nil +} + // buildGoValueForMap constructs a reflect.Value that is a struct with fields in // the same order as keys in the provided map Value. The struct fields are // tagged with `toml:""` so go-toml will use the original key diff --git a/parsing/toml/toml_writer_test.go b/parsing/toml/toml_writer_test.go index 0678c05..b8be964 100644 --- a/parsing/toml/toml_writer_test.go +++ b/parsing/toml/toml_writer_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/tomwright/dasel/v3/model" "github.com/tomwright/dasel/v3/parsing" "github.com/tomwright/dasel/v3/parsing/toml" ) @@ -241,6 +242,79 @@ func TestTomlWriter_MoreCases(t *testing.T) { }) } +// TestTomlWriter_RootValue covers top level values that aren't tables, e.g. the +// result of selecting a single scalar or list out of a document. A TOML document +// root must be a table, so these are written as bare values. +func TestTomlWriter_RootValue(t *testing.T) { + slice := func(vals ...*model.Value) *model.Value { + s := model.NewSliceValue() + for _, v := range vals { + if err := s.Append(v); err != nil { + t.Fatalf("failed to append to slice: %v", err) + } + } + return s + } + kvMap := func(k string, v *model.Value) *model.Value { + m := model.NewMapValue() + if err := m.SetMapKey(k, v); err != nil { + t.Fatalf("failed to set map key: %v", err) + } + return m + } + + tests := map[string]struct { + in *model.Value + exp string + }{ + "string": {in: model.NewStringValue("world"), exp: "'world'\n"}, + "string quoting": {in: model.NewStringValue(`it's "here"`), exp: "\"it's \\\"here\\\"\"\n"}, + "int": {in: model.NewIntValue(123), exp: "123\n"}, + "negative int": {in: model.NewIntValue(-5), exp: "-5\n"}, + "float": {in: model.NewFloatValue(12.3), exp: "12.3\n"}, + "bool true": {in: model.NewBoolValue(true), exp: "true\n"}, + "bool false": {in: model.NewBoolValue(false), exp: "false\n"}, + "empty slice": {in: slice(), exp: "[]\n"}, + "int slice": {in: slice(model.NewIntValue(1), model.NewIntValue(2)), exp: "[1, 2]\n"}, + "string slice": {in: slice(model.NewStringValue("a")), exp: "['a']\n"}, + "nested slice": {in: slice(slice(model.NewIntValue(1)), slice()), exp: "[[1], []]\n"}, + "slice of tables": {in: slice(kvMap("a", model.NewIntValue(1)), kvMap("a", model.NewIntValue(2))), exp: "[{a = 1}, {a = 2}]\n"}, + } + + for name, tc := range tests { + name := name + tc := tc + t.Run(name, func(t *testing.T) { + for _, compact := range []bool{false, true} { + opts := parsing.DefaultWriterOptions() + opts.Compact = compact + writer, err := toml.TOML.NewWriter(opts) + if err != nil { + t.Fatalf("unexpected error creating writer: %v", err) + } + + out, err := writer.Write(tc.in) + if err != nil { + t.Fatalf("writer error (compact=%v): %v", compact, err) + } + if got := string(out); got != tc.exp { + t.Fatalf("root value output mismatch (compact=%v)\nexpected:\n%s\ngot:\n%s", compact, tc.exp, got) + } + } + }) + } + + t.Run("null", func(t *testing.T) { + writer, err := toml.TOML.NewWriter(parsing.DefaultWriterOptions()) + if err != nil { + t.Fatalf("unexpected error creating writer: %v", err) + } + if _, err := writer.Write(model.NewNullValue()); err == nil { + t.Fatal("expected an error writing a null root value, got none") + } + }) +} + func TestTomlWriter_Compact(t *testing.T) { doc := []byte(`title = "TOML Example" [owner]