Debian Codegraph @

parsing/toml/toml_writer.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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 var goValue interface{}
37 var err error
38
39 if value.IsMap() {
40 goValue, err = buildGoValueForMap(value)
41 if err != nil {
42 return nil, fmt.Errorf("failed to construct go value: %w", err)
43 }
44 } else {
45 // handle scalars, slices, etc. Use goTypeAndValue to get a concrete reflect.Value
46 typ, rv, err := goTypeAndValue(value)
47 if err != nil {
48 return nil, fmt.Errorf("failed to convert non-map top-level value: %w", err)
49 }
50 // For nil/zero interface, ensure we pass nil interface rather than a typed zero.
51 if typ.Kind() == reflect.Interface && rv.IsZero() {
52 goValue = nil
53 } else {
54 goValue = rv.Interface()
55 }
56 }
57
58 // We currently encode the top level value directly. We have little control over nested values.
59 // Perhaps it would be better to implement a custom Encoder that respects metadata on nested values?
60 var buf bytes.Buffer
61 encoder := pkg.NewEncoder(&buf)
62 if j.options.Compact {
63 encoder.SetIndentTables(false)
64 encoder.SetTablesInline(true)
65 encoder.SetArraysMultiline(false)
66 }
67
68 if err := encoder.Encode(goValue); err != nil {
69 return nil, fmt.Errorf("toml encode failed: %w", err)
70 }
71 outBytes := buf.Bytes()
72
73 // Ensure trailing newline for consistency with other format writers/tests.
74 if len(outBytes) == 0 || outBytes[len(outBytes)-1] != '\n' {
75 outBytes = append(outBytes, '\n')
76 }
77
78 return outBytes, nil
79 }
80
81 // buildGoValueForMap constructs a reflect.Value that is a struct with fields in
82 // the same order as keys in the provided map Value. The struct fields are
83 // tagged with `toml:"<original key>"` so go-toml will use the original key
84 // names when encoding.
85 func buildGoValueForMap(v *model.Value) (interface{}, error) {
86 kvs, err := v.MapKeyValues()
87 if err != nil {
88 return nil, err
89 }
90
91 // Build struct fields in order
92 fields := make([]reflect.StructField, 0, len(kvs))
93 fieldValues := make([]reflect.Value, 0, len(kvs))
94
95 for i, kv := range kvs {
96 ft, fv, err := goTypeAndValue(kv.Value)
97 if err != nil {
98 return nil, fmt.Errorf("error converting key %q: %w", kv.Key, err)
99 }
100
101 tomlTagContents := []string{kv.Key}
102
103 // These currently do not take effect. They are placeholders for future functionality.
104 if v, ok := kv.Value.MetadataValue(tomlStringStyleKey); ok {
105 if style, ok := v.(string); ok && style != "" {
106 switch style {
107 case tomlStringStyleMultilineBasic, tomlStringStyleMultilineLiteral:
108 tomlTagContents = append(tomlTagContents, "multiline")
109 }
110 }
111 }
112 if v, ok := kv.Value.MetadataValue(tomlTableStyleKey); ok {
113 if style, ok := v.(string); ok && style != "" {
114 switch style {
115 case tomlTableStyleInline:
116 tomlTagContents = append(tomlTagContents, "inline")
117 }
118 }
119 }
120
121 // create exported field name (F0, F1...) and set tag to preserve toml key
122 field := reflect.StructField{
123 Name: "F" + strconv.Itoa(i),
124 Type: ft,
125 Tag: reflect.StructTag(fmt.Sprintf(`toml:"%s"`, strings.Join(tomlTagContents, ","))),
126 }
127 fields = append(fields, field)
128 fieldValues = append(fieldValues, fv)
129 }
130
131 structType := reflect.StructOf(fields)
132 val := reflect.New(structType).Elem()
133
134 for i := range fieldValues {
135 val.Field(i).Set(fieldValues[i])
136 }
137
138 return val.Interface(), nil
139 }
140
141 // goTypeAndValue returns a reflect.Type and a reflect.Value suitable for use as a
142 // struct field/type for the given model.Value. It converts nested maps into
143 // reflect.StructOf types recursively (preserving key order), converts slices to
144 // slices of appropriate element types when possible, or []interface{} otherwise.
145 func goTypeAndValue(v *model.Value) (reflect.Type, reflect.Value, error) {
146 switch v.Type() {
147 case model.TypeString:
148 s, err := v.StringValue()
149 if err != nil {
150 return nil, reflect.Value{}, err
151 }
152 return reflect.TypeOf(""), reflect.ValueOf(s), nil
153 case model.TypeInt:
154 i, err := v.IntValue()
155 if err != nil {
156 return nil, reflect.Value{}, err
157 }
158 // use int64 to be safe
159 return reflect.TypeOf(int64(0)), reflect.ValueOf(i), nil
160 case model.TypeFloat:
161 f, err := v.FloatValue()
162 if err != nil {
163 return nil, reflect.Value{}, err
164 }
165 return reflect.TypeOf(float64(0)), reflect.ValueOf(f), nil
166 case model.TypeBool:
167 b, err := v.BoolValue()
168 if err != nil {
169 return nil, reflect.Value{}, err
170 }
171 return reflect.TypeOf(true), reflect.ValueOf(b), nil
172 case model.TypeNull:
173 // represent null as interface{}(nil)
174 return reflect.TypeOf((*interface{})(nil)).Elem(), reflect.Zero(reflect.TypeOf((*interface{})(nil)).Elem()), nil
175 case model.TypeMap:
176 // For nested maps, prefer map[string]interface{} values rather than
177 // generating nested struct types. Using struct types for nested maps
178 // causes go-toml to emit explicit table headers for those nested
179 // structures which can change the document shape on round-trip. The
180 // top-level map is still handled by buildGoValueForMap which generates
181 // a struct to preserve ordering.
182 kvs, err := v.MapKeyValues()
183 if err != nil {
184 return nil, reflect.Value{}, err
185 }
186 m := make(map[string]interface{})
187 for _, kv := range kvs {
188 _, rv, err := goTypeAndValue(kv.Value)
189 if err != nil {
190 return nil, reflect.Value{}, fmt.Errorf("error in nested key %q: %w", kv.Key, err)
191 }
192 m[kv.Key] = rv.Interface()
193 }
194 return reflect.TypeOf(map[string]interface{}{}), reflect.ValueOf(m), nil
195 case model.TypeSlice:
196 // Decide element types. If all elements are maps and have compatible keys,
197 // build a struct type for elements and return a slice of that struct type.
198 length, _ := v.SliceLen()
199 if length == 0 {
200 // empty slice -> use []interface{}
201 elemType := reflect.TypeOf((*interface{})(nil)).Elem()
202 return reflect.SliceOf(elemType), reflect.MakeSlice(reflect.SliceOf(elemType), 0, 0), nil
203 }
204
205 // inspect first element
206 first, _ := v.GetSliceIndex(0)
207 if first.IsMap() {
208 // Collect union of keys across elements in order of appearance
209 seen := map[string]bool{}
210 keys := make([]string, 0)
211 _ = v.RangeSlice(func(_ int, item *model.Value) error {
212 if !item.IsMap() {
213 // mixed types -> fallback to []interface{}
214 keys = nil
215 return nil
216 }
217 kvs, _ := item.MapKeyValues()
218 for _, kv := range kvs {
219 if !seen[kv.Key] {
220 seen[kv.Key] = true
221 keys = append(keys, kv.Key)
222 }
223 }
224 return nil
225 })
226
227 if keys != nil {
228 // Build []map[string]interface{} to preserve keys and values without
229 // forcing a generated struct type which can cause conversion issues.
230 sliceMaps := make([]map[string]interface{}, 0, length)
231 _ = v.RangeSlice(func(_ int, item *model.Value) error {
232 m := map[string]interface{}{}
233 if item.IsMap() {
234 kvs, _ := item.MapKeyValues()
235 for _, kv := range kvs {
236 _, rv, err := goTypeAndValue(kv.Value)
237 if err != nil {
238 return err
239 }
240 m[kv.Key] = rv.Interface()
241 }
242 }
243 sliceMaps = append(sliceMaps, m)
244 return nil
245 })
246 return reflect.TypeOf([]map[string]interface{}{}), reflect.ValueOf(sliceMaps), nil
247 }
248 }
249
250 // fallback: build []interface{}
251 elems := make([]interface{}, 0, length)
252 _ = v.RangeSlice(func(_ int, item *model.Value) error {
253 gt, rv, err := goTypeAndValue(item)
254 if err != nil {
255 return err
256 }
257 // convert reflect.Value to interface{}
258 elems = append(elems, rv.Interface())
259 _ = gt
260 return nil
261 })
262 return reflect.TypeOf([]interface{}{}), reflect.ValueOf(elems), nil
263 default:
264 // fallback to stringified interface
265 s := fmt.Sprintf("%v", v.Interface())
266 return reflect.TypeOf(""), reflect.ValueOf(s), nil
267 }
268 }