-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfuncmap.go
More file actions
685 lines (601 loc) · 17 KB
/
Copy pathfuncmap.go
File metadata and controls
685 lines (601 loc) · 17 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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
package vuego
import (
"context"
"encoding/json"
"fmt"
"html"
"io/fs"
"reflect"
"regexp"
"strconv"
"strings"
"time"
yaml "gopkg.in/yaml.v3"
"github.com/titpetric/vuego/internal/helpers"
)
// FuncMap is a map of function names to functions, similar to text/template's FuncMap.
// Functions can have any number of parameters and must return 1 or 2 values.
// If 2 values are returned, the second must be an error.
//
// Functions can optionally take *VueContext or context.Context as the first parameter:
//
// - func myFunc(ctx context.Context) bool { ... }
// - func myFunc(ctx *VueContext, arg1 string) (string, error) { ... }
// - func myFunc(arg1 string) string { ... }
//
// This allows access to the execution context.
type FuncMap map[string]any
// DefaultFuncMap returns a FuncMap with built-in utility functions.
func (v *Vue) DefaultFuncMap() FuncMap {
return FuncMap{
"upper": upperFunc,
"lower": lowerFunc,
"title": titleFunc,
"formatTime": formatTimeFunc,
"formatDate": formatDateFunc,
"default": defaultFunc,
"len": lenFunc,
"trim": trimFunc,
"escape": escapeFunc,
"int": intFunc,
"string": stringFunc,
"json": jsonFunc,
"jsonPretty": jsonPrettyFunc,
"type": typeFunc,
"file": fileFunc(v),
"jsonFile": jsonFileFunc(v),
"yamlFile": yamlFileFunc(v),
}
}
// pipeExpr represents a parsed pipe expression like "value | fn1 | . > 5 | fn2(arg)"
type pipeExpr struct {
initial string
segments []pipeSegment
}
// pipeSegment represents either a filter call or an expression in a pipe chain
type pipeSegment struct {
typ segmentType // "filter" or "expr"
expr string // The expression/filter text
name string // Filter name (only for filters)
args []string // Filter arguments (only for filters)
}
type segmentType string
const (
segmentFilter = "filter"
segmentExpr = "expr"
)
// matches function calls like "fn(arg1, arg2)" or just "fn"
var filterRe = regexp.MustCompile(`^(\w+)(?:\((.*?)\))?$`)
// parsePipeExpr parses "item | double | . > 5" into segments, auto-detecting expressions vs filters
func parsePipeExpr(expr string) pipeExpr {
// Check if this is a complex expression (contains operators like ||, &&, etc.)
// before trying to split on pipe character
trimmed := strings.TrimSpace(expr)
if helpers.IsComplexExpr(trimmed) {
return pipeExpr{
initial: "",
segments: []pipeSegment{{
typ: segmentExpr,
expr: trimmed,
}},
}
}
if !strings.Contains(expr, "|") {
// Check if it's a function call (including no-arg functions like "fn()")
if matches := filterRe.FindStringSubmatch(trimmed); matches != nil && matches[1] != "" {
return pipeExpr{
initial: "",
segments: []pipeSegment{{
typ: segmentFilter,
expr: trimmed,
name: matches[1],
args: parseArgs(matches[2]),
}},
}
}
// Just a simple variable reference
return pipeExpr{initial: trimmed}
}
parts := strings.Split(expr, "|")
firstPart := strings.TrimSpace(parts[0])
result := pipeExpr{
initial: firstPart,
segments: make([]pipeSegment, 0, len(parts)-1),
}
for i := 1; i < len(parts); i++ {
part := strings.TrimSpace(parts[i])
result.segments = append(result.segments, classifySegment(part))
}
return result
}
// classifySegment determines if a pipe segment is a filter call or expression
func classifySegment(part string) pipeSegment {
// Check for complex expression operators first
if helpers.IsComplexExpr(part) {
return pipeSegment{
typ: segmentExpr,
expr: part,
}
}
// Try to match as function call
if matches := filterRe.FindStringSubmatch(part); matches != nil {
name := matches[1]
if helpers.IsIdentifier(name) {
args := []string{}
if matches[2] != "" {
args = parseArgs(matches[2])
}
return pipeSegment{
typ: segmentFilter,
expr: part,
name: name,
args: args,
}
}
}
// Otherwise treat as expression
return pipeSegment{
typ: segmentExpr,
expr: part,
}
}
// parseArgs parses comma-separated arguments, handling quoted strings
func parseArgs(argStr string) []string {
var args []string
var current strings.Builder
inQuote := false
quoteChar := rune(0)
for _, ch := range strings.TrimSpace(argStr) {
switch {
case (ch == '"' || ch == '\'') && !inQuote:
inQuote = true
quoteChar = ch
case ch == quoteChar && inQuote:
inQuote = false
quoteChar = 0
case ch == ',' && !inQuote:
if current.Len() > 0 {
args = append(args, strings.TrimSpace(current.String()))
current.Reset()
}
default:
current.WriteRune(ch)
}
}
if current.Len() > 0 {
args = append(args, strings.TrimSpace(current.String()))
}
return args
}
// evalPipe evaluates a pipe expression, handling both filters and expressions
func (v *Vue) evalPipe(ctx VueContext, expr pipeExpr) (any, error) {
// Handle direct function calls (no initial value)
if expr.initial == "" && len(expr.segments) > 0 {
val, err := v.evalSegment(ctx, expr.segments[0], nil, true, false)
if err != nil {
return nil, err
}
// Apply remaining segments
for i := 1; i < len(expr.segments); i++ {
val, err = v.evalSegment(ctx, expr.segments[i], val, false, true)
if err != nil {
return nil, err
}
}
return val, nil
}
// Resolve initial value
var val any
var ok bool
val, ok = ctx.stack.Resolve(expr.initial)
if !ok {
if len(expr.segments) > 0 {
val = nil // Pass nil to first segment filter
} else {
return nil, fmt.Errorf("variable '%s' not found", expr.initial)
}
}
// Apply each segment in sequence
for i, seg := range expr.segments {
var err error
val, err = v.evalSegment(ctx, seg, val, i == 0, true)
if err != nil {
return nil, err
}
}
return val, nil
}
// evalSegment evaluates a single pipe segment (either filter or expression)
// isFirst indicates if this is the first segment
// fromInitial indicates if the input came from initial variable resolution
func (v *Vue) evalSegment(ctx VueContext, seg pipeSegment, input any, isFirst, fromInitial bool) (any, error) {
switch seg.typ {
case segmentFilter:
return v.evalFilter(ctx, seg, input, isFirst, fromInitial)
case segmentExpr:
// Use expr library with . representing the input value
env := ctx.ExprEnv()
if input != nil {
env["."] = input
defer delete(env, ".")
}
result, err := v.exprEval.Eval(seg.expr, env)
if err != nil {
return nil, fmt.Errorf("in expression '%s': %w", seg.expr, err)
}
return result, nil
}
return nil, fmt.Errorf("unknown segment type: %v", seg.typ)
}
// evalFilter applies a filter function to input
// isFirst indicates if this is the first segment
// fromInitial indicates if input came from initial variable resolution
func (v *Vue) evalFilter(ctx VueContext, seg pipeSegment, input any, isFirst, fromInitial bool) (any, error) {
fn, exists := v.funcMap[seg.name]
if !exists {
return nil, fmt.Errorf("function '%s' not found", seg.name)
}
// Prepend input if:
// - Not the first segment (pipe continuation), OR
// - First segment that came from initial variable resolution (passes input even if nil)
args := []any{}
if !isFirst || (isFirst && fromInitial) {
args = append(args, input)
}
for _, argExpr := range seg.args {
argVal := v.resolveArgument(ctx, argExpr)
args = append(args, argVal)
}
result, err := v.callFunc(&ctx, fn, args...)
if err != nil {
return nil, fmt.Errorf("%s(): %w", seg.name, err)
}
return result, nil
}
// resolveArgument resolves a single argument (either a variable reference or literal)
func (v *Vue) resolveArgument(ctx VueContext, arg string) any {
arg = strings.TrimSpace(arg)
// Check if it's a quoted string literal
if len(arg) >= 2 {
if (arg[0] == '"' && arg[len(arg)-1] == '"') ||
(arg[0] == '\'' && arg[len(arg)-1] == '\'') {
return arg[1 : len(arg)-1]
}
}
// Try to parse as integer
if i, err := strconv.Atoi(arg); err == nil {
return i
}
// Try to parse as float
if f, err := strconv.ParseFloat(arg, 64); err == nil {
return f
}
// Try to parse as bool
if b, err := strconv.ParseBool(arg); err == nil {
return b
}
// Try to resolve as variable
if val, ok := ctx.stack.Resolve(arg); ok {
return val
}
// Return as-is (literal string)
return arg
}
// callFunc calls a function from the FuncMap with optional VueContext as first argument.
// If the function's first parameter is *VueContext, the context is passed automatically.
// Otherwise, all provided arguments are passed directly.
func (v *Vue) callFunc(ctx *VueContext, fn any, args ...any) (any, error) {
fnVal := reflect.ValueOf(fn)
fnType := fnVal.Type()
if fnType.Kind() != reflect.Func {
return nil, fmt.Errorf("not a function")
}
// Check if first parameter is *VueContext or context.Context
hasContextParam := false
hasStdContext := false
numIn := fnType.NumIn()
if numIn > 0 {
firstParamType := fnType.In(0)
if firstParamType == reflect.TypeOf((*VueContext)(nil)) {
hasContextParam = true
} else if firstParamType == reflect.TypeOf((*context.Context)(nil)).Elem() {
hasStdContext = true
}
}
// Adjust expected argument count based on context parameter
expectedArgs := numIn
if hasContextParam || hasStdContext {
expectedArgs = numIn - 1 // Don't count the context parameter
}
// For variadic functions, adjust to required args (excluding the variadic ...T part)
requiredArgs := expectedArgs
if fnType.IsVariadic() {
requiredArgs = expectedArgs - 1
}
// Build final argument list
var finalArgs []any
if hasContextParam {
finalArgs = append(finalArgs, ctx)
finalArgs = append(finalArgs, args...)
} else if hasStdContext {
finalArgs = append(finalArgs, ctx.Context())
finalArgs = append(finalArgs, args...)
} else {
finalArgs = args
}
// Check argument count
if fnType.IsVariadic() {
if len(args) < requiredArgs {
return nil, fmt.Errorf("function expects at least %d arguments, got %d", requiredArgs, len(args))
}
} else {
if len(args) != expectedArgs {
return nil, fmt.Errorf("function expects %d arguments, got %d", expectedArgs, len(args))
}
}
// Prepare arguments with type conversion
in := make([]reflect.Value, len(finalArgs))
for i, arg := range finalArgs {
var argType reflect.Type
if fnType.IsVariadic() && i >= numIn-1 {
// Variadic argument - use element type
argType = fnType.In(numIn - 1).Elem()
} else {
argType = fnType.In(i)
}
argVal := reflect.ValueOf(arg)
// Handle nil
if arg == nil {
in[i] = reflect.Zero(argType)
continue
}
// Try to convert the argument to the expected type
if argVal.Type().AssignableTo(argType) {
in[i] = argVal
} else if argVal.Type().ConvertibleTo(argType) {
in[i] = argVal.Convert(argType)
} else {
// Try to handle common conversions
converted, ok := convertValue(argVal, argType)
if !ok {
return nil, fmt.Errorf("cannot convert argument %d from %v to %v", i, argVal.Type(), argType)
}
in[i] = converted
}
}
// Call the function
out := fnVal.Call(in)
// Handle return values
switch len(out) {
case 0:
return nil, nil
case 1:
// Single return value
return out[0].Interface(), nil
case 2:
// Two return values - second should be error
result := out[0].Interface()
if out[1].IsNil() {
return result, nil
}
if err, ok := out[1].Interface().(error); ok {
return result, err
}
return result, nil
default:
return nil, fmt.Errorf("function returns too many values")
}
}
// convertValue attempts common type conversions
func convertValue(val reflect.Value, targetType reflect.Type) (reflect.Value, bool) {
// Handle string to basic types
if val.Kind() == reflect.String {
s := val.String()
switch targetType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
return reflect.ValueOf(i).Convert(targetType), true
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if u, err := strconv.ParseUint(s, 10, 64); err == nil {
return reflect.ValueOf(u).Convert(targetType), true
}
case reflect.Float32, reflect.Float64:
if f, err := strconv.ParseFloat(s, 64); err == nil {
return reflect.ValueOf(f).Convert(targetType), true
}
case reflect.Bool:
if b, err := strconv.ParseBool(s); err == nil {
return reflect.ValueOf(b), true
}
}
}
// Handle int to string
if val.Kind() >= reflect.Int && val.Kind() <= reflect.Int64 && targetType.Kind() == reflect.String {
return reflect.ValueOf(fmt.Sprintf("%d", val.Int())), true
}
// Handle uint to string
if val.Kind() >= reflect.Uint && val.Kind() <= reflect.Uint64 && targetType.Kind() == reflect.String {
return reflect.ValueOf(fmt.Sprintf("%d", val.Uint())), true
}
// Handle float to string
if (val.Kind() == reflect.Float32 || val.Kind() == reflect.Float64) && targetType.Kind() == reflect.String {
return reflect.ValueOf(fmt.Sprintf("%v", val.Float())), true
}
// Handle bool to string
if val.Kind() == reflect.Bool && targetType.Kind() == reflect.String {
return reflect.ValueOf(fmt.Sprintf("%t", val.Bool())), true
}
return reflect.Value{}, false
}
// Built-in filter functions
func fileFunc(v *Vue) func(*VueContext, string) (any, error) {
return func(ctx *VueContext, filename string) (any, error) {
// Resolve filename through the context's stack if it's a variable reference
if ctx != nil {
if val, ok := ctx.Stack().Resolve(filename); ok {
filename = fmt.Sprint(val)
}
}
if v.templateFS == nil {
return "", fmt.Errorf("error loading file from nil fs: %s", filename)
}
d, err := fs.ReadFile(v.templateFS, filename)
if err != nil {
return "", err
}
return string(d), nil
}
}
func jsonFileFunc(v *Vue) func(*VueContext, string) (any, error) {
return func(ctx *VueContext, filename string) (any, error) {
// Resolve filename through the context's stack if it's a variable reference
if ctx != nil {
if val, ok := ctx.Stack().Resolve(filename); ok {
filename = fmt.Sprint(val)
}
}
if v.templateFS == nil {
return "", fmt.Errorf("error loading file from nil fs: %s", filename)
}
d, err := fs.ReadFile(v.templateFS, filename)
if err != nil {
return "", err
}
var result map[string]any
if err := json.Unmarshal(d, &result); err != nil {
return "", fmt.Errorf("error decoding json from file %s: %w", filename, err)
}
return result, nil
}
}
func yamlFileFunc(v *Vue) func(*VueContext, string) (any, error) {
return func(ctx *VueContext, filename string) (any, error) {
// Resolve filename through the context's stack if it's a variable reference
if ctx != nil {
if val, ok := ctx.Stack().Resolve(filename); ok {
filename = fmt.Sprint(val)
}
}
if v.templateFS == nil {
return "", fmt.Errorf("error loading file from nil fs: %s", filename)
}
d, err := fs.ReadFile(v.templateFS, filename)
if err != nil {
return "", err
}
var result map[string]any
if err := yaml.Unmarshal(d, &result); err != nil {
return "", fmt.Errorf("error decoding json from file %s: %w", filename, err)
}
return result, nil
}
}
func typeFunc(v any) any {
return fmt.Sprintf("%T", v)
}
func upperFunc(v any) any {
if s, ok := v.(string); ok {
return strings.ToUpper(s)
}
return v
}
func lowerFunc(v any) any {
if s, ok := v.(string); ok {
return strings.ToLower(s)
}
return v
}
func titleFunc(v any) any {
if s, ok := v.(string); ok {
words := strings.Fields(s)
for i, word := range words {
if len(word) > 0 {
words[i] = strings.ToUpper(word[:1]) + strings.ToLower(word[1:])
}
}
return strings.Join(words, " ")
}
return v
}
func formatTimeFunc(v any, layout any) any {
layoutStr := "2006-01-02 15:04:05"
if s, ok := layout.(string); ok {
layoutStr = s
}
switch t := v.(type) {
case time.Time:
return t.Format(layoutStr)
case string:
// Try to parse as RFC3339 or Unix timestamp
if parsed, err := time.Parse(time.RFC3339, t); err == nil {
return parsed.Format(layoutStr)
}
}
return v
}
func formatDateFunc(v any, layout any) any {
layoutStr := "2006-01-02"
if s, ok := layout.(string); ok {
layoutStr = s
}
return formatTimeFunc(v, layoutStr)
}
func defaultFunc(v any, def any) any {
if v == nil || v == "" {
return def
}
return v
}
func lenFunc(v any) any {
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.String, reflect.Slice, reflect.Array, reflect.Map:
return rv.Len()
}
return 0
}
func trimFunc(v any) any {
if s, ok := v.(string); ok {
return strings.TrimSpace(s)
}
return v
}
func escapeFunc(v any) any {
if s, ok := v.(string); ok {
return html.EscapeString(s)
}
return fmt.Sprint(v)
}
func intFunc(v any) any {
switch t := v.(type) {
case int:
return t
case int64:
return int(t)
case float64:
return int(t)
case string:
if i, err := strconv.Atoi(t); err == nil {
return i
}
}
return 0
}
func stringFunc(v any) any {
return fmt.Sprint(v)
}
func jsonFunc(v any) (string, error) {
b, err := json.Marshal(v)
if err != nil {
return "", fmt.Errorf("failed to marshal to JSON: %w", err)
}
return string(b), nil
}
func jsonPrettyFunc(v any) (string, error) {
b, err := json.MarshalIndent(v, " ", "")
if err != nil {
return "", fmt.Errorf("failed to marshal to JSON: %w", err)
}
return string(b), nil
}