| 1 |
/* |
| 2 |
Copyright 2024 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package cel |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"reflect" |
| 22 |
|
| 23 |
"github.com/blang/semver/v4" |
| 24 |
"github.com/google/cel-go/cel" |
| 25 |
"github.com/google/cel-go/common/types" |
| 26 |
"github.com/google/cel-go/common/types/ref" |
| 27 |
) |
| 28 |
|
| 29 |
var ( |
| 30 |
SemverType = cel.ObjectType("kubernetes.Semver") |
| 31 |
) |
| 32 |
|
| 33 |
// Semver provdes a CEL representation of a [semver.Version]. |
| 34 |
type Semver struct { |
| 35 |
semver.Version |
| 36 |
} |
| 37 |
|
| 38 |
func (v Semver) ConvertToNative(typeDesc reflect.Type) (interface{}, error) { |
| 39 |
if reflect.TypeOf(v.Version).AssignableTo(typeDesc) { |
| 40 |
return v.Version, nil |
| 41 |
} |
| 42 |
if reflect.TypeOf("").AssignableTo(typeDesc) { |
| 43 |
return v.Version.String(), nil |
| 44 |
} |
| 45 |
return nil, fmt.Errorf("type conversion error from 'Semver' to '%v'", typeDesc) |
| 46 |
} |
| 47 |
|
| 48 |
func (v Semver) ConvertToType(typeVal ref.Type) ref.Val { |
| 49 |
switch typeVal { |
| 50 |
case SemverType: |
| 51 |
return v |
| 52 |
case types.TypeType: |
| 53 |
return SemverType |
| 54 |
default: |
| 55 |
return types.NewErr("type conversion error from '%s' to '%s'", SemverType, typeVal) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
func (v Semver) Equal(other ref.Val) ref.Val { |
| 60 |
otherDur, ok := other.(Semver) |
| 61 |
if !ok { |
| 62 |
return types.MaybeNoSuchOverloadErr(other) |
| 63 |
} |
| 64 |
return types.Bool(v.Version.EQ(otherDur.Version)) |
| 65 |
} |
| 66 |
|
| 67 |
func (v Semver) Type() ref.Type { |
| 68 |
return SemverType |
| 69 |
} |
| 70 |
|
| 71 |
func (v Semver) Value() interface{} { |
| 72 |
return v.Version |
| 73 |
} |