| 1 | package toml |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "strconv" |
| 7 | |
| 8 | "github.com/pelletier/go-toml/v2/unstable" |
| 9 | "github.com/tomwright/dasel/v3/model" |
| 10 | "github.com/tomwright/dasel/v3/parsing" |
| 11 | ) |
| 12 | |
| 13 | var _ parsing.Reader = (*tomlReader)(nil) |
| 14 | |
| 15 | func newTOMLReader(options parsing.ReaderOptions) (parsing.Reader, error) { |
| 16 | return &tomlReader{}, nil |
| 17 | } |
| 18 | |
| 19 | const ( |
| 20 | tomlStringStyleKey = "toml_string_style" |
| 21 | |
| 22 | tomlStringStyleMultilineLiteral = "multiline_literal" |
| 23 | tomlStringStyleMultilineBasic = "multiline_basic" |
| 24 | tomlStringStyleLiteral = "literal" |
| 25 | tomlStringStyleBasic = "basic" |
| 26 | |
| 27 | tomlTableStyleKey = "toml_table_style" |
| 28 | tomlTableStyleStandard = "standard" |
| 29 | tomlTableStyleArray = "array" |
| 30 | tomlTableStyleInline = "inline" |
| 31 | ) |
| 32 | |
| 33 | type tomlReader struct{} |
| 34 | |
| 35 | // Read reads a value from a byte slice. |
| 36 | func (j *tomlReader) Read(data []byte) (*model.Value, error) { |
| 37 | p := &unstable.Parser{} |
| 38 | p.Reset(data) |
| 39 | |
| 40 | root := model.NewMapValue() |
| 41 | |
| 42 | var active *model.Value |
| 43 | |
| 44 | for p.NextExpression() { |
| 45 | expr := p.Expression() |
| 46 | switch expr.Kind { |
| 47 | case unstable.Invalid, unstable.Comment: |
| 48 | // ignore |
| 49 | continue |
| 50 | case unstable.KeyValue: |
| 51 | keyParts, val, err := j.parseKeyValueNode(p, expr) |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | if active != nil { |
| 56 | if err := setDottedKey(root, active, keyParts, val); err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | } else { |
| 60 | if err := setDottedKey(root, nil, keyParts, val); err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | case unstable.Table: |
| 66 | parts, quoted, err := extractKeyFromTableNode(p, expr) |
| 67 | if err != nil { |
| 68 | return nil, err |
| 69 | } |
| 70 | m, err := ensureMapAt(root, parts) |
| 71 | if err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | // Record table header parts and quoting info on the map so the writer |
| 75 | // can reproduce the header exactly if needed. |
| 76 | m.SetMetadataValue(tomlTableStyleKey, tomlTableStyleStandard) |
| 77 | m.SetMetadataValue("toml_table_header_parts", parts) |
| 78 | m.SetMetadataValue("toml_table_header_quoted", quoted) |
| 79 | active = m |
| 80 | |
| 81 | case unstable.ArrayTable: |
| 82 | parts, quoted, err := extractKeyFromTableNode(p, expr) |
| 83 | if err != nil { |
| 84 | return nil, err |
| 85 | } |
| 86 | slice, err := ensureSliceAt(root, parts) |
| 87 | if err != nil { |
| 88 | return nil, err |
| 89 | } |
| 90 | obj := model.NewMapValue() |
| 91 | // Mark this object as created via an array table so the writer can |
| 92 | // emit [[...]] headers for it. |
| 93 | obj.SetMetadataValue(tomlTableStyleKey, tomlTableStyleArray) |
| 94 | obj.SetMetadataValue("toml_table_header_parts", parts) |
| 95 | obj.SetMetadataValue("toml_table_header_quoted", quoted) |
| 96 | if err := slice.Append(obj); err != nil { |
| 97 | return nil, err |
| 98 | } |
| 99 | active = obj |
| 100 | |
| 101 | default: |
| 102 | // top-level value nodes are unexpected; ignore |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | return root, nil |
| 107 | } |
| 108 | |
| 109 | // readNode parses a value node (not table/keyvalue headers). |
| 110 | func (j *tomlReader) readNode(p *unstable.Parser, n *unstable.Node) (string, *model.Value, error) { |
| 111 | switch n.Kind { |
| 112 | // Meta |
| 113 | case unstable.Invalid: |
| 114 | return "", nil, nil |
| 115 | case unstable.Comment: |
| 116 | return "", nil, nil |
| 117 | case unstable.Key: |
| 118 | return "", model.NewStringValue(string(n.Data)), nil |
| 119 | |
| 120 | // Container values |
| 121 | case unstable.Array: |
| 122 | v, err := j.readArrayValue(p, n) |
| 123 | return "", v, err |
| 124 | case unstable.InlineTable: |
| 125 | return j.readInlineTable(p, n) |
| 126 | |
| 127 | // Values |
| 128 | case unstable.String: |
| 129 | v := model.NewStringValue(string(n.Data)) |
| 130 | |
| 131 | raw := p.Raw(n.Raw) |
| 132 | switch { |
| 133 | case len(raw) >= 3 && bytes.HasPrefix(raw, []byte("''")) && bytes.HasPrefix(raw, []byte("'''")): |
| 134 | v.SetMetadataValue(tomlStringStyleKey, tomlStringStyleMultilineLiteral) |
| 135 | case len(raw) >= 3 && bytes.HasPrefix(raw, []byte("\"\"\"")): |
| 136 | v.SetMetadataValue(tomlStringStyleKey, tomlStringStyleMultilineBasic) |
| 137 | case len(raw) >= 1 && raw[0] == '\'': |
| 138 | v.SetMetadataValue(tomlStringStyleKey, tomlStringStyleLiteral) |
| 139 | default: |
| 140 | v.SetMetadataValue(tomlStringStyleKey, tomlStringStyleBasic) |
| 141 | } |
| 142 | |
| 143 | return "", v, nil |
| 144 | case unstable.Bool: |
| 145 | return "", model.NewBoolValue(string(n.Data) == "true"), nil |
| 146 | case unstable.Float: |
| 147 | f, err := strconv.ParseFloat(string(n.Data), 64) |
| 148 | if err != nil { |
| 149 | return "", nil, err |
| 150 | } |
| 151 | return "", model.NewFloatValue(f), nil |
| 152 | case unstable.Integer: |
| 153 | i64, err := strconv.ParseInt(string(n.Data), 0, 64) |
| 154 | if err != nil { |
| 155 | return "", nil, err |
| 156 | } |
| 157 | return "", model.NewIntValue(int64(i64)), nil |
| 158 | case unstable.LocalDate: |
| 159 | return "", model.NewStringValue(string(n.Data)), nil |
| 160 | case unstable.LocalTime: |
| 161 | return "", model.NewStringValue(string(n.Data)), nil |
| 162 | case unstable.LocalDateTime: |
| 163 | return "", model.NewStringValue(string(n.Data)), nil |
| 164 | case unstable.DateTime: |
| 165 | return "", model.NewStringValue(string(n.Data)), nil |
| 166 | default: |
| 167 | return "", nil, fmt.Errorf("unhandled node kind: %s", n.Kind.String()) |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | // parseKeyValueNode extracts the key segments and value from a KeyValue node without consuming parser expressions. |
| 172 | func (j *tomlReader) parseKeyValueNode(p *unstable.Parser, n *unstable.Node) ([]string, *model.Value, error) { |
| 173 | i := n.Children() |
| 174 | var keyParts []string |
| 175 | var val *model.Value |
| 176 | |
| 177 | for i.Next() { |
| 178 | child := i.Node() |
| 179 | if child.Kind == unstable.Key { |
| 180 | keyParts = append(keyParts, string(child.Data)) |
| 181 | continue |
| 182 | } |
| 183 | _, v, err := j.readNode(p, child) |
| 184 | if err != nil { |
| 185 | return nil, nil, err |
| 186 | } |
| 187 | val = v |
| 188 | } |
| 189 | |
| 190 | if len(keyParts) == 0 { |
| 191 | return nil, nil, fmt.Errorf("missing key in key/value node") |
| 192 | } |
| 193 | if val == nil { |
| 194 | return nil, nil, fmt.Errorf("missing value in key/value node") |
| 195 | } |
| 196 | |
| 197 | return keyParts, val, nil |
| 198 | } |
| 199 | |
| 200 | // extractKeyFromTableNode returns the key segments from a Table/ArrayTable node. |
| 201 | func extractKeyFromTableNode(p *unstable.Parser, n *unstable.Node) ([]string, []bool, error) { |
| 202 | i := n.Children() |
| 203 | var parts []string |
| 204 | var quoted []bool |
| 205 | for i.Next() { |
| 206 | child := i.Node() |
| 207 | if child.Kind == unstable.Key { |
| 208 | parts = append(parts, string(child.Data)) |
| 209 | raw := p.Raw(child.Raw) |
| 210 | isQuoted := false |
| 211 | if len(raw) > 0 && (raw[0] == '"' || raw[0] == '\'') { |
| 212 | isQuoted = true |
| 213 | } |
| 214 | quoted = append(quoted, isQuoted) |
| 215 | continue |
| 216 | } |
| 217 | return nil, nil, fmt.Errorf("expected table child node, got %s", child.Kind.String()) |
| 218 | } |
| 219 | if len(parts) == 0 { |
| 220 | return nil, nil, fmt.Errorf("missing table child key node") |
| 221 | } |
| 222 | return parts, quoted, nil |
| 223 | } |
| 224 | |
| 225 | // ensureMapAt ensures a map exists at the dotted path under root and returns it. |
| 226 | func ensureMapAt(root *model.Value, path []string) (*model.Value, error) { |
| 227 | if len(path) == 0 { |
| 228 | return root, nil |
| 229 | } |
| 230 | cur := root |
| 231 | for _, seg := range path { |
| 232 | exists, err := cur.MapKeyExists(seg) |
| 233 | if err != nil { |
| 234 | return nil, err |
| 235 | } |
| 236 | if !exists { |
| 237 | m := model.NewMapValue() |
| 238 | if err := cur.SetMapKey(seg, m); err != nil { |
| 239 | return nil, err |
| 240 | } |
| 241 | cur = m |
| 242 | continue |
| 243 | } |
| 244 | next, err := cur.GetMapKey(seg) |
| 245 | if err != nil { |
| 246 | return nil, err |
| 247 | } |
| 248 | if next.IsSlice() { |
| 249 | sliceLen, err := next.Len() |
| 250 | if err != nil { |
| 251 | return nil, err |
| 252 | } |
| 253 | next, err = next.GetSliceIndex(sliceLen - 1) |
| 254 | if err != nil { |
| 255 | return nil, err |
| 256 | } |
| 257 | } |
| 258 | if !next.IsMap() { |
| 259 | return nil, fmt.Errorf("conflicting types at path '%s': expected map", seg) |
| 260 | } |
| 261 | cur = next |
| 262 | } |
| 263 | return cur, nil |
| 264 | } |
| 265 | |
| 266 | // ensureSliceAt ensures a slice exists at the dotted path under root and returns it. |
| 267 | func ensureSliceAt(root *model.Value, path []string) (*model.Value, error) { |
| 268 | if len(path) == 0 { |
| 269 | return nil, fmt.Errorf("empty path for array table") |
| 270 | } |
| 271 | parentPath := path[:len(path)-1] |
| 272 | finalSeg := path[len(path)-1] |
| 273 | parent, err := ensureMapAt(root, parentPath) |
| 274 | if err != nil { |
| 275 | return nil, err |
| 276 | } |
| 277 | exists, err := parent.MapKeyExists(finalSeg) |
| 278 | if err != nil { |
| 279 | return nil, err |
| 280 | } |
| 281 | if !exists { |
| 282 | s := model.NewSliceValue() |
| 283 | if err := parent.SetMapKey(finalSeg, s); err != nil { |
| 284 | return nil, err |
| 285 | } |
| 286 | return s, nil |
| 287 | } |
| 288 | v, err := parent.GetMapKey(finalSeg) |
| 289 | if err != nil { |
| 290 | return nil, err |
| 291 | } |
| 292 | if !v.IsSlice() { |
| 293 | return nil, fmt.Errorf("conflicting types at path '%s': expected slice", finalSeg) |
| 294 | } |
| 295 | return v, nil |
| 296 | } |
| 297 | |
| 298 | // setDottedKey sets a value at a (possibly dotted) key within the given container (creating intermediate maps). |
| 299 | // If active is non-nil, it is the current table object to set keys relative to; root is only used when active is nil to |
| 300 | // create implicit parent maps on the root. |
| 301 | func setDottedKey(root, active *model.Value, parts []string, val *model.Value) error { |
| 302 | if len(parts) == 0 { |
| 303 | return fmt.Errorf("empty key") |
| 304 | } |
| 305 | // If active table provided, we should set relative to it. But parts may be dotted (i.e., multiple segments). |
| 306 | if active != nil { |
| 307 | if len(parts) == 1 { |
| 308 | return active.SetMapKey(parts[0], val) |
| 309 | } |
| 310 | parent, err := ensureMapAt(active, parts[:len(parts)-1]) |
| 311 | if err != nil { |
| 312 | return err |
| 313 | } |
| 314 | return parent.SetMapKey(parts[len(parts)-1], val) |
| 315 | } |
| 316 | // No active table: set on root |
| 317 | if len(parts) == 1 { |
| 318 | return root.SetMapKey(parts[0], val) |
| 319 | } |
| 320 | parent, err := ensureMapAt(root, parts[:len(parts)-1]) |
| 321 | if err != nil { |
| 322 | return err |
| 323 | } |
| 324 | return parent.SetMapKey(parts[len(parts)-1], val) |
| 325 | } |
| 326 | |
| 327 | func (j *tomlReader) readInlineTable(p *unstable.Parser, n *unstable.Node) (string, *model.Value, error) { |
| 328 | res := model.NewMapValue() |
| 329 | res.SetMetadataValue(tomlTableStyleKey, tomlTableStyleInline) |
| 330 | |
| 331 | i := n.Children() |
| 332 | for i.Next() { |
| 333 | childNode := i.Node() |
| 334 | // Inline table children are key/value pairs. Handle KeyValue specially. |
| 335 | switch childNode.Kind { |
| 336 | case unstable.KeyValue: |
| 337 | kparts, v, err := j.parseKeyValueNode(p, childNode) |
| 338 | if err != nil { |
| 339 | return "", nil, err |
| 340 | } |
| 341 | if err := setDottedKey(res, nil, kparts, v); err != nil { |
| 342 | return "", nil, err |
| 343 | } |
| 344 | default: |
| 345 | // fallback to readNode for other kinds (e.g., Key) |
| 346 | key, val, err := j.readNode(p, childNode) |
| 347 | if err != nil { |
| 348 | return "", nil, err |
| 349 | } |
| 350 | if key == "" { |
| 351 | return "", nil, fmt.Errorf("missing key in inline table child") |
| 352 | } |
| 353 | if err := res.SetMapKey(key, val); err != nil { |
| 354 | return "", nil, err |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | return "", res, nil |
| 360 | } |
| 361 | |
| 362 | func (j *tomlReader) readArrayValue(p *unstable.Parser, n *unstable.Node) (*model.Value, error) { |
| 363 | res := model.NewSliceValue() |
| 364 | |
| 365 | i := n.Children() |
| 366 | |
| 367 | for i.Next() { |
| 368 | childNode := i.Node() |
| 369 | |
| 370 | _, val, err := j.readNode(p, childNode) |
| 371 | if err != nil { |
| 372 | return nil, err |
| 373 | } |
| 374 | |
| 375 | val.SetMetadataValue(tomlTableStyleKey, tomlTableStyleArray) |
| 376 | |
| 377 | if err := res.Append(val); err != nil { |
| 378 | return nil, err |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | return res, nil |
| 383 | } |