-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargs_parser.go
More file actions
507 lines (435 loc) · 13.4 KB
/
args_parser.go
File metadata and controls
507 lines (435 loc) · 13.4 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package clicky
import (
"encoding/base64"
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"unicode/utf8"
"github.com/flanksource/clicky/api"
)
type Help interface {
Help() api.Textable
}
// ParseArgumentsAsMap parses HTTPie-style command line arguments into a map
// Supports:
//
// key=value - String values
// key:=value - JSON values (numbers, booleans, arrays, objects)
// key==value - Query parameters (returned in separate map)
// key@file - Read value from file
// key:=@file - Read JSON from file
// Header:value - HTTP headers (ignored in this function)
// key[sub]=val - Nested JSON structures
func ParseArgumentsAsMap(args []string) (map[string]any, error) {
data, _, _, err := ParseArgumentsComplete(args)
return data, err
}
// ParseArgumentsWithHeaders parses arguments and separates headers
func ParseArgumentsWithHeaders(args []string) (map[string]any, map[string]string, error) {
data, headers, _, err := ParseArgumentsComplete(args)
return data, headers, err
}
// ParseArgumentsComplete parses all argument types and returns separated results
func ParseArgumentsComplete(args []string) (map[string]any, map[string]string, map[string]string, error) {
data := make(map[string]any)
headers := make(map[string]string)
query := make(map[string]string)
for _, rawArg := range args {
// Handle escaped arguments BEFORE parsing
arg := unescapeArgument(rawArg)
// Check for query parameter (but not if == is escaped)
if isQueryParameter(rawArg) {
parts := strings.SplitN(arg, "==", 2)
if len(parts) == 2 {
query[parts[0]] = parts[1]
}
continue
}
// Check for headers (but not if colon is escaped)
if isHeaderParameter(rawArg) {
colonIdx := strings.Index(arg, ":")
key := arg[:colonIdx]
value := arg[colonIdx+1:]
if strings.HasPrefix(value, "@") {
// Header from file: Header:@file
filepath := value[1:]
content, err := readFileAsString(filepath)
if err != nil {
return nil, nil, nil, fmt.Errorf("reading header file '%s': %w", filepath, err)
}
headers[key] = strings.TrimSpace(content)
} else {
// Direct header value
headers[key] = value
}
continue
}
// Parse other argument types (data fields) - pass the raw version for position detection
key, value, argType, err := parseArgumentEnhanced(rawArg)
if err != nil {
return nil, nil, nil, fmt.Errorf("parsing '%s': %w", arg, err)
}
if key != "" && argType == "data" {
// Handle nested bracket notation
if strings.Contains(key, "[") {
err = setNestedValue(data, key, value)
if err != nil {
return nil, nil, nil, fmt.Errorf("setting nested value '%s': %w", key, err)
}
} else {
data[key] = value
}
}
}
return data, headers, query, nil
}
// ParseArgumentsWithQuery parses arguments and separates query parameters (backward compatibility)
func ParseArgumentsWithQuery(args []string) (data map[string]any, query map[string]string, err error) {
data, _, query, err = ParseArgumentsComplete(args)
return data, query, err
}
// parseArgumentEnhanced parses a single argument and returns key, value, type, and error
func parseArgumentEnhanced(rawArg string) (string, any, string, error) {
// Work with the raw argument for position detection, but unescape for final values
// Array from stdin: []key=- or key[]=-
if strings.Contains(rawArg, "=-") {
var key string
if strings.HasPrefix(rawArg, "[]") && strings.Contains(rawArg, "=-") {
// []key=- format
idx := strings.Index(rawArg, "=-")
key = unescapeArgument(rawArg[2:idx])
} else if strings.Contains(rawArg, "[]=-") {
// key[]=- format
idx := strings.Index(rawArg, "[]=-")
key = unescapeArgument(rawArg[:idx])
}
if key != "" {
lines, err := readLinesFromFile("-")
if err != nil {
return "", nil, "", fmt.Errorf("reading stdin: %w", err)
}
return key, lines, "data", nil
}
}
// Array from file: []key=@file or key[]=@file
if strings.Contains(rawArg, "=@") && !strings.Contains(rawArg, ":=@") {
var key, filepath string
if strings.HasPrefix(rawArg, "[]") {
// []key=@file format
idx := strings.Index(rawArg, "=@")
key = unescapeArgument(rawArg[2:idx])
filepath = rawArg[idx+2:] // Skip the =@
} else if strings.Contains(rawArg, "[]=@") {
// key[]=@file format
idx := strings.Index(rawArg, "[]=@")
key = unescapeArgument(rawArg[:idx])
filepath = rawArg[idx+4:] // Skip the []=@
}
if key != "" && filepath != "" {
lines, err := readLinesFromFile(filepath)
if err != nil {
return "", nil, "", fmt.Errorf("reading file %s: %w", filepath, err)
}
return key, lines, "data", nil
}
}
// JSON from file: key:=@file.json
if idx := strings.Index(rawArg, ":=@"); idx > 0 {
key := unescapeArgument(rawArg[:idx])
filepath := rawArg[idx+3:]
content, err := os.ReadFile(filepath)
if err != nil {
return "", nil, "", fmt.Errorf("reading file %s: %w", filepath, err)
}
var value any
if err := json.Unmarshal(content, &value); err != nil {
return "", nil, "", fmt.Errorf("parsing JSON from %s: %w", filepath, err)
}
return key, value, "data", nil
}
// String or binary from file: key@file (check for escaped @)
if idx := strings.Index(rawArg, "@"); idx > 0 && !strings.Contains(rawArg[:idx], "=") && !isEscaped(rawArg, "@") {
key := unescapeArgument(rawArg[:idx])
filepath := rawArg[idx+1:]
value, err := readFileAsStringOrBase64(filepath)
if err != nil {
return "", nil, "", fmt.Errorf("reading file %s: %w", filepath, err)
}
return key, value, "data", nil
}
// JSON value: key:=value
if idx := strings.Index(rawArg, ":="); idx > 0 {
key := unescapeArgument(rawArg[:idx])
jsonStr := rawArg[idx+2:]
var value any
if err := json.Unmarshal([]byte(jsonStr), &value); err != nil {
return "", nil, "", fmt.Errorf("parsing JSON value '%s': %w", jsonStr, err)
}
return key, value, "data", nil
}
// Query parameters are handled at a higher level, no need to check here
// String value: key=value (but handle escaped equals in key)
if idx := findUnescapedEquals(rawArg); idx > 0 {
// Use the raw argument to find position, but unescape the parts
rawKey := rawArg[:idx]
rawValue := rawArg[idx+1:]
key := unescapeArgument(rawKey)
value := unescapeArgument(rawValue)
return key, value, "data", nil
}
return "", nil, "", fmt.Errorf("invalid argument format, expected key=value, key:=json, key@file, Header:value, or key:=@file")
}
// Helper functions
// readFileAsString reads a file and returns its content as a string
func readFileAsString(filepath string) (string, error) {
content, err := os.ReadFile(filepath)
if err != nil {
return "", err
}
return string(content), nil
}
// readFileAsStringOrBase64 reads a file and returns it as string or base64 if binary
func readFileAsStringOrBase64(filepath string) (string, error) {
content, err := os.ReadFile(filepath)
if err != nil {
return "", err
}
// Check if content is valid UTF-8 text
if utf8.Valid(content) {
// For text files, return as string
return string(content), nil
}
// For binary files, return as base64
return base64.StdEncoding.EncodeToString(content), nil
}
// readLinesFromFile reads lines from a file or stdin and returns them as a slice
// Skips empty lines and lines starting with #
func readLinesFromFile(filepath string) ([]string, error) {
var content []byte
var err error
if filepath == "-" {
// Read from stdin
content, err = os.ReadFile("/dev/stdin")
} else {
// Read from file
content, err = os.ReadFile(filepath)
}
if err != nil {
return nil, err
}
var lines []string
for _, line := range strings.Split(string(content), "\n") {
line = strings.TrimSpace(line)
if line != "" && !strings.HasPrefix(line, "#") {
lines = append(lines, line)
}
}
return lines, nil
}
// isQueryParameter checks if an argument is a query parameter (key==value) and not escaped
func isQueryParameter(arg string) bool {
return strings.Contains(arg, "==") && !isEscaped(arg, "==")
}
// isHeaderParameter checks if an argument is a header (Key:value) and not escaped
func isHeaderParameter(arg string) bool {
colonIdx := strings.Index(arg, ":")
if colonIdx <= 0 {
return false
}
// Must not have = before the colon
if strings.Contains(arg[:colonIdx], "=") {
return false
}
// Must not be :=
if colonIdx+1 < len(arg) && arg[colonIdx+1] == '=' {
return false
}
// Must not be escaped
return !isEscaped(arg, ":")
}
// findUnescapedEquals finds the first unescaped = in the argument for key=value parsing
func findUnescapedEquals(arg string) int {
for i := 0; i < len(arg); i++ {
if arg[i] == '=' {
// Count consecutive backslashes before this =
backslashCount := 0
for j := i - 1; j >= 0 && arg[j] == '\\'; j-- {
backslashCount++
}
// If even number of backslashes (including 0), the = is not escaped
if backslashCount%2 == 0 {
return i
}
}
}
return -1
}
// isEscaped checks if a pattern is escaped in the argument
func isEscaped(arg, pattern string) bool {
idx := strings.Index(arg, pattern)
if idx <= 0 {
return false
}
// Count consecutive backslashes before the pattern
backslashCount := 0
for i := idx - 1; i >= 0 && arg[i] == '\\'; i-- {
backslashCount++
}
// If odd number of backslashes, the pattern is escaped
return backslashCount%2 == 1
}
// unescapeArgument handles escape sequences in arguments
func unescapeArgument(arg string) string {
// Handle basic escape sequences
result := strings.ReplaceAll(arg, "\\=", "=")
result = strings.ReplaceAll(result, "\\:", ":")
result = strings.ReplaceAll(result, "\\@", "@")
result = strings.ReplaceAll(result, "\\\\", "\\")
return result
}
// setNestedValue sets a value in a nested map using bracket notation like "user[profile][name]"
func setNestedValue(data map[string]any, key string, value any) error {
// Parse bracket notation: user[profile][name] or items[]
bracketRegex := regexp.MustCompile(`^([^[]+)(\[[^\]]*\])+$`)
if !bracketRegex.MatchString(key) {
return fmt.Errorf("invalid bracket notation: %s", key)
}
// Extract base key (everything before first bracket)
firstBracket := strings.Index(key, "[")
baseKey := key[:firstBracket]
// Extract all bracket parts from the entire key
bracketRegex2 := regexp.MustCompile(`\[([^\]]*)\]`)
bracketMatches := bracketRegex2.FindAllStringSubmatch(key, -1)
// Build the full path: ["user", "profile", "name"]
fullPath := []string{baseKey}
for _, bracketMatch := range bracketMatches {
fullPath = append(fullPath, bracketMatch[1])
}
// Special case for simple arrays like tags[]
if len(fullPath) == 2 && fullPath[1] == "" {
arrayKey := fullPath[0]
if data[arrayKey] == nil {
data[arrayKey] = []any{}
}
if arr, ok := data[arrayKey].([]any); ok {
data[arrayKey] = append(arr, value)
} else {
data[arrayKey] = []any{value}
}
return nil
}
// Navigate and create structure for complex paths
current := data
for i, pathKey := range fullPath {
if i == len(fullPath)-1 {
// Last key - set the value
current[pathKey] = value
} else {
// Intermediate key - ensure structure exists
if pathKey == "" {
return fmt.Errorf("empty key not allowed in intermediate path")
}
if current[pathKey] == nil {
current[pathKey] = make(map[string]any)
}
// Navigate to next level
if obj, ok := current[pathKey].(map[string]any); ok {
current = obj
} else {
return fmt.Errorf("cannot navigate through non-object at key: %s", pathKey)
}
}
}
return nil
}
// MustParseArgumentsAsMap is like ParseArgumentsAsMap but panics on error
func MustParseArgumentsAsMap(args []string) map[string]any {
result, err := ParseArgumentsAsMap(args)
if err != nil {
panic(err)
}
return result
}
// Args is a custom map type for parsed arguments with helper methods
type Args map[string]any
// GetString returns the string value for a key, or empty string if not found or wrong type
func (a Args) GetString(key string) string {
val, ok := a[key]
if !ok {
return ""
}
switch v := val.(type) {
case string:
return v
case []string:
if len(v) > 0 {
return v[0]
}
return ""
case []interface{}:
if len(v) > 0 {
if str, ok := v[0].(string); ok {
return str
}
}
return ""
default:
return fmt.Sprintf("%v", v)
}
}
// GetStringSlice returns the string slice value for a key, or empty slice if not found
func (a Args) GetStringSlice(key string) []string {
val, ok := a[key]
if !ok {
return []string{}
}
switch v := val.(type) {
case []string:
return v
case string:
return []string{v}
case []interface{}:
result := make([]string, 0, len(v))
for _, item := range v {
if str, ok := item.(string); ok {
result = append(result, str)
} else {
result = append(result, fmt.Sprintf("%v", item))
}
}
return result
default:
return []string{fmt.Sprintf("%v", v)}
}
}
// MarshalJSON implements json.Marshaler interface
func (a Args) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any(a))
}
// UnmarshalJSON implements json.Unmarshaler interface
func (a *Args) UnmarshalJSON(data []byte) error {
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
return err
}
*a = Args(m)
return nil
}
// ParseArguments parses HTTPie-style arguments and returns an Args type
func ParseArguments(args []string) (Args, error) {
data, err := ParseArgumentsAsMap(args)
if err != nil {
return nil, err
}
return Args(data), nil
}
// MustParseArguments is like ParseArguments but panics on error
func MustParseArguments(args []string) Args {
result, err := ParseArguments(args)
if err != nil {
panic(err)
}
return result
}