-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathKeyDecoder.java
More file actions
342 lines (305 loc) · 14 KB
/
Copy pathKeyDecoder.java
File metadata and controls
342 lines (305 loc) · 14 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package dev.toonformat.jtoon.decoder;
import dev.toonformat.jtoon.PathExpansion;
import dev.toonformat.jtoon.util.StringEscaper;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import static dev.toonformat.jtoon.util.Headers.KEYED_ARRAY_PATTERN;
/**
* Handles decoding of key values/arrays to JSON format.
*/
public class KeyDecoder {
private KeyDecoder() { throw new UnsupportedOperationException("Utility class cannot be instantiated"); }
/**
* Processes a keyed array line (e.g., "key[3]: value").
* @param result result
* @param content the content string to parse
* @param keyedArray keyed array
* @param parentDepth parent depth of keyed array line
* @param context decode object in order to deal with lines, delimiter and options
*/
protected static void processKeyedArrayLine(Map<String, Object> result, String content, Matcher keyedArray,
int parentDepth, DecodeContext context) {
String originalKey = keyedArray.group(1).trim();
String key = StringEscaper.unescape(originalKey);
String arrayHeader = content.substring(keyedArray.group(1).length());
List<Object> arrayValue = ArrayDecoder.parseArray(arrayHeader, parentDepth + 1, context);
// Handle path expansion for array keys
if (shouldExpandKey(originalKey, context)) {
expandPathIntoMap(result, key, arrayValue, context);
} else {
// Check for conflicts with existing expanded paths
DecodeHelper.checkPathExpansionConflict(result, key, arrayValue, context);
result.put(key, arrayValue);
}
}
/**
* Expands a dotted key into nested object structure.
* @param map map
* @param dottedKey dottedKey
* @param value value
* @param context decode object in order to deal with lines, delimiter and options
*/
protected static void expandPathIntoMap(Map<String, Object> map, String dottedKey, Object value, DecodeContext context) {
String[] segments = dottedKey.split("\\.");
Map<String, Object> current = map;
// Navigate/create nested structure
for (int i = 0; i < segments.length - 1; i++) {
String segment = segments[i];
Object existing = current.get(segment);
if (existing == null) {
// Create new nested object
Map<String, Object> nested = new LinkedHashMap<>();
current.put(segment, nested);
current = nested;
} else if (existing instanceof Map) {
// Use existing nested object
@SuppressWarnings("unchecked")
Map<String, Object> existingMap = (Map<String, Object>) existing;
current = existingMap;
} else {
// Conflict: existing is not a Map
if (context.options.strict()) {
throw new IllegalArgumentException(
String.format("Path expansion conflict: %s is %s, cannot expand to object",
segment, existing.getClass().getSimpleName()));
}
// LWW: overwrite with new nested object
Map<String, Object> nested = new LinkedHashMap<>();
current.put(segment, nested);
current = nested;
}
}
// Set final value
String finalSegment = segments[segments.length - 1];
Object existing = current.get(finalSegment);
DecodeHelper.checkFinalValueConflict(finalSegment, existing, value, context);
// LWW: last write wins (always overwrite in non-strict, or if types match in
// strict)
current.put(finalSegment, value);
}
/**
* Processes a key-value line (e.g., "key: value").
* @param result result
* @param content the content string to parse
* @param depth the depth of the value line
* @param context decode object in order to deal with lines, delimiter and options
*/
protected static void processKeyValueLine(Map<String, Object> result, String content, int depth, DecodeContext context) {
int colonIdx = DecodeHelper.findUnquotedColon(content);
if (colonIdx > 0) {
String key = content.substring(0, colonIdx).trim();
String value = content.substring(colonIdx + 1).trim();
parseKeyValuePairIntoMap(result, key, value, depth, context);
} else {
// No colon found in key-value context - this is an error
if (context.options.strict()) {
throw new IllegalArgumentException(
"Missing colon in key-value context at line " + (context.currentLine + 1));
}
context.currentLine++;
}
}
/**
* Parses a key-value pair and adds it to an existing map.
* @param map existing map
* @param key key
* @param value the value string to parse
* @param depth the depth of the value pair
* @param context decode object in order to deal with lines, delimiter and options
*/
protected static void parseKeyValuePairIntoMap(Map<String, Object> map, String key, String value,
int depth, DecodeContext context) {
String unescapedKey = StringEscaper.unescape(key);
Object parsedValue = parseKeyValue(value, depth, context);
putKeyValueIntoMap(map, key, unescapedKey, parsedValue, context);
}
/**
* Checks if a key should be expanded (is a valid identifier segment).
* Keys with dots that are valid identifiers can be expanded.
* Quoted keys are never expanded.
* @param key key
* @param context decode object in order to deal with lines, delimiter and options
* @return true if key should be expanded or false if not
*/
protected static boolean shouldExpandKey(String key, DecodeContext context) {
if (context.options.expandPaths() != PathExpansion.SAFE) {
return false;
}
// Quoted keys should not be expanded
if (key.trim().startsWith("\"") && key.trim().endsWith("\"")) {
return false;
}
// Check if key contains dots and is a valid identifier pattern
if (!key.contains(".")) {
return false;
}
// Valid identifier: starts with letter or underscore, followed by letters,
// digits, underscores
// Each segment must match this pattern
String[] segments = key.split("\\.");
for (String segment : segments) {
if (!segment.matches("^[a-zA-Z_]\\w*$")) {
return false;
}
}
return true;
}
/**
* Parses a key-value string into an Object, handling nested objects, empty
* values, and primitives.
*
* @param value the value string to parse
* @param depth the depth at which the key-value pair is located
* @return the parsed value (Map, List, or primitive)
*/
private static Object parseKeyValue(String value, int depth, DecodeContext context) {
// Check if next line is nested (deeper indentation)
if (context.currentLine + 1 < context.lines.length) {
int nextDepth = DecodeHelper.getDepth(context.lines[context.currentLine + 1], context);
if (nextDepth > depth) {
context.currentLine++;
// parseNestedObject manages currentLine, so we don't increment here
return ObjectDecoder.parseNestedObject(depth, context);
} else {
// If value is empty, create empty object; otherwise parse as primitive
Object parsedValue;
if (value.trim().isEmpty()) {
parsedValue = new LinkedHashMap<>();
} else {
parsedValue = PrimitiveDecoder.parse(value);
}
context.currentLine++;
return parsedValue;
}
} else {
// If value is empty, create empty object; otherwise parse as primitive
Object parsedValue;
if (value.trim().isEmpty()) {
parsedValue = new LinkedHashMap<>();
} else {
parsedValue = PrimitiveDecoder.parse(value);
}
context.currentLine++;
return parsedValue;
}
}
/**
* Puts a key-value pair into a map, handling path expansion.
*
* @param map the map to put the key-value pair into
* @param originalKey the original key before being unescaped (used for path
* expansion check)
* @param unescapedKey the unescaped key
* @param value the value to put
*/
private static void putKeyValueIntoMap(Map<String, Object> map, String originalKey, String unescapedKey,
Object value, DecodeContext context) {
// Handle path expansion
if (shouldExpandKey(originalKey, context)) {
expandPathIntoMap(map, unescapedKey, value, context);
} else {
DecodeHelper.checkPathExpansionConflict(map, unescapedKey, value, context);
map.put(unescapedKey, value);
}
}
/**
* Parses a key-value pair at root level, creating a new Map.
* @param key key-value
* @param value the value string to parse
* @param depth the depth of the key value pair
* @param parseRootFields true or false if root fields should be parsed
* @param context decode object in order to deal with lines, delimiter and options
*/
protected static Object parseKeyValuePair(String key, String value, int depth, boolean parseRootFields,
DecodeContext context) {
Map<String, Object> obj = new LinkedHashMap<>();
KeyDecoder.parseKeyValuePairIntoMap(obj, key, value, depth, context);
if (parseRootFields) {
ObjectDecoder.parseRootObjectFields(obj, depth, context);
}
return obj;
}
/**
* Parses a keyed array value (e.g., "items[2]{id,name}:").
* @param keyedArray keyed array
* @param content the content string to parse
* @param depth the depth of the keyed array value
* @param context decode object in order to deal with lines, delimiter and options
* @return parsed keyed array value
*/
protected static Object parseKeyedArrayValue(Matcher keyedArray, String content, int depth, DecodeContext context) {
String originalKey = keyedArray.group(1).trim();
String key = StringEscaper.unescape(originalKey);
String arrayHeader = content.substring(keyedArray.group(1).length());
var arrayValue = ArrayDecoder.parseArray(arrayHeader, depth, context);
Map<String, Object> obj = new LinkedHashMap<>();
// Handle path expansion for array keys
if (KeyDecoder.shouldExpandKey(originalKey, context)) {
KeyDecoder.expandPathIntoMap(obj, key, arrayValue, context);
} else {
// Check for conflicts with existing expanded paths
DecodeHelper.checkPathExpansionConflict(obj, key, arrayValue, context);
obj.put(key, arrayValue);
}
// Continue parsing root-level fields if at depth 0
if (depth == 0) {
ObjectDecoder.parseRootObjectFields(obj, depth, context);
}
return obj;
}
/**
* Parses a keyed array field and adds it to the item map.
*
* @param fieldContent the field content to parse
* @param item the map to add the field to
* @param depth the depth of the list item
* @return true if the field was processed as a keyed array, false otherwise
*/
protected static boolean parseKeyedArrayField(String fieldContent, Map<String, Object> item, int depth, DecodeContext context) {
Matcher keyedArray = KEYED_ARRAY_PATTERN.matcher(fieldContent);
if (!keyedArray.matches()) {
return false;
}
String originalKey = keyedArray.group(1).trim();
String key = StringEscaper.unescape(originalKey);
String arrayHeader = fieldContent.substring(keyedArray.group(1).length());
// For nested arrays in list items, default to comma delimiter if not specified
String nestedArrayDelimiter = ArrayDecoder.extractDelimiterFromHeader(arrayHeader, context);
var arrayValue = ArrayDecoder.parseArrayWithDelimiter(arrayHeader, depth + 2, nestedArrayDelimiter, context);
// Handle path expansion for array keys
if (KeyDecoder.shouldExpandKey(originalKey, context)) {
KeyDecoder.expandPathIntoMap(item, key, arrayValue, context);
} else {
item.put(key, arrayValue);
}
// parseArrayWithDelimiter manages currentLine correctly
return true;
}
/**
* Parses a key-value field and adds it to the item map.
*
* @param fieldContent the field content to parse
* @param item the map to add the field to
* @param depth the depth of the list item
* @return true if the field was processed as a key-value pair, false otherwise
*/
protected static boolean parseKeyValueField(String fieldContent, Map<String, Object> item, int depth, DecodeContext context) {
int colonIdx = DecodeHelper.findUnquotedColon(fieldContent);
if (colonIdx <= 0) {
return false;
}
String fieldKey = StringEscaper.unescape(fieldContent.substring(0, colonIdx).trim());
String fieldValue = fieldContent.substring(colonIdx + 1).trim();
Object parsedValue = ObjectDecoder.parseFieldValue(fieldValue, depth + 2, context);
// Handle path expansion
if (KeyDecoder.shouldExpandKey(fieldKey, context)) {
KeyDecoder.expandPathIntoMap(item, fieldKey, parsedValue, context);
} else {
item.put(fieldKey, parsedValue);
}
// parseFieldValue manages currentLine appropriately
return true;
}
}