-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore_funcs.go
More file actions
852 lines (794 loc) · 26 KB
/
core_funcs.go
File metadata and controls
852 lines (794 loc) · 26 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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
// Copyright 2026 The CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"strings"
"text/template/parse"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/token"
)
// funcArg wraps either an unresolved AST node (from first-command
// position) or a pre-resolved CUE expression (from a piped value).
type funcArg struct {
node parse.Node // non-nil for unresolved AST nodes
expr ast.Expr // pre-resolved CUE expression (when node is nil)
obj string // helm object name (when pre-resolved)
field []string // field path within context object (when pre-resolved)
}
// coreFunc registers a handler for a core template function.
type coreFunc struct {
// nargs is the expected argument count, not counting the function
// name itself. Use -1 for variadic functions.
nargs int
// pipedFirst means the piped value goes first in args rather than
// last. This is only used by tpl where the piped value is the
// template string (first arg), not the context (second arg).
pipedFirst bool
// convert produces a CUE expression from the function arguments.
// Side effects (recording defaults, comments, imports, helpers,
// field tracking) happen inside the handler.
convert func(c *converter, args []funcArg) (expr ast.Expr, helmObj string, err error)
}
// coreFuncs maps function names to their unified handlers.
// Initialized in init() to avoid an initialization cycle with
// convertSubPipe which references coreFuncs.
var coreFuncs map[string]coreFunc
func init() {
coreFuncs = map[string]coreFunc{
"default": {nargs: 2, convert: convertDefault},
"printf": {nargs: -1, convert: convertPrintf},
"print": {nargs: -1, convert: convertPrint},
"required": {nargs: 2, convert: convertRequired},
"fail": {nargs: 1, convert: convertFail},
"include": {nargs: -1, convert: convertInclude},
"ternary": {nargs: 3, convert: convertTernary},
"list": {nargs: -1, convert: convertList},
"dict": {nargs: -1, convert: convertDict},
"get": {nargs: 2, convert: convertGet},
"coalesce": {nargs: -1, convert: convertCoalesce},
"max": {nargs: -1, convert: convertMax},
"min": {nargs: -1, convert: convertMin},
"tpl": {nargs: 2, pipedFirst: true, convert: convertTpl},
"index": {nargs: -1, convert: convertIndex},
"merge": {nargs: -1, convert: convertMerge},
"mergeOverwrite": {nargs: -1, convert: convertMergeOverwrite},
"dig": {nargs: -1, convert: convertDig},
"omit": {nargs: -1, convert: convertOmit},
"typeIs": {nargs: 2, convert: convertTypeIs},
"deepCopy": {nargs: 1, convert: convertDeepCopy},
"eq": {nargs: 2, convert: makeConvertCmp(token.EQL)},
"ne": {nargs: 2, convert: makeConvertCmp(token.NEQ)},
"lt": {nargs: 2, convert: makeConvertCmp(token.LSS)},
"gt": {nargs: 2, convert: makeConvertCmp(token.GTR)},
"le": {nargs: 2, convert: makeConvertCmp(token.LEQ)},
"ge": {nargs: 2, convert: makeConvertCmp(token.GEQ)},
"concat": {nargs: -1, convert: convertConcat},
}
}
// resolveExpr resolves a funcArg to a CUE expression and helm object name.
func (c *converter) resolveExpr(a funcArg) (ast.Expr, string, error) {
if a.node != nil {
return c.nodeToExpr(a.node)
}
return a.expr, a.obj, nil
}
// resolveField resolves a funcArg to a CUE expression, helm object name,
// and field path. This handles the FieldNode/VariableNode tracking that
// the first-command default/required cases need.
func (c *converter) resolveField(a funcArg) (expr ast.Expr, helmObj string, fieldPath []string, err error) {
if a.node == nil {
return a.expr, a.obj, a.field, nil
}
switch n := a.node.(type) {
case *parse.FieldNode:
expr, helmObj = c.fieldToCUEInContext(n.Ident)
if helmObj != "" {
fieldPath = n.Ident[1:]
c.trackFieldRef(helmObj, fieldPath)
}
return expr, helmObj, fieldPath, nil
case *parse.VariableNode:
if len(n.Ident) >= 2 && n.Ident[0] == "$" {
expr, helmObj = c.dollarFieldToCUE(n.Ident[1:])
if helmObj != "" {
if len(n.Ident) >= 3 {
fieldPath = n.Ident[2:]
}
c.trackFieldRef(helmObj, fieldPath)
}
return expr, helmObj, fieldPath, nil
}
if len(n.Ident) >= 2 && n.Ident[0] != "$" {
if localExpr, ok := c.localVars[n.Ident[0]]; ok {
return buildSelChain(localExpr, n.Ident[1:]), "", nil, nil
}
}
if len(n.Ident) == 1 && n.Ident[0] != "$" {
if localExpr, ok := c.localVars[n.Ident[0]]; ok {
return localExpr, "", nil, nil
}
}
// Fall through to nodeToExpr for other variable forms.
e, obj, exprErr := c.nodeToExpr(a.node)
if exprErr != nil {
return nil, "", nil, exprErr
}
return e, obj, nil, nil
case *parse.ChainNode:
e, obj, exprErr := c.nodeToExpr(a.node)
if exprErr != nil {
return nil, "", nil, exprErr
}
return e, obj, nil, nil
default:
e, obj, exprErr := c.nodeToExpr(a.node)
if exprErr != nil {
return nil, "", nil, exprErr
}
return e, obj, nil, nil
}
}
// resolveLiteral tries to resolve a funcArg as a CUE literal first,
// falling back to a full expression if the node isn't a literal.
func (c *converter) resolveLiteral(a funcArg) (ast.Expr, error) {
if a.node != nil {
lit, err := nodeToCUELiteral(a.node)
if err != nil {
e, _, exprErr := c.nodeToExpr(a.node)
if exprErr != nil {
return nil, err // return original literal error
}
return e, nil
}
return lit, nil
}
return a.expr, nil
}
// resolveCondition resolves a funcArg to a CUE condition expression.
// For AST nodes it delegates to conditionNodeToExpr; for pre-resolved
// expressions it wraps in the _nonzero truthiness check.
func (c *converter) resolveCondition(a funcArg) (ast.Expr, error) {
if a.node != nil {
return c.conditionNodeToExpr(a.node)
}
return nonzeroExpr(a.expr), nil
}
// buildPipeArgs constructs a []funcArg for a pipeline function call,
// placing the piped value last (or first if cf.pipedFirst).
func buildPipeArgs(cf coreFunc, explicitNodes []parse.Node, piped funcArg) []funcArg {
explicit := make([]funcArg, len(explicitNodes))
for i, n := range explicitNodes {
explicit[i] = funcArg{node: n}
}
if cf.pipedFirst {
return append([]funcArg{piped}, explicit...)
}
return append(explicit, piped)
}
// --- Handler implementations ---
func convertDefault(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 2 {
return nil, "", fmt.Errorf("default requires 2 arguments, got %d", len(args))
}
defaultValExpr, err := c.resolveLiteral(args[0])
if err != nil {
return nil, "", fmt.Errorf("default value: %w", err)
}
saved := c.suppressRequired
c.suppressRequired = true
expr, helmObj, _, err := c.resolveField(args[1])
c.suppressRequired = saved
if err != nil {
return nil, "", fmt.Errorf("default field: %w", err)
}
return c.defaultExpr(expr, defaultValExpr), helmObj, nil
}
func convertPrintf(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 1 {
return nil, "", fmt.Errorf("printf requires at least a format string")
}
// Delegate to the existing convertPrintf which operates on parse.Nodes.
// All args should have nodes (from first-command or buildPipeArgs).
nodes := make([]parse.Node, len(args))
for i, a := range args {
if a.node == nil {
return nil, "", fmt.Errorf("printf: unexpected pre-resolved argument")
}
nodes[i] = a.node
}
return c.convertPrintf(nodes)
}
func convertPrint(c *converter, args []funcArg) (ast.Expr, string, error) {
nodes := make([]parse.Node, len(args))
for i, a := range args {
if a.node == nil {
return nil, "", fmt.Errorf("print: unexpected pre-resolved argument")
}
nodes[i] = a.node
}
expr, err := c.convertPrint(nodes)
if err != nil {
return nil, "", err
}
return expr, "", nil
}
func convertRequired(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 2 {
return nil, "", fmt.Errorf("required requires 2 arguments, got %d", len(args))
}
msg, err := c.resolveLiteral(args[0])
if err != nil {
return nil, "", fmt.Errorf("required message: %w", err)
}
expr, helmObj, fieldPath, err := c.resolveField(args[1])
if err != nil {
return nil, "", fmt.Errorf("required field: %w", err)
}
_ = fieldPath // tracked inside resolveField
c.comments[expr] = fmt.Sprintf("// required: %s", exprToText(msg))
return expr, helmObj, nil
}
func convertFail(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 1 {
return nil, "", fmt.Errorf("fail requires 1 argument, got %d", len(args))
}
msg, err := c.resolveLiteral(args[0])
if err != nil {
return nil, "", fmt.Errorf("fail message: %w", err)
}
return callExpr("error", msg), "", nil
}
func convertInclude(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 1 {
return nil, "", fmt.Errorf("include requires at least a template name")
}
// args[0] = template name, args[1] = optional context
nameArg := args[0]
if nameArg.node == nil {
return nil, "", fmt.Errorf("include: template name must be an AST node")
}
var ctxArgExpr ast.Expr
var ctxHelmObj string
var ctxBasePath []string
var dictMap map[string]contextSource
if len(args) >= 2 {
ctxArg := args[1]
if ctxArg.node == nil {
return nil, "", fmt.Errorf("include: context must be an AST node")
}
var ctxErr error
ctxArgExpr, ctxHelmObj, ctxBasePath, dictMap, ctxErr = c.convertIncludeContext(ctxArg.node)
if ctxErr != nil {
return nil, "", ctxErr
}
}
var cueName string
var helmObj string
var expr ast.Expr
if nameNode, ok := nameArg.node.(*parse.StringNode); ok {
var err error
cueName, helmObj, err = c.handleInclude(nameNode.Text, nil)
if err != nil {
return nil, "", err
}
expr = ast.NewIdent(cueName)
} else {
nameExpr, nameErr := c.convertIncludeNameExpr(nameArg.node)
if nameErr != nil {
return nil, "", nameErr
}
c.hasDynamicInclude = true
cueName = fmt.Sprintf("_helpers[%s]", exprToText(nameExpr))
expr = indexExpr(ast.NewIdent("_helpers"), nameExpr)
}
if ctxHelmObj != "" {
c.propagateHelperArgRefs(cueName, ctxHelmObj, ctxBasePath)
} else if dictMap != nil {
c.propagateDictHelperArgRefs(cueName, dictMap)
}
if ctxArgExpr != nil {
expr = binOp(token.AND, expr, &ast.StructLit{Elts: []ast.Decl{
&ast.Field{Label: ast.NewIdent("#arg"), Value: ctxArgExpr},
&ast.EmbedDecl{Expr: ast.NewIdent("_")},
}})
}
return expr, helmObj, nil
}
func convertTernary(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 3 {
return nil, "", fmt.Errorf("ternary requires 3 arguments, got %d", len(args))
}
trueVal, trueObj, err := c.resolveExpr(args[0])
if err != nil {
return nil, "", fmt.Errorf("ternary true value: %w", err)
}
falseVal, falseObj, err := c.resolveExpr(args[1])
if err != nil {
return nil, "", fmt.Errorf("ternary false value: %w", err)
}
condExpr, err := c.resolveCondition(args[2])
if err != nil {
return nil, "", fmt.Errorf("ternary condition: %w", err)
}
c.hasConditions = true
// Build [if cond {trueVal}, falseVal][0]
listLit := &ast.ListLit{
Elts: []ast.Expr{
&ast.Comprehension{
Clauses: []ast.Clause{&ast.IfClause{Condition: condExpr}},
Value: &ast.StructLit{Elts: []ast.Decl{&ast.EmbedDecl{Expr: trueVal}}},
},
falseVal,
},
}
expr := indexExpr(listLit, cueInt(0))
var helmObj string
if trueObj != "" {
helmObj = trueObj
}
if falseObj != "" {
helmObj = falseObj
}
return expr, helmObj, nil
}
func convertList(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) == 0 {
return &ast.ListLit{}, "", nil
}
var helmObj string
var elems []ast.Expr
for _, a := range args {
e, obj, err := c.resolveExpr(a)
if err != nil {
return nil, "", fmt.Errorf("list argument: %w", err)
}
if obj != "" {
helmObj = obj
}
elems = append(elems, e)
}
return &ast.ListLit{Elts: elems}, helmObj, nil
}
func convertDict(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) == 0 {
return &ast.StructLit{}, "", nil
}
if len(args)%2 != 0 {
return nil, "", fmt.Errorf("dict requires an even number of arguments, got %d", len(args))
}
var helmObj string
var fields []ast.Decl
for i := 0; i < len(args); i += 2 {
// Key must be a string literal node.
keyArg := args[i]
if keyArg.node == nil {
return nil, "", fmt.Errorf("dict key must be a string literal")
}
keyNode, ok := keyArg.node.(*parse.StringNode)
if !ok {
return nil, "", fmt.Errorf("dict key must be a string literal")
}
valExpr, valObj, err := c.resolveExpr(args[i+1])
if err != nil {
return nil, "", fmt.Errorf("dict value: %w", err)
}
if valObj != "" {
helmObj = valObj
}
fields = append(fields, &ast.Field{
Label: cueKeyLabel(keyNode.Text),
Value: valExpr,
})
}
return &ast.StructLit{Elts: fields}, helmObj, nil
}
func convertGet(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 2 {
return nil, "", fmt.Errorf("get requires 2 arguments, got %d", len(args))
}
mapExpr, mapObj, err := c.resolveExpr(args[0])
if err != nil {
return nil, "", fmt.Errorf("get map argument: %w", err)
}
var helmObj string
if mapObj != "" {
helmObj = mapObj
refs := c.fieldRefs[mapObj]
if len(refs) > 0 {
c.trackNonScalarRef(mapObj, refs[len(refs)-1])
}
}
// Key can be a literal string or an expression.
keyArg := args[1]
if keyArg.node != nil {
if keyNode, ok := keyArg.node.(*parse.StringNode); ok {
if identRe.MatchString(keyNode.Text) {
return selExpr(mapExpr, keyNode.Text), helmObj, nil
}
return indexExpr(mapExpr, cueString(keyNode.Text)), helmObj, nil
}
}
keyExpr, _, err := c.resolveExpr(keyArg)
if err != nil {
return nil, "", fmt.Errorf("get key argument: %w", err)
}
return indexExpr(mapExpr, keyExpr), helmObj, nil
}
func convertIndex(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 2 {
return nil, "", fmt.Errorf("index requires at least 2 arguments, got %d", len(args))
}
expr, helmObj, err := c.resolveExpr(args[0])
if err != nil {
return nil, "", fmt.Errorf("index collection: %w", err)
}
if helmObj != "" {
refs := c.fieldRefs[helmObj]
if len(refs) > 0 {
c.trackNonScalarRef(helmObj, refs[len(refs)-1])
}
}
for _, keyArg := range args[1:] {
if keyArg.node != nil {
switch kn := keyArg.node.(type) {
case *parse.StringNode:
if identRe.MatchString(kn.Text) {
expr = selExpr(expr, kn.Text)
} else {
expr = indexExpr(expr, cueString(kn.Text))
}
continue
case *parse.NumberNode:
expr = indexExpr(expr, &ast.BasicLit{Kind: token.INT, Value: kn.Text})
continue
}
}
keyExpr, _, err := c.resolveExpr(keyArg)
if err != nil {
return nil, "", fmt.Errorf("index key: %w", err)
}
expr = indexExpr(expr, keyExpr)
}
return expr, helmObj, nil
}
func convertCoalesce(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 1 {
return nil, "", fmt.Errorf("coalesce requires at least 1 argument")
}
c.hasConditions = true
var helmObj string
var elems []ast.Expr
for i, a := range args {
e, obj, err := c.resolveExpr(a)
if err != nil {
return nil, "", fmt.Errorf("coalesce argument: %w", err)
}
if obj != "" {
helmObj = obj
}
if i < len(args)-1 {
condExpr, err := c.resolveCondition(a)
if err != nil {
return nil, "", fmt.Errorf("coalesce condition: %w", err)
}
elems = append(elems, &ast.Comprehension{
Clauses: []ast.Clause{&ast.IfClause{Condition: condExpr}},
Value: &ast.StructLit{Elts: []ast.Decl{&ast.EmbedDecl{Expr: e}}},
})
} else {
elems = append(elems, e)
}
}
return indexExpr(&ast.ListLit{Elts: elems}, cueInt(0)), helmObj, nil
}
func convertMax(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 2 {
return nil, "", fmt.Errorf("max requires at least 2 arguments, got %d", len(args))
}
return convertMinMaxImpl(c, args, "Max")
}
func convertMin(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 2 {
return nil, "", fmt.Errorf("min requires at least 2 arguments, got %d", len(args))
}
return convertMinMaxImpl(c, args, "Min")
}
func convertMinMaxImpl(c *converter, args []funcArg, fn string) (ast.Expr, string, error) {
var helmObj string
var elems []ast.Expr
for _, a := range args {
e, obj, err := c.resolveExpr(a)
if err != nil {
return nil, "", fmt.Errorf("%s argument: %w", strings.ToLower(fn), err)
}
if obj != "" {
helmObj = obj
}
elems = append(elems, e)
}
c.addImport("list")
return importCall("list", fn, &ast.ListLit{Elts: elems}), helmObj, nil
}
func convertTpl(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 2 {
return nil, "", fmt.Errorf("tpl requires 2 arguments, got %d", len(args))
}
// args[0] = template expression, args[1] = context
tmplArg := args[0]
ctxArg := args[1]
var tmplExpr ast.Expr
var tmplObj string
if tmplArg.node != nil {
var err error
tmplExpr, tmplObj, err = c.convertTplArg(tmplArg.node)
if err != nil {
return nil, "", fmt.Errorf("tpl template argument: %w", err)
}
} else {
tmplExpr = tmplArg.expr
tmplObj = tmplArg.obj
}
if ctxArg.node != nil {
c.convertTplContext(ctxArg.node)
} else {
// Pre-resolved context from pipeline — still mark all context objects.
for helmObj := range c.config.ContextObjects {
c.usedContextObjects[helmObj] = true
}
}
c.addImport("encoding/yaml")
c.addImport("text/template")
h := c.tplContextDef()
c.usedHelpers[h.Name] = h
expr := importCall("encoding/yaml", "Unmarshal",
importCall("text/template", "Execute", tmplExpr, ast.NewIdent("_tplContext")))
var helmObj string
if tmplObj != "" {
helmObj = tmplObj
}
return expr, helmObj, nil
}
func convertDig(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 3 {
return nil, "", fmt.Errorf("dig requires at least 3 arguments, got %d", len(args))
}
// Last arg is the map, second-to-last is the default,
// everything before that is the key path.
mapArg := args[len(args)-1]
defaultArg := args[len(args)-2]
keyArgs := args[:len(args)-2]
mapExpr, helmObj, err := c.resolveExpr(mapArg)
if err != nil {
return nil, "", fmt.Errorf("dig map argument: %w", err)
}
if helmObj != "" {
// Track the map as a non-scalar ref.
refs := c.fieldRefs[helmObj]
if len(refs) > 0 {
c.trackNonScalarRef(helmObj, refs[len(refs)-1])
}
}
defaultValExpr, err := c.resolveLiteral(defaultArg)
if err != nil {
return nil, "", fmt.Errorf("dig default argument: %w", err)
}
// Build the path list: ["key1", "key2", ...]
var pathElts []ast.Expr
for _, ka := range keyArgs {
keyExpr, err := c.resolveLiteral(ka)
if err != nil {
return nil, "", fmt.Errorf("dig key argument: %w", err)
}
pathElts = append(pathElts, keyExpr)
}
pathList := &ast.ListLit{Elts: pathElts}
c.usedHelpers["_dig"] = HelperDef{Name: "_dig", Def: digDef}
expr := selExpr(
parenExpr(binOp(token.AND, ast.NewIdent("_dig"), &ast.StructLit{Elts: []ast.Decl{
&ast.Field{Label: ast.NewIdent("#path"), Value: pathList},
&ast.Field{Label: ast.NewIdent("#default"), Value: defaultValExpr},
&ast.Field{Label: ast.NewIdent("#arg"), Value: mapExpr},
}})),
"res",
)
return expr, helmObj, nil
}
func convertOmit(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 2 {
return nil, "", fmt.Errorf("omit requires at least 2 arguments, got %d", len(args))
}
// First arg is the map, remaining are keys to omit.
mapArg := args[0]
keyArgs := args[1:]
mapExpr, helmObj, err := c.resolveExpr(mapArg)
if err != nil {
return nil, "", fmt.Errorf("omit map argument: %w", err)
}
if helmObj != "" {
refs := c.fieldRefs[helmObj]
if len(refs) > 0 {
c.trackNonScalarRef(helmObj, refs[len(refs)-1])
}
}
var keyElts []ast.Expr
for _, ka := range keyArgs {
keyExpr, err := c.resolveLiteral(ka)
if err != nil {
return nil, "", fmt.Errorf("omit key argument: %w", err)
}
keyElts = append(keyElts, keyExpr)
}
keyList := &ast.ListLit{Elts: keyElts}
c.addImport("list")
c.usedHelpers["_omit"] = HelperDef{
Name: "_omit", Def: omitDef, Imports: []string{"list"},
}
expr := parenExpr(binOp(token.AND, ast.NewIdent("_omit"), compactStruct(
&ast.Field{Label: ast.NewIdent("#arg"), Value: mapExpr},
&ast.Field{Label: ast.NewIdent("#omit"), Value: keyList},
)))
return expr, helmObj, nil
}
// convertMerge handles Sprig's merge function: merge dst src1 src2 ...
// The destination (first arg) wins over sources. We chain pairwise
// _merge helpers for each source argument.
func convertMerge(c *converter, args []funcArg) (ast.Expr, string, error) {
return convertMergeImpl(c, args, "_merge", mergeDef)
}
// convertMergeOverwrite handles Sprig's mergeOverwrite function:
// mergeOverwrite dst src1 src2 ... where sources override the destination.
func convertMergeOverwrite(c *converter, args []funcArg) (ast.Expr, string, error) {
return convertMergeImpl(c, args, "_mergeOverwrite", mergeOverwriteDef)
}
func convertMergeImpl(c *converter, args []funcArg, helperName, helperDef string) (ast.Expr, string, error) {
if len(args) < 2 {
return nil, "", fmt.Errorf("%s requires at least 2 arguments, got %d", helperName, len(args))
}
c.usedHelpers[helperName] = HelperDef{Name: helperName, Def: helperDef}
// Resolve the destination (first argument).
result, helmObj, err := c.resolveExpr(args[0])
if err != nil {
return nil, "", fmt.Errorf("%s destination: %w", helperName, err)
}
// Mark the destination as non-scalar.
if helmObj != "" {
refs := c.fieldRefs[helmObj]
if len(refs) > 0 {
c.trackNonScalarRef(helmObj, refs[len(refs)-1])
}
}
// Chain each source: result = (_merge & {#a: result, #b: src}).out
for i := 1; i < len(args); i++ {
srcExpr, srcObj, err := c.resolveExpr(args[i])
if err != nil {
return nil, "", fmt.Errorf("%s source %d: %w", helperName, i, err)
}
if srcObj != "" {
refs := c.fieldRefs[srcObj]
if len(refs) > 0 {
c.trackNonScalarRef(srcObj, refs[len(refs)-1])
}
}
result = selExpr(
parenExpr(binOp(token.AND, ast.NewIdent(helperName), compactStruct(
&ast.Field{Label: ast.NewIdent("#a"), Value: result},
&ast.Field{Label: ast.NewIdent("#b"), Value: srcExpr},
))),
"out",
)
}
return result, helmObj, nil
}
// convertTypeIs handles Sprig's typeIs function in pipeline position:
// typeIs "string" .value → (value & string) != _|_
func convertTypeIs(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 2 {
return nil, "", fmt.Errorf("typeIs requires 2 arguments, got %d", len(args))
}
typeStr, err := c.resolveLiteral(args[0])
if err != nil {
return nil, "", fmt.Errorf("typeIs type argument: %w", err)
}
strLit, ok := typeStr.(*ast.BasicLit)
if !ok || strLit.Kind != token.STRING {
return nil, "", fmt.Errorf("typeIs type must be a string literal")
}
// Strip quotes from the literal.
typeName := strings.Trim(strLit.Value, "\"")
valExpr, helmObj, err := c.resolveExpr(args[1])
if err != nil {
return nil, "", fmt.Errorf("typeIs value argument: %w", err)
}
typeIsMap := map[string]string{
"bool": "bool",
"string": "string",
"int": "int",
"int64": "int",
"float64": "float",
"map[string]interface {}": "{...}",
"[]interface {}": "[...]",
}
if typeName == "<nil>" || typeName == "<invalid>" {
return binOp(token.EQL, valExpr, &ast.BottomLit{}), helmObj, nil
}
cueType, ok := typeIsMap[typeName]
if !ok {
return nil, "", fmt.Errorf("unsupported typeIs type: %q", typeName)
}
var typeExpr ast.Expr
switch cueType {
case "{...}":
typeExpr = &ast.StructLit{
Elts: []ast.Decl{&ast.Ellipsis{}},
}
case "[...]":
typeExpr = &ast.ListLit{
Elts: []ast.Expr{&ast.Ellipsis{}},
}
default:
typeExpr = ast.NewIdent(cueType)
}
return binOp(token.NEQ, parenExpr(binOp(token.AND, valExpr, typeExpr)), &ast.BottomLit{}), helmObj, nil
}
// convertDeepCopy handles Sprig's deepCopy function. CUE values are
// immutable so deepCopy is a no-op — return the argument unchanged.
func convertDeepCopy(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 1 {
return nil, "", fmt.Errorf("deepCopy requires 1 argument, got %d", len(args))
}
return c.resolveExpr(args[0])
}
// makeConvertCmp returns a coreFunc converter for a comparison operator.
// The Go template builtins eq, ne, lt, gt, le, ge take two arguments
// and produce a boolean. In CUE this becomes a binary operation.
func makeConvertCmp(op token.Token) func(c *converter, args []funcArg) (ast.Expr, string, error) {
return func(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) != 2 {
return nil, "", fmt.Errorf("comparison requires 2 arguments, got %d", len(args))
}
a, _, err := c.resolveExpr(args[0])
if err != nil {
return nil, "", err
}
b, _, err := c.resolveExpr(args[1])
if err != nil {
return nil, "", err
}
return binOp(op, a, b), "", nil
}
}
// convertConcat handles Sprig's concat function which concatenates
// multiple lists: concat $list1 $list2 ... → list.Concat([list1, list2, ...]).
func convertConcat(c *converter, args []funcArg) (ast.Expr, string, error) {
if len(args) < 1 {
return nil, "", fmt.Errorf("concat requires at least 1 argument, got %d", len(args))
}
elts := make([]ast.Expr, len(args))
for i, a := range args {
e, helmObj, err := c.resolveExpr(a)
if err != nil {
return nil, "", fmt.Errorf("concat argument %d: %w", i, err)
}
elts[i] = e
// Track as non-scalar since concat arguments are lists.
if helmObj != "" {
if f, ok := a.node.(*parse.FieldNode); ok && len(f.Ident) >= 2 {
c.trackNonScalarRef(helmObj, f.Ident[1:])
}
}
}
c.addImport("list")
return importCall("list", "Concat", &ast.ListLit{Elts: elts}), "", nil
}