Debian Codegraph @

pkg/cel/url.go

raw
1 /*
2 Copyright 2022 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 "net/url"
22 "reflect"
23
24 "github.com/google/cel-go/cel"
25 "github.com/google/cel-go/checker/decls"
26 "github.com/google/cel-go/common/types"
27 "github.com/google/cel-go/common/types/ref"
28 )
29
30 // URL provides a CEL representation of a URL.
31 type URL struct {
32 *url.URL
33 }
34
35 var (
36 URLObject = decls.NewObjectType("kubernetes.URL")
37 typeValue = types.NewTypeValue("kubernetes.URL")
38 URLType = cel.ObjectType("kubernetes.URL")
39 )
40
41 // ConvertToNative implements ref.Val.ConvertToNative.
42 func (d URL) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {
43 if reflect.TypeOf(d.URL).AssignableTo(typeDesc) {
44 return d.URL, nil
45 }
46 if reflect.TypeOf("").AssignableTo(typeDesc) {
47 return d.URL.String(), nil
48 }
49 return nil, fmt.Errorf("type conversion error from 'URL' to '%v'", typeDesc)
50 }
51
52 // ConvertToType implements ref.Val.ConvertToType.
53 func (d URL) ConvertToType(typeVal ref.Type) ref.Val {
54 switch typeVal {
55 case typeValue:
56 return d
57 case types.TypeType:
58 return typeValue
59 }
60 return types.NewErr("type conversion error from '%s' to '%s'", typeValue, typeVal)
61 }
62
63 // Equal implements ref.Val.Equal.
64 func (d URL) Equal(other ref.Val) ref.Val {
65 otherDur, ok := other.(URL)
66 if !ok {
67 return types.MaybeNoSuchOverloadErr(other)
68 }
69 return types.Bool(d.URL.String() == otherDur.URL.String())
70 }
71
72 // Type implements ref.Val.Type.
73 func (d URL) Type() ref.Type {
74 return typeValue
75 }
76
77 // Value implements ref.Val.Value.
78 func (d URL) Value() interface{} {
79 return d.URL
80 }