|
| 1 | +package custom_cel |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/google/cel-go/cel" |
| 5 | + "github.com/google/cel-go/common" |
| 6 | + "github.com/google/cel-go/common/ast" |
| 7 | + "github.com/google/cel-go/common/operators" |
| 8 | + "github.com/google/cel-go/common/types" |
| 9 | + "github.com/google/cel-go/common/types/ref" |
| 10 | + "github.com/google/cel-go/common/types/traits" |
| 11 | + "github.com/google/cel-go/parser" |
| 12 | + "k8s.io/apiserver/pkg/cel/library" |
| 13 | + "slices" |
| 14 | + "sort" |
| 15 | +) |
| 16 | + |
| 17 | +// Lists returns a cel.EnvOption to configure extended functions Lists manipulation. |
| 18 | +// |
| 19 | +// # SortBy |
| 20 | +// |
| 21 | +// Returns a new sorted list by the field defined. |
| 22 | +// It supports all types that implements the base traits.Comparer interface. |
| 23 | +// |
| 24 | +// <list>.sort_by(obj, obj.field) ==> <list> |
| 25 | +// |
| 26 | +// Examples: |
| 27 | +// |
| 28 | +// [2,3,1].sort_by(i,i) ==> [1,2,3] |
| 29 | +// |
| 30 | +// [{Name: "c", Age: 10}, {Name: "a", Age: 30}, {Name: "b", Age: 1}].sort_by(obj, obj.age) ==> [{Name: "b", Age: 1}, {Name: "c", Age: 10}, {Name: "a", Age: 30}] |
| 31 | +// |
| 32 | +// # ReverseList |
| 33 | +// |
| 34 | +// Returns a new list in reverse order. |
| 35 | +// It supports all types that implements the base traits.Comparer interface |
| 36 | +// |
| 37 | +// <list>.reverse_list() ==> <list> |
| 38 | +// |
| 39 | +// # Examples |
| 40 | +// |
| 41 | +// [1,2,3].reverse_list() ==> [3,2,1] |
| 42 | +// |
| 43 | +// ["x", "y", "z"].reverse_list() ==> ["z", "y", "x"] |
| 44 | +func Lists() cel.EnvOption { |
| 45 | + return cel.Lib(listsLib{}) |
| 46 | +} |
| 47 | + |
| 48 | +type listsLib struct{} |
| 49 | + |
| 50 | +// CompileOptions implements the Library interface method defining the basic compile configuration |
| 51 | +func (u listsLib) CompileOptions() []cel.EnvOption { |
| 52 | + dynListType := cel.ListType(cel.DynType) |
| 53 | + sortByMacro := parser.NewReceiverMacro("sort_by", 2, makeSortBy) |
| 54 | + return []cel.EnvOption{ |
| 55 | + library.Lists(), |
| 56 | + cel.Macros(sortByMacro), |
| 57 | + cel.Function( |
| 58 | + "pair", |
| 59 | + cel.Overload( |
| 60 | + "make_pair", |
| 61 | + []*cel.Type{cel.DynType, cel.DynType}, |
| 62 | + cel.DynType, |
| 63 | + cel.BinaryBinding(makePair), |
| 64 | + ), |
| 65 | + ), |
| 66 | + cel.Function( |
| 67 | + "sort", |
| 68 | + cel.Overload( |
| 69 | + "sort_list", |
| 70 | + []*cel.Type{dynListType}, |
| 71 | + dynListType, |
| 72 | + cel.UnaryBinding(makeSort), |
| 73 | + ), |
| 74 | + ), |
| 75 | + cel.Function( |
| 76 | + "reverse_list", |
| 77 | + cel.MemberOverload( |
| 78 | + "reverse_list_id", |
| 79 | + []*cel.Type{cel.ListType(cel.DynType)}, |
| 80 | + cel.ListType(cel.DynType), |
| 81 | + cel.UnaryBinding(makeReverse), |
| 82 | + ), |
| 83 | + ), |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +// ProgramOptions implements the Library interface method defining the basic program options |
| 88 | +func (u listsLib) ProgramOptions() []cel.ProgramOption { |
| 89 | + return []cel.ProgramOption{} |
| 90 | +} |
| 91 | + |
| 92 | +type pair struct { |
| 93 | + order ref.Val |
| 94 | + value ref.Val |
| 95 | +} |
| 96 | + |
| 97 | +var ( |
| 98 | + orderKey = types.DefaultTypeAdapter.NativeToValue("order") |
| 99 | + valueKey = types.DefaultTypeAdapter.NativeToValue("value") |
| 100 | +) |
| 101 | + |
| 102 | +func makePair(order ref.Val, value ref.Val) ref.Val { |
| 103 | + if _, ok := order.(traits.Comparer); !ok { |
| 104 | + return types.ValOrErr(order, "unable to build ordered pair with value %v", order.Value()) |
| 105 | + } |
| 106 | + return types.NewStringInterfaceMap(types.DefaultTypeAdapter, map[string]any{ |
| 107 | + "order": order.Value(), |
| 108 | + "value": value.Value(), |
| 109 | + }) |
| 110 | +} |
| 111 | + |
| 112 | +func makeSort(itemsVal ref.Val) ref.Val { |
| 113 | + items, ok := itemsVal.(traits.Lister) |
| 114 | + if !ok { |
| 115 | + return types.ValOrErr(itemsVal, "unable to convert to traits.Lister") |
| 116 | + } |
| 117 | + |
| 118 | + pairs := make([]pair, 0, items.Size().Value().(int64)) |
| 119 | + index := 0 |
| 120 | + for it := items.Iterator(); it.HasNext().(types.Bool); { |
| 121 | + curr, ok := it.Next().(traits.Mapper) |
| 122 | + if !ok { |
| 123 | + return types.NewErr("unable to convert elem %d to traits.Mapper", index) |
| 124 | + } |
| 125 | + |
| 126 | + pairs = append(pairs, pair{ |
| 127 | + order: curr.Get(orderKey), |
| 128 | + value: curr.Get(valueKey), |
| 129 | + }) |
| 130 | + index++ |
| 131 | + } |
| 132 | + |
| 133 | + sort.Slice(pairs, func(i, j int) bool { |
| 134 | + return pairs[i].order.(traits.Comparer).Compare(pairs[j].order) == types.IntNegOne |
| 135 | + }) |
| 136 | + |
| 137 | + var ordered []interface{} |
| 138 | + for _, v := range pairs { |
| 139 | + ordered = append(ordered, v.value.Value()) |
| 140 | + } |
| 141 | + |
| 142 | + return types.NewDynamicList(types.DefaultTypeAdapter, ordered) |
| 143 | +} |
| 144 | + |
| 145 | +func extractIdent(e ast.Expr) (string, bool) { |
| 146 | + if e.Kind() == ast.IdentKind { |
| 147 | + return e.AsIdent(), true |
| 148 | + } |
| 149 | + return "", false |
| 150 | +} |
| 151 | + |
| 152 | +func makeSortBy(eh parser.ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) { |
| 153 | + v, found := extractIdent(args[0]) |
| 154 | + if !found { |
| 155 | + return nil, eh.NewError(args[0].ID(), "argument is not an identifier") |
| 156 | + } |
| 157 | + |
| 158 | + var fn = args[1] |
| 159 | + |
| 160 | + init := eh.NewList() |
| 161 | + condition := eh.NewLiteral(types.True) |
| 162 | + |
| 163 | + step := eh.NewCall(operators.Add, eh.NewAccuIdent(), eh.NewList( |
| 164 | + eh.NewCall("pair", fn, args[0]), |
| 165 | + )) |
| 166 | + |
| 167 | + /* |
| 168 | + This comprehension is expanded to: |
| 169 | + __result__ = [] # init expr |
| 170 | + for $v in $target: |
| 171 | + __result__ += [pair(fn(v), v)] # step expr |
| 172 | + return sort(__result__) # result expr |
| 173 | + */ |
| 174 | + mapped := eh.NewComprehension( |
| 175 | + target, |
| 176 | + v, |
| 177 | + parser.AccumulatorName, |
| 178 | + init, |
| 179 | + condition, |
| 180 | + step, |
| 181 | + eh.NewCall( |
| 182 | + "sort", |
| 183 | + eh.NewAccuIdent(), |
| 184 | + ), |
| 185 | + ) |
| 186 | + |
| 187 | + return mapped, nil |
| 188 | +} |
| 189 | + |
| 190 | +func makeReverse(itemsVal ref.Val) ref.Val { |
| 191 | + items, ok := itemsVal.(traits.Lister) |
| 192 | + if !ok { |
| 193 | + return types.ValOrErr(itemsVal, "unable to convert to traits.Lister") |
| 194 | + } |
| 195 | + |
| 196 | + orderedItems := make([]ref.Val, 0, items.Size().Value().(int64)) |
| 197 | + for it := items.Iterator(); it.HasNext().(types.Bool); { |
| 198 | + orderedItems = append(orderedItems, it.Next()) |
| 199 | + } |
| 200 | + |
| 201 | + slices.Reverse(orderedItems) |
| 202 | + |
| 203 | + return types.NewDynamicList(types.DefaultTypeAdapter, orderedItems) |
| 204 | +} |
0 commit comments