github.com/oam-dev/kubevela@v1.9.11/references/cuegen/option.go (about)

     1  /*
     2  Copyright 2023 The KubeVela 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 cuegen
    18  
    19  import goast "go/ast"
    20  
    21  // Type is a special cue type
    22  type Type string
    23  
    24  const (
    25  	// TypeAny converts go type to _(top value) in cue
    26  	TypeAny Type = "any"
    27  	// TypeEllipsis converts go type to {...} in cue
    28  	TypeEllipsis Type = "ellipsis"
    29  )
    30  
    31  type options struct {
    32  	types      map[string]Type
    33  	nullable   bool
    34  	typeFilter func(typ *goast.TypeSpec) bool
    35  }
    36  
    37  // Option is a function that configures generation options
    38  type Option func(opts *options)
    39  
    40  func newDefaultOptions() *options {
    41  	return &options{
    42  		types: map[string]Type{
    43  			"map[string]interface{}": TypeEllipsis, "map[string]any": TypeEllipsis,
    44  			"interface{}": TypeAny, "any": TypeAny,
    45  		},
    46  		nullable:   false,
    47  		typeFilter: func(_ *goast.TypeSpec) bool { return true },
    48  	}
    49  }
    50  
    51  // WithTypes appends go types as specified cue types in generation
    52  //
    53  // Example:*k8s.io/apimachinery/pkg/apis/meta/v1/unstructured.Unstructured, TypeEllipsis
    54  //
    55  //   - Default any types: interface{}, any
    56  //   - Default ellipsis types: map[string]interface{}, map[string]any
    57  func WithTypes(types map[string]Type) Option {
    58  	return func(opts *options) {
    59  		for k, v := range types {
    60  			opts.types[k] = v
    61  		}
    62  	}
    63  }
    64  
    65  // WithNullable will generate null enum for pointer type
    66  func WithNullable() Option {
    67  	return func(opts *options) {
    68  		opts.nullable = true
    69  	}
    70  }
    71  
    72  // WithTypeFilter filters top struct types to be generated, and filter returns true to generate the type, otherwise false
    73  func WithTypeFilter(filter func(typ *goast.TypeSpec) bool) Option {
    74  	// return invalid option if filter is nil, so that it will not be applied
    75  	if filter == nil {
    76  		return nil
    77  	}
    78  
    79  	return func(opts *options) {
    80  		opts.typeFilter = filter
    81  	}
    82  }