-
Notifications
You must be signed in to change notification settings - Fork 22
/
functions.go
91 lines (82 loc) · 2.58 KB
/
functions.go
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
// SPDX-FileCopyrightText: 2023 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0
package install
import (
"github.com/mandelsoft/spiff/dynaml"
"github.com/mandelsoft/spiff/spiffing"
"github.com/mandelsoft/spiff/yaml"
"github.com/open-component-model/ocm/v2/pkg/contexts/ocm"
)
func NewFunctions(ctx ocm.Context, credvals CredentialValues) spiffing.Functions {
funcs := spiffing.NewFunctions()
funcs.RegisterFunction("getCredentials", spiffGetCredentials(credvals))
funcs.RegisterFunction("hasCredentials", spiffHasCredentials(credvals))
return funcs
}
func spiffGetCredentials(credvals CredentialValues) spiffing.Function {
return func(arguments []interface{}, binding dynaml.Binding) (interface{}, dynaml.EvaluationInfo, bool) {
var info dynaml.EvaluationInfo
if len(arguments) < 1 || len(arguments) > 2 {
return info.Error("credential name and optional property name argument required")
}
name, ok := arguments[0].(string)
if !ok {
return info.Error("credential name argument must be string")
}
creds := credvals[name]
if creds == nil {
return info.Error("credential %q not found", name)
}
if len(arguments) == 1 {
val := map[string]spiffing.Node{}
for n, v := range creds {
val[n] = yaml.NewNode(v, "credential")
}
return val, info, true
}
key, ok := arguments[1].(string)
if !ok {
return info.Error("credential property argument must be string")
}
if key == "*" || key == "" {
if len(creds) > 1 {
return info.Error("there are multiple credential properties")
}
for _, v := range creds {
return v, info, true
}
return "", info, true
}
v, ok := creds[key]
if !ok {
return info.Error("there is no credential property %q", key)
}
return v, info, true
}
}
func spiffHasCredentials(credvals CredentialValues) dynaml.Function {
return func(arguments []interface{}, binding dynaml.Binding) (interface{}, dynaml.EvaluationInfo, bool) {
var info dynaml.EvaluationInfo
if len(arguments) < 1 || len(arguments) > 2 {
return info.Error("credential name and optional property name argument required")
}
name, ok := arguments[0].(string)
if !ok {
return info.Error("credential name argument must be string")
}
creds := credvals[name]
if creds == nil || len(arguments) == 1 {
return creds != nil, info, true
}
key, ok := arguments[1].(string)
if !ok {
return info.Error("credential property argument must be string")
}
if key == "*" || key == "" {
return len(creds) == 1, info, true
}
_, ok = creds[key]
return ok, info, true
}
}