This repository has been archived by the owner on Jun 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mask.go
102 lines (93 loc) · 2.22 KB
/
mask.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
92
93
94
95
96
97
98
99
100
101
102
package structural
import (
"cuelang.org/go/cue"
)
func CueMask(sorig, smask string) (string, error) {
out := NewpvStruct()
vorigi, err := r.Compile("", sorig)
if err != nil {
return "", err
}
vorig := vorigi.Value()
if vorig.Err() != nil {
return "", vorig.Err()
}
vmaski, err := r.Compile("", smask)
if err != nil {
return "", err
}
vmask := vmaski.Value()
if vmask.Err() != nil {
return "", vmask.Err()
}
err = cueMask(out, vorig, vmask)
if err != nil {
return "", err
}
return out.ToString()
}
func cueMask(out *pvStruct, vorig, vmask cue.Value) error {
// Loop over the keys in orig
vorigStruct, err := vorig.Struct()
if err != nil {
return err
}
vorigIter := vorigStruct.Fields()
for vorigIter.Next() {
key := vorigIter.Label()
origVal := vorigIter.Value()
maskLookup, err := vmask.LookupField(key)
// Include anythig not in mask
if err != nil {
out.Set(key, *ExprFromValue(origVal))
continue
}
maskVal := maskLookup.Value
// If orig is a builtin and doesn't unify with mask, then use it
if isBuiltin(origVal) && origVal.Unify(maskVal).Kind() == cue.BottomKind {
out.Set(key, *ExprFromValue(origVal))
continue
}
if isList(origVal) {
lval := NewpvList()
origListIter, err := origVal.List()
if err != nil {
return err
}
// If orig is a list but mask isn't, keep all elements
// of the list that don't unify with mask
if !isList(maskVal) {
for origListIter.Next() {
elem := origListIter.Value()
if elem.Unify(maskVal).Kind() == cue.BottomKind {
lval.Append(*ExprFromValue(elem))
}
}
} else if isList(maskVal) {
// Else, consider element-wise
maskListIter, err := maskVal.List()
if err != nil {
return err
}
for origListIter.Next() && maskListIter.Next() {
origElem := origListIter.Value()
maskElem := maskListIter.Value()
if origElem.Unify(maskElem).Kind() == cue.BottomKind {
lval.Append(*ExprFromValue(origElem))
}
}
}
out.Set(key, *lval.ToExpr())
}
// If orig is a struct then recurse
if isStruct(origVal) {
rval := NewpvStruct()
err = cueMask(rval, origVal, maskVal)
if err != nil {
return err
}
out.Set(key, *rval.ToExpr())
}
}
return nil
}