| 1 |
package toml |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"reflect" |
| 7 |
"strconv" |
| 8 |
"strings" |
| 9 |
|
| 10 |
pkg "github.com/pelletier/go-toml/v2" |
| 11 |
"github.com/tomwright/dasel/v3/model" |
| 12 |
"github.com/tomwright/dasel/v3/parsing" |
| 13 |
) |
| 14 |
|
| 15 |
var _ parsing.Writer = (*tomlWriter)(nil) |
| 16 |
|
| 17 |
func newTOMLWriter(options parsing.WriterOptions) (parsing.Writer, error) { |
| 18 |
w := &tomlWriter{options: options} |
| 19 |
return w, nil |
| 20 |
} |
| 21 |
|
| 22 |
type tomlWriter struct { |
| 23 |
options parsing.WriterOptions |
| 24 |
} |
| 25 |
|
| 26 |
// Write converts the dasel model.Value into Go values backed by dynamically |
| 27 |
// generated struct types (reflect.StructOf) that preserve key ordering, then |
| 28 |
// delegates to go-toml Marshal to produce canonical TOML output. |
| 29 |
// This implementation doesn't preserve all formatting metadata (multiline strings, etc) |
| 30 |
// and needs some work to do so. |
| 31 |
func (j *tomlWriter) Write(value *model.Value) ([]byte, error) { |
| 32 |
if value == nil { |
| 33 |
return nil, fmt.Errorf("nil value") |
| 34 |
} |
| 35 |
|
| 36 |
// We currently encode the top level value directly. We have little control over nested values. |
| 37 |
// Perhaps it would be better to implement a custom Encoder that respects metadata on nested values? |
| 38 |
var buf bytes.Buffer |
| 39 |
encoder := pkg.NewEncoder(&buf) |
| 40 |
if j.options.Compact { |
| 41 |
encoder.SetIndentTables(false) |
| 42 |
encoder.SetTablesInline(true) |
| 43 |
encoder.SetArraysMultiline(false) |
| 44 |
} |
| 45 |
|
| •46 |
var outBytes []byte |
| 47 |
|
| 48 |
if value.IsMap() { |
| 49 |
goValue, err := buildGoValueForMap(value) |
| 50 |
if err != nil { |
| 51 |
return nil, fmt.Errorf("failed to construct go value: %w", err) |
| 52 |
} |
| 53 |
if err := encoder.Encode(goValue); err != nil { |
| 54 |
return nil, fmt.Errorf("toml encode failed: %w", err) |
| 55 |
} |
| 56 |
outBytes = buf.Bytes() |
| 57 |
} else { |
| 58 |
// handle scalars, slices, etc. |
| 59 |
var err error |
| 60 |
outBytes, err = encodeRootValue(encoder, &buf, value) |
| 61 |
if err != nil { |
| 62 |
return nil, err |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
// Ensure trailing newline for consistency with other format writers/tests. |
| 67 |
if len(outBytes) == 0 || outBytes[len(outBytes)-1] != '\n' { |
| 68 |
outBytes = append(outBytes, '\n') |
| 69 |
} |
| 70 |
|
| 71 |
return outBytes, nil |
| 72 |
} |
| 73 |
|
| •74 |
// rootValueKey is the placeholder key used when encoding a non-table document root. |
| 75 |
const rootValueKey = "v" |
| 76 |
|
| 77 |
// encodeRootValue encodes a top level value that isn't a map, e.g. the result of |
| 78 |
// selecting a single scalar or list out of a document. |
| 79 |
// A TOML document root must be a table, so go-toml will only encode these values |
| 80 |
// as part of a key/value pair. We encode against a placeholder key and strip the |
| 81 |
// `<key> = ` prefix back off, leaving go-toml in charge of formatting the value. |
| 82 |
func encodeRootValue(encoder *pkg.Encoder, buf *bytes.Buffer, value *model.Value) ([]byte, error) { |
| 83 |
typ, rv, err := goTypeAndValue(value) |
| 84 |
if err != nil { |
| 85 |
return nil, fmt.Errorf("failed to convert non-map top-level value: %w", err) |
| 86 |
} |
| 87 |
|
| 88 |
// A null root has no TOML representation at all. Pass the nil interface |
| 89 |
// through so go-toml reports it rather than silently writing nothing. |
| 90 |
if typ.Kind() == reflect.Interface && rv.IsZero() { |
| 91 |
if err := encoder.Encode(nil); err != nil { |
| 92 |
return nil, fmt.Errorf("toml encode failed: %w", err) |
| 93 |
} |
| 94 |
return buf.Bytes(), nil |
| 95 |
} |
| 96 |
|
| 97 |
// The inline option keeps maps and lists of maps as inline tables, rather than |
| 98 |
// go-toml emitting table headers built from the placeholder key. |
| 99 |
wrapperType := reflect.StructOf([]reflect.StructField{{ |
| 100 |
Name: "F0", |
| 101 |
Type: typ, |
| 102 |
Tag: reflect.StructTag(fmt.Sprintf(`toml:"%s,inline"`, rootValueKey)), |
| 103 |
}}) |
| 104 |
wrapper := reflect.New(wrapperType).Elem() |
| 105 |
wrapper.Field(0).Set(rv) |
| 106 |
|
| 107 |
if err := encoder.Encode(wrapper.Interface()); err != nil { |
| 108 |
return nil, fmt.Errorf("toml encode failed: %w", err) |
| 109 |
} |
| 110 |
|
| 111 |
prefix := []byte(rootValueKey + " = ") |
| 112 |
out := buf.Bytes() |
| 113 |
if !bytes.HasPrefix(out, prefix) { |
| 114 |
return nil, fmt.Errorf("toml encode failed: unexpected encoding of top-level value: %s", string(out)) |
| 115 |
} |
| 116 |
return out[len(prefix):], nil |
| 117 |
} |
| 118 |
|
| 119 |
// buildGoValueForMap constructs a reflect.Value that is a struct with fields in |
| 120 |
// the same order as keys in the provided map Value. The struct fields are |
| 121 |
// tagged with `toml:"<original key>"` so go-toml will use the original key |
| 122 |
// names when encoding. |
| 123 |
func buildGoValueForMap(v *model.Value) (interface{}, error) { |
| 124 |
kvs, err := v.MapKeyValues() |
| 125 |
if err != nil { |
| 126 |
return nil, err |
| 127 |
} |
| 128 |
|
| 129 |
// Build struct fields in order |
| 130 |
fields := make([]reflect.StructField, 0, len(kvs)) |
| 131 |
fieldValues := make([]reflect.Value, 0, len(kvs)) |
| 132 |
|
| 133 |
for i, kv := range kvs { |
| 134 |
ft, fv, err := goTypeAndValue(kv.Value) |
| 135 |
if err != nil { |
| 136 |
return nil, fmt.Errorf("error converting key %q: %w", kv.Key, err) |
| 137 |
} |
| 138 |
|
| 139 |
tomlTagContents := []string{kv.Key} |
| 140 |
|
| 141 |
// These currently do not take effect. They are placeholders for future functionality. |
| 142 |
if v, ok := kv.Value.MetadataValue(tomlStringStyleKey); ok { |
| 143 |
if style, ok := v.(string); ok && style != "" { |
| 144 |
switch style { |
| 145 |
case tomlStringStyleMultilineBasic, tomlStringStyleMultilineLiteral: |
| 146 |
tomlTagContents = append(tomlTagContents, "multiline") |
| 147 |
} |
| 148 |
} |
| 149 |
} |
| 150 |
if v, ok := kv.Value.MetadataValue(tomlTableStyleKey); ok { |
| 151 |
if style, ok := v.(string); ok && style != "" { |
| 152 |
switch style { |
| 153 |
case tomlTableStyleInline: |
| 154 |
tomlTagContents = append(tomlTagContents, "inline") |
| 155 |
} |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
// create exported field name (F0, F1...) and set tag to preserve toml key |
| 160 |
field := reflect.StructField{ |
| 161 |
Name: "F" + strconv.Itoa(i), |
| 162 |
Type: ft, |
| 163 |
Tag: reflect.StructTag(fmt.Sprintf(`toml:"%s"`, strings.Join(tomlTagContents, ","))), |
| 164 |
} |
| 165 |
fields = append(fields, field) |
| 166 |
fieldValues = append(fieldValues, fv) |
| 167 |
} |
| 168 |
|
| 169 |
structType := reflect.StructOf(fields) |
| 170 |
val := reflect.New(structType).Elem() |
| 171 |
|
| 172 |
for i := range fieldValues { |
| 173 |
val.Field(i).Set(fieldValues[i]) |
| 174 |
} |
| 175 |
|
| 176 |
return val.Interface(), nil |
| 177 |
} |
| 178 |
|
| 179 |
// goTypeAndValue returns a reflect.Type and a reflect.Value suitable for use as a |
| 180 |
// struct field/type for the given model.Value. It converts nested maps into |
| 181 |
// reflect.StructOf types recursively (preserving key order), converts slices to |
| 182 |
// slices of appropriate element types when possible, or []interface{} otherwise. |
| 183 |
func goTypeAndValue(v *model.Value) (reflect.Type, reflect.Value, error) { |
| 184 |
switch v.Type() { |
| 185 |
case model.TypeString: |
| 186 |
s, err := v.StringValue() |
| 187 |
if err != nil { |
| 188 |
return nil, reflect.Value{}, err |
| 189 |
} |
| 190 |
return reflect.TypeOf(""), reflect.ValueOf(s), nil |
| 191 |
case model.TypeInt: |
| 192 |
i, err := v.IntValue() |
| 193 |
if err != nil { |
| 194 |
return nil, reflect.Value{}, err |
| 195 |
} |
| 196 |
// use int64 to be safe |
| 197 |
return reflect.TypeOf(int64(0)), reflect.ValueOf(i), nil |
| 198 |
case model.TypeFloat: |
| 199 |
f, err := v.FloatValue() |
| 200 |
if err != nil { |
| 201 |
return nil, reflect.Value{}, err |
| 202 |
} |
| 203 |
return reflect.TypeOf(float64(0)), reflect.ValueOf(f), nil |
| 204 |
case model.TypeBool: |
| 205 |
b, err := v.BoolValue() |
| 206 |
if err != nil { |
| 207 |
return nil, reflect.Value{}, err |
| 208 |
} |
| 209 |
return reflect.TypeOf(true), reflect.ValueOf(b), nil |
| 210 |
case model.TypeNull: |
| 211 |
// represent null as interface{}(nil) |
| 212 |
return reflect.TypeOf((*interface{})(nil)).Elem(), reflect.Zero(reflect.TypeOf((*interface{})(nil)).Elem()), nil |
| 213 |
case model.TypeMap: |
| 214 |
// For nested maps, prefer map[string]interface{} values rather than |
| 215 |
// generating nested struct types. Using struct types for nested maps |
| 216 |
// causes go-toml to emit explicit table headers for those nested |
| 217 |
// structures which can change the document shape on round-trip. The |
| 218 |
// top-level map is still handled by buildGoValueForMap which generates |
| 219 |
// a struct to preserve ordering. |
| 220 |
kvs, err := v.MapKeyValues() |
| 221 |
if err != nil { |
| 222 |
return nil, reflect.Value{}, err |
| 223 |
} |
| 224 |
m := make(map[string]interface{}) |
| 225 |
for _, kv := range kvs { |
| 226 |
_, rv, err := goTypeAndValue(kv.Value) |
| 227 |
if err != nil { |
| 228 |
return nil, reflect.Value{}, fmt.Errorf("error in nested key %q: %w", kv.Key, err) |
| 229 |
} |
| 230 |
m[kv.Key] = rv.Interface() |
| 231 |
} |
| 232 |
return reflect.TypeOf(map[string]interface{}{}), reflect.ValueOf(m), nil |
| 233 |
case model.TypeSlice: |
| 234 |
// Decide element types. If all elements are maps and have compatible keys, |
| 235 |
// build a struct type for elements and return a slice of that struct type. |
| 236 |
length, _ := v.SliceLen() |
| 237 |
if length == 0 { |
| 238 |
// empty slice -> use []interface{} |
| 239 |
elemType := reflect.TypeOf((*interface{})(nil)).Elem() |
| 240 |
return reflect.SliceOf(elemType), reflect.MakeSlice(reflect.SliceOf(elemType), 0, 0), nil |
| 241 |
} |
| 242 |
|
| 243 |
// inspect first element |
| 244 |
first, _ := v.GetSliceIndex(0) |
| 245 |
if first.IsMap() { |
| 246 |
// Collect union of keys across elements in order of appearance |
| 247 |
seen := map[string]bool{} |
| 248 |
keys := make([]string, 0) |
| 249 |
_ = v.RangeSlice(func(_ int, item *model.Value) error { |
| 250 |
if !item.IsMap() { |
| 251 |
// mixed types -> fallback to []interface{} |
| 252 |
keys = nil |
| 253 |
return nil |
| 254 |
} |
| 255 |
kvs, _ := item.MapKeyValues() |
| 256 |
for _, kv := range kvs { |
| 257 |
if !seen[kv.Key] { |
| 258 |
seen[kv.Key] = true |
| 259 |
keys = append(keys, kv.Key) |
| 260 |
} |
| 261 |
} |
| 262 |
return nil |
| 263 |
}) |
| 264 |
|
| 265 |
if keys != nil { |
| 266 |
// Build []map[string]interface{} to preserve keys and values without |
| 267 |
// forcing a generated struct type which can cause conversion issues. |
| 268 |
sliceMaps := make([]map[string]interface{}, 0, length) |
| 269 |
_ = v.RangeSlice(func(_ int, item *model.Value) error { |
| 270 |
m := map[string]interface{}{} |
| 271 |
if item.IsMap() { |
| 272 |
kvs, _ := item.MapKeyValues() |
| 273 |
for _, kv := range kvs { |
| 274 |
_, rv, err := goTypeAndValue(kv.Value) |
| 275 |
if err != nil { |
| 276 |
return err |
| 277 |
} |
| 278 |
m[kv.Key] = rv.Interface() |
| 279 |
} |
| 280 |
} |
| 281 |
sliceMaps = append(sliceMaps, m) |
| 282 |
return nil |
| 283 |
}) |
| 284 |
return reflect.TypeOf([]map[string]interface{}{}), reflect.ValueOf(sliceMaps), nil |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
// fallback: build []interface{} |
| 289 |
elems := make([]interface{}, 0, length) |
| 290 |
_ = v.RangeSlice(func(_ int, item *model.Value) error { |
| 291 |
gt, rv, err := goTypeAndValue(item) |
| 292 |
if err != nil { |
| 293 |
return err |
| 294 |
} |
| 295 |
// convert reflect.Value to interface{} |
| 296 |
elems = append(elems, rv.Interface()) |
| 297 |
_ = gt |
| 298 |
return nil |
| 299 |
}) |
| 300 |
return reflect.TypeOf([]interface{}{}), reflect.ValueOf(elems), nil |
| 301 |
default: |
| 302 |
// fallback to stringified interface |
| 303 |
s := fmt.Sprintf("%v", v.Interface()) |
| 304 |
return reflect.TypeOf(""), reflect.ValueOf(s), nil |
| 305 |
} |
| 306 |
} |