-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.go
More file actions
226 lines (184 loc) · 4.66 KB
/
Copy pathdecoder.go
File metadata and controls
226 lines (184 loc) · 4.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package gotoon
import (
"regexp"
"strconv"
"strings"
)
// Decoder handles decoding TOON format strings to Go data structures.
type Decoder struct {
config *Config
unflattener *ArrayUnflattener
}
// NewDecoder creates a new Decoder with the given configuration.
func NewDecoder(config *Config) *Decoder {
if config == nil {
config = DefaultConfig()
}
return &Decoder{
config: config,
unflattener: NewArrayUnflattener(),
}
}
// Decode converts a TOON format string to Go data structures.
func (d *Decoder) Decode(toon string) (map[string]any, error) {
lines := strings.Split(toon, "\n")
result := make(map[string]any)
type stackItem struct {
data map[string]any
indent int
key string
}
stack := []stackItem{{data: result, indent: -1, key: ""}}
i := 0
for i < len(lines) {
line := lines[i]
if strings.TrimSpace(line) == "" {
i++
continue
}
indent := len(line) - len(strings.TrimLeft(line, " "))
content := strings.TrimSpace(line)
for len(stack) > 1 && indent <= stack[len(stack)-1].indent {
stack = stack[:len(stack)-1]
}
current := stack[len(stack)-1].data
if match := regexp.MustCompile(`^items\[(\d+)\]\{([^\}]*)\}:$`).FindStringSubmatch(content); match != nil {
rowCount, _ := strconv.Atoi(match[1])
columnsStr := match[2]
var columns []string
if columnsStr != "" {
columns = strings.Split(columnsStr, ",")
for j := range columns {
columns[j] = strings.TrimSpace(columns[j])
}
}
rows := [][]any{}
for j := 0; j < rowCount && (i+1+j) < len(lines); j++ {
rowLine := lines[i+1+j]
rowContent := strings.TrimSpace(rowLine)
if rowContent == "" {
continue
}
cells := d.parseRow(rowContent, len(columns))
rows = append(rows, cells)
}
i += rowCount
var items []any
if hasNestedColumns(columns) {
objects := d.unflattener.Unflatten(rows, columns)
items = make([]any, len(objects))
for idx, obj := range objects {
items[idx] = obj
}
} else {
items = d.rowsToObjects(rows, columns)
}
if len(stack) > 1 {
parentKey := stack[len(stack)-1].key
parentData := stack[len(stack)-2].data
parentData[parentKey] = items
} else {
current["_items"] = items
}
} else if strings.HasSuffix(content, ":") && !strings.Contains(content, ": ") {
key := strings.TrimSuffix(content, ":")
current[key] = make(map[string]any)
stack = append(stack, stackItem{
data: current[key].(map[string]any),
indent: indent,
key: key,
})
} else if strings.Contains(content, ": ") {
parts := strings.SplitN(content, ": ", 2)
key := parts[0]
value := d.parseValue(parts[1])
current[key] = value
}
i++
}
if items, exists := result["_items"]; exists {
return map[string]any{"items": items}, nil
}
return result, nil
}
// parseRow parses a CSV-like row with escape handling.
func (d *Decoder) parseRow(row string, expectedCount int) []any {
cells := []any{}
current := ""
escaped := false
for i := 0; i < len(row); i++ {
char := row[i]
if escaped {
current += string(char)
escaped = false
continue
}
if char == '\\' {
escaped = true
continue
}
if char == ',' {
cells = append(cells, d.parseValue(current))
current = ""
continue
}
current += string(char)
}
cells = append(cells, d.parseValue(current))
for len(cells) < expectedCount {
cells = append(cells, nil)
}
return cells
}
// parseValue converts a string value to its appropriate type.
func (d *Decoder) parseValue(value string) any {
value = strings.TrimSpace(value)
if value == "" || value == "null" {
return nil
}
if value == "true" {
return true
}
if value == "false" {
return false
}
if strings.Contains(value, ".") {
if f, err := strconv.ParseFloat(value, 64); err == nil {
return f
}
} else {
if i, err := strconv.ParseInt(value, 10, 64); err == nil {
return int(i)
}
}
value = strings.ReplaceAll(value, "\\n", "\n")
value = strings.ReplaceAll(value, "\\,", ",")
value = strings.ReplaceAll(value, "\\:", ":")
value = strings.ReplaceAll(value, "\\\\", "\\")
return value
}
// rowsToObjects converts rows to objects (non-nested case).
func (d *Decoder) rowsToObjects(rows [][]any, columns []string) []any {
objects := make([]any, len(rows))
for i, row := range rows {
obj := make(map[string]any)
for j, col := range columns {
if j < len(row) {
obj[col] = row[j]
} else {
obj[col] = nil
}
}
objects[i] = obj
}
return objects
}
// hasNestedColumns checks if any column contains a dot (nested path).
func hasNestedColumns(columns []string) bool {
for _, col := range columns {
if strings.Contains(col, ".") {
return true
}
}
return false
}