k8s.io/apiserver@v0.31.1/pkg/cel/mutation/unstructured/typeref.go (about)

     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 unstructured
    18  
    19  import (
    20  	"github.com/google/cel-go/common/types"
    21  	"github.com/google/cel-go/common/types/ref"
    22  
    23  	"k8s.io/apiserver/pkg/cel/mutation/common"
    24  )
    25  
    26  // TypeRef is the implementation of TypeRef for an unstructured object.
    27  // This is especially usefully when the schema is not known or available.
    28  type TypeRef struct {
    29  	celObjectType *types.Type
    30  	celTypeType   *types.Type
    31  }
    32  
    33  func (r *TypeRef) HasTrait(trait int) bool {
    34  	return common.ObjectTraits|trait != 0
    35  }
    36  
    37  // TypeName returns the name of this TypeRef.
    38  func (r *TypeRef) TypeName() string {
    39  	return r.celObjectType.TypeName()
    40  }
    41  
    42  // Val returns an instance given the fields.
    43  func (r *TypeRef) Val(fields map[string]ref.Val) ref.Val {
    44  	return common.NewObjectVal(r, fields)
    45  }
    46  
    47  // CELType returns the type. The returned type is of TypeType type.
    48  func (r *TypeRef) CELType() *types.Type {
    49  	return r.celTypeType
    50  }
    51  
    52  // Field looks up the field by name.
    53  // This is the unstructured version that allows any name as the field name.
    54  // The returned field is of DynType type.
    55  func (r *TypeRef) Field(name string) (*types.FieldType, bool) {
    56  	return NewFieldType(name), true
    57  }
    58  
    59  // NewTypeRef creates a TypeRef by the given field name.
    60  func NewTypeRef(name string) *TypeRef {
    61  	objectType := types.NewObjectType(name, common.ObjectTraits)
    62  	return &TypeRef{
    63  		celObjectType: objectType,
    64  		celTypeType:   types.NewTypeTypeWithParam(objectType),
    65  	}
    66  }