astmodel

package
v0.0.0-...-b4ea117 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2024 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CodeGeneratedFileSuffix is used to identify generated files (note there is no file extension here)
	CodeGeneratedFileSuffix = "_gen"

	// ARMReferenceTag is the tag ID used for specifying references to other ARM resources on properties.
	ARMReferenceTag = "armReference"

	// OptionalConfigMapPairTag is the tag ID used for specifying an optional configMap reference pair.
	// There will be 2 of these tags on two different properties, each pointing to the ARM property they apply to.
	// For example:
	// PrincipalId *string `optionalConfigMapPair:"PrincipalId"`
	// PrincipalIdRef *genruntime.ConfigMapReference `optionalConfigMapPair:"PrincipalId"`
	OptionalConfigMapPairTag = "optionalConfigMapPair"

	// SerializationType is the tag ID used for controlling if resources have special serialization rules
	SerializationType                        = "serializationType"
	SerializationTypeExplicitEmptyCollection = "explicitEmptyCollection"
)
View Source
const (
	Exported    = Visibility("exported")
	NotExported = Visibility("notexported")
)
View Source
const (
	EnumValidationName     string = "Enum"
	RequiredValidationName string = "Required"

	// Strings:
	MinLengthValidationName string = "MinLength"
	MaxLengthValidationName string = "MaxLength"
	PatternValidationName   string = "Pattern"

	// Arrays:
	MinItemsValidationName    string = "MinItems"
	MaxItemsValidationName    string = "MaxItems"
	UniqueItemsValidationName string = "UniqueItems"

	// Numbers:
	MaximumValidationName          string = "Maximum"
	MinimumValidationName          string = "Minimum"
	ExclusiveMaximumValidationName string = "ExclusiveMaximum"
	ExclusiveMinimumValidationName string = "ExclusiveMinimum"
	MultipleOfValidationName       string = "MultipleOf"
)

see: https://book.kubebuilder.io/reference/markers/crd-validation.html

View Source
const (
	// ResourceScopeLocation is a resource deployed into a location (subscription + location)
	ResourceScopeLocation = ResourceScope("location")
	// ResourceScopeResourceGroup is a standard ARM resource that deploys into a resource group.
	ResourceScopeResourceGroup = ResourceScope("resourcegroup")
	// ResourceScopeExtension is an extension resource. Extension resources can have any resource as their parent.
	ResourceScopeExtension = ResourceScope("extension")
	// ResourceScopeTenant is an ARM resource at the tenant level (for example subscription, managementGroup, etc)
	ResourceScopeTenant = ResourceScope("tenant")
)
View Source
const (
	ResourceOperationGet    = ResourceOperation("GET")
	ResourceOperationHead   = ResourceOperation("HEAD")
	ResourceOperationPut    = ResourceOperation("PUT")
	ResourceOperationDelete = ResourceOperation("DELETE")
)
View Source
const (
	APIVersionProperty               = "APIVersion" // Used by armconversion package
	AzureNameProperty                = "AzureName"
	NameProperty                     = "Name" // Used by armconversion package
	OwnerProperty                    = "Owner"
	SetAzureNameFunc                 = "SetAzureName"
	TypeProperty                     = "Type" // Used by armconversion package
	OperatorSpecProperty             = "OperatorSpec"
	OperatorSpecSecretsProperty      = "Secrets"
	OperatorSpecConfigMapsProperty   = "ConfigMaps"
	ConditionsProperty               = "Conditions"
	OptionalConfigMapReferenceSuffix = "FromConfig"
	UserAssignedIdentitiesProperty   = "UserAssignedIdentities"
	UserAssignedIdentitiesTypeName   = "UserAssignedIdentityDetails"
)

These are some magical field names which we're going to use or generate

View Source
const (
	StorageFlag = TypeFlag("storage")
	ARMFlag     = TypeFlag("arm")
	OneOfFlag   = TypeFlag("oneof")
	DoNotPrune  = TypeFlag("donotprune")
)
View Source
const (
	// SpecSuffix is the suffix used for all Spec types
	SpecSuffix = "_Spec"
	// StatusSuffix is the suffix used for all Status types
	StatusSuffix = "_STATUS"
	// ARMSuffix is the suffix used for all ARM types
	ARMSuffix = "_ARM"
	// ARMPackageName is the name used for ARM subpackages
	ARMPackageName = "arm"
)
View Source
const (
	CompatPackageName = "compat"
)
View Source
const GeneratorVersion string = "v1api"
View Source
const (
	GroupSuffix = ".azure.com"
)
View Source
const (
	StoragePackageName = "storage"
)

Variables

View Source
var (
	AdditionalPropertiesPropertyName = PropertyName("AdditionalProperties")
	AdditionalPropertiesJsonName     = "additionalProperties"
)

for want of a better place for this to live…

View Source
var (
	OptionalAnyType    = &OptionalType{AnyType}
	OptionalARMIDType  = &OptionalType{ARMIDType}
	OptionalBoolType   = &OptionalType{BoolType}
	OptionalErrorType  = &OptionalType{ErrorType}
	OptionalFloatType  = &OptionalType{FloatType}
	OptionalIntType    = &OptionalType{IntType}
	OptionalStringType = &OptionalType{StringType}
	OptionalUInt64Type = &OptionalType{UInt64Type}
	OptionalUInt32Type = &OptionalType{UInt32Type}
)

Commonly used optionals We bypass the constructor as that has a dependency on the cachedOptionals map that won't have been initialized yet

View Source
var (
	// References to standard Go Libraries
	ErrorsReference  = MakeExternalPackageReference("errors")
	FmtReference     = MakeExternalPackageReference("fmt")
	JsonReference    = MakeExternalPackageReference("encoding/json")
	OSReference      = MakeExternalPackageReference("os")
	ReflectReference = MakeExternalPackageReference("reflect")
	StringsReference = MakeExternalPackageReference("strings")
	TestingReference = MakeExternalPackageReference("testing")
	ContextReference = MakeExternalPackageReference("context")

	// References to our Libraries
	GenRuntimeReference             = MakeExternalPackageReference(genRuntimePathPrefix)
	GenRuntimeConditionsReference   = MakeExternalPackageReference(genRuntimePathPrefix + "/conditions")
	GenRuntimeRegistrationReference = MakeExternalPackageReference(genRuntimePathPrefix + "/registration")
	ReflectHelpersReference         = MakeExternalPackageReference(reflectHelpersPath)
	GenRuntimeConfigMapsReference   = MakeExternalPackageReference(genRuntimePathPrefix + "/configmaps")
	GenRuntimeSecretsReference      = MakeExternalPackageReference(genRuntimePathPrefix + "/secrets")
	GenericARMClientReference       = MakeExternalPackageReference(genericARMClientPath)

	// References to other libraries
	APIExtensionsReference       = MakeExternalPackageReference("k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1")
	APIExtensionsJSONReference   = MakeExternalPackageReference("k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/JSON")
	APIMachineryErrorsReference  = MakeExternalPackageReference("k8s.io/apimachinery/pkg/util/errors")
	APIMachineryRuntimeReference = MakeExternalPackageReference("k8s.io/apimachinery/pkg/runtime")
	APIMachinerySchemaReference  = MakeExternalPackageReference("k8s.io/apimachinery/pkg/runtime/schema")
	MetaV1Reference              = MakeExternalPackageReference("k8s.io/apimachinery/pkg/apis/meta/v1")
	CoreV1Reference              = MakeExternalPackageReference("k8s.io/api/core/v1")
	LogrReference                = MakeExternalPackageReference("github.com/go-logr/logr")

	ClientGoSchemeReference     = MakeExternalPackageReference("k8s.io/client-go/kubernetes/scheme")
	ControllerRuntimeAdmission  = MakeExternalPackageReference("sigs.k8s.io/controller-runtime/pkg/webhook/admission")
	ControllerRuntimeConversion = MakeExternalPackageReference("sigs.k8s.io/controller-runtime/pkg/conversion")
	ControllerSchemeReference   = MakeExternalPackageReference("sigs.k8s.io/controller-runtime/pkg/scheme")
	ControllerRuntimeClient     = MakeExternalPackageReference("sigs.k8s.io/controller-runtime/pkg/client")
	GitHubErrorsReference       = MakeExternalPackageReference("github.com/pkg/errors")

	// References to libraries used for testing
	CmpReference        = MakeExternalPackageReference("github.com/google/go-cmp/cmp")
	CmpOptsReference    = MakeExternalPackageReference("github.com/google/go-cmp/cmp/cmpopts")
	DiffReference       = MakeExternalPackageReference("github.com/kylelemons/godebug/diff")
	GopterReference     = MakeExternalPackageReference("github.com/leanovate/gopter")
	GopterGenReference  = MakeExternalPackageReference("github.com/leanovate/gopter/gen")
	GopterPropReference = MakeExternalPackageReference("github.com/leanovate/gopter/prop")
	GomegaReference     = MakeExternalPackageReference("github.com/onsi/gomega")
	PrettyReference     = MakeExternalPackageReference("github.com/kr/pretty")

	// Imports with specified names
	GomegaImport = NewPackageImport(GomegaReference).WithName(".")

	// Type names - GenRuntime
	KubernetesResourceType           = MakeExternalTypeName(GenRuntimeReference, "KubernetesResource")
	KuberentesConfigExporterType     = MakeExternalTypeName(GenRuntimeReference, "KubernetesConfigExporter")
	TenantResourceType               = MakeExternalTypeName(GenRuntimeReference, "TenantResource")
	ConvertibleSpecInterfaceType     = MakeExternalTypeName(GenRuntimeReference, "ConvertibleSpec")
	ConvertibleStatusInterfaceType   = MakeExternalTypeName(GenRuntimeReference, "ConvertibleStatus")
	ResourceReferenceType            = MakeExternalTypeName(GenRuntimeReference, "ResourceReference")
	ArbitraryOwnerReference          = MakeExternalTypeName(GenRuntimeReference, "ArbitraryOwnerReference")
	KnownResourceReferenceType       = MakeExternalTypeName(GenRuntimeReference, "KnownResourceReference")
	PropertyBagType                  = MakeExternalTypeName(GenRuntimeReference, "PropertyBag")
	ToARMConverterInterfaceType      = MakeExternalTypeName(GenRuntimeReference, "ToARMConverter")
	ARMResourceSpecType              = MakeExternalTypeName(GenRuntimeReference, "ARMResourceSpec")
	ARMResourceStatusType            = MakeExternalTypeName(GenRuntimeReference, "ARMResourceStatus")
	ResourceScopeType                = MakeExternalTypeName(GenRuntimeReference, "ResourceScope")
	ConvertToARMResolvedDetailsType  = MakeExternalTypeName(GenRuntimeReference, "ConvertToARMResolvedDetails")
	SecretReferenceType              = MakeExternalTypeName(GenRuntimeReference, "SecretReference")
	SecretMapReferenceType           = MakeExternalTypeName(GenRuntimeReference, "SecretMapReference")
	ResourceExtensionType            = MakeExternalTypeName(GenRuntimeReference, "ResourceExtension")
	SecretDestinationType            = MakeExternalTypeName(GenRuntimeReference, "SecretDestination")
	ConfigMapDestinationType         = MakeExternalTypeName(GenRuntimeReference, "ConfigMapDestination")
	ConfigMapReferenceType           = MakeExternalTypeName(GenRuntimeReference, "ConfigMapReference")
	GenRuntimeDefaulterInterfaceName = MakeExternalTypeName(GenRuntimeReference, "Defaulter")
	GenRuntimeValidatorInterfaceName = MakeExternalTypeName(GenRuntimeReference, "Validator")
	GenRuntimeMetaObjectType         = MakeExternalTypeName(GenRuntimeReference, "MetaObject")
	LocatableResourceInterfaceName   = MakeExternalTypeName(GenRuntimeReference, "LocatableResource")
	ImportableResourceType           = MakeExternalTypeName(GenRuntimeReference, "ImportableResource")
	ResourceOperationType            = MakeExternalTypeName(GenRuntimeReference, "ResourceOperation")
	ResourceOperationTypeArray       = NewArrayType(ResourceOperationType)

	// Optional types - GenRuntime
	OptionalConfigMapReferenceType     = NewOptionalType(ConfigMapReferenceType)
	OptionalKnownResourceReferenceType = NewOptionalType(KnownResourceReferenceType)
	OptionalResourceReferenceType      = NewOptionalType(ResourceReferenceType)
	OptionalSecretReferenceType        = NewOptionalType(SecretReferenceType)
	OptionalSecretMapReferenceType     = NewOptionalType(SecretMapReferenceType)

	// Predeclared maps
	MapOfStringStringType = NewMapType(StringType, StringType)

	// Type names - Generic ARM client
	GenericClientType = MakeExternalTypeName(GenericARMClientReference, "GenericClient")

	// Type names - Registration
	StorageTypeRegistrationType = MakeExternalTypeName(GenRuntimeRegistrationReference, "StorageType")
	IndexRegistrationType       = MakeExternalTypeName(GenRuntimeRegistrationReference, "Index")
	WatchRegistrationType       = MakeExternalTypeName(GenRuntimeRegistrationReference, "Watch")

	ConditionType   = MakeExternalTypeName(GenRuntimeConditionsReference, "Condition")
	ConditionsType  = MakeExternalTypeName(GenRuntimeConditionsReference, "Conditions")
	ConditionerType = MakeExternalTypeName(GenRuntimeConditionsReference, "Conditioner")

	// Type names - API Machinery
	GroupVersionKindType = MakeExternalTypeName(APIMachinerySchemaReference, "GroupVersionKind")
	SchemeType           = MakeExternalTypeName(APIMachineryRuntimeReference, "Scheme")
	JSONType             = MakeExternalTypeName(APIExtensionsReference, "JSON")
	ObjectMetaType       = MakeExternalTypeName(MetaV1Reference, "ObjectMeta")

	// Type names - Controller Runtime
	ConvertibleInterface        = MakeExternalTypeName(ControllerRuntimeConversion, "Convertible")
	HubInterface                = MakeExternalTypeName(ControllerRuntimeConversion, "Hub")
	ControllerRuntimeObjectType = MakeExternalTypeName(ControllerRuntimeClient, "Object")
	DefaulterInterfaceName      = MakeExternalTypeName(ControllerRuntimeAdmission, "Defaulter")
	ValidatorInterfaceName      = MakeExternalTypeName(ControllerRuntimeAdmission, "Validator")

	// Type names - Core types
	SecretType    = MakeExternalTypeName(CoreV1Reference, "Secret")
	ConfigMapType = MakeExternalTypeName(CoreV1Reference, "ConfigMap")

	// Type names - stdlib types
	ContextType = MakeExternalTypeName(ContextReference, "Context")

	// Type names - Logr types
	LogrType = MakeExternalTypeName(LogrReference, "Logger")
)
View Source
var ARMIDType = &PrimitiveType{"armid", "\"\""}

ARMIDType represents the Go string type for an ARM ID

View Source
var AnyType = &PrimitiveType{"interface{}", "nil"}

AnyType represents the root Go interface type, permitting any object

View Source
var BoolType = &PrimitiveType{"bool", "false"}

BoolType represents the Go bool type

View Source
var CodeGenerationComments []string = []string{

	"// Code generated by azure-service-operator-codegen. DO NOT EDIT.",
}
View Source
var ContinueMerge error = errors.New("special error that indicates that the merger was not applicable")
View Source
var EmptyInterfaceType = NewInterfaceType()
View Source
var EmptyObjectType = NewObjectType()

EmptyObjectType is an empty object

View Source
var EmptyPropertyReference = PropertyReference{}

EmptyPropertyReference is a convenience constant for when we have no value

View Source
var ErrorType = &PrimitiveType{"error", "nil"}

ErrorType represents the standard Go error interface

View Source
var FloatType = &PrimitiveType{"float64", "0"}

FloatType represents the Go float64 type

View Source
var IntType = &PrimitiveType{"int", "0"}

IntType represents a Go integer type

View Source
var StringType = &PrimitiveType{"string", "\"\""}

StringType represents the Go string type

View Source
var UInt32Type = &PrimitiveType{"uint32", "0"}

UInt32Type represents a Go uint32 type

View Source
var UInt64Type = &PrimitiveType{"uint64", "0"}

UInt64Type represents a Go uint64 type

Functions

func AddValidationComments

func AddValidationComments(commentList *dst.Decorations, validations []KubeBuilderValidation)

func AsSimpleDeclarations

func AsSimpleDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
	theType Type,
) ([]dst.Decl, error)

AsSimpleDeclarations is a helper for types that only require a simple name/alias to be defined

func AssignFromAliasOfCollection

func AssignFromAliasOfCollection(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

AssignFromAliasOfCollection assigns an array of values from an alias of that same type. This function generates code that looks like this:

<destination> <assignmentHandler> <destinationType>(<source>)

func AssignFromAliasOfPrimitive

func AssignFromAliasOfPrimitive(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

AssignFromAliasOfPrimitive assigns a primitive value from an alias of that same type. This function generates code that looks like this:

<destination> <assignmentHandler> <destinationType>(<source>)

func AssignFromEnum

func AssignFromEnum(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

AssignFromEnum reads a value from an enum type. This function generates code that looks like this: <destination> = <primitiveType>(<source>)

func AssignFromOptional

func AssignFromOptional(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

AssignFromOptional assigns address of source to destination. This function generates code that looks like this, for simple conversions:

if (<source> != nil) {
    <destination> <assignmentHandler> *<source>
}

or:

if (<source> != nil) {
    <destination>Temp := convert(*<source>)
    <destination> <assignmentHandler> <destination>Temp
}

func AssignToAliasOfCollection

func AssignToAliasOfCollection(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

AssignToAliasOfCollection assigns an array of values to an alias of that same type. This function generates code that looks like this:

<destination> <assignmentHandler> <destinationType>(<source>)

func AssignToAliasOfPrimitive

func AssignToAliasOfPrimitive(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

AssignToAliasOfPrimitive assigns a primitive value to an alias of that same type. This function generates code that looks like this:

<destination> <assignmentHandler> <destinationType>(<source>)

func AssignToEnum

func AssignToEnum(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

AssignToEnum stores a value into an enum type. This function generates code that looks like this: <destination> = <enumType>(<source>)

func AssignToOptional

func AssignToOptional(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

AssignToOptional assigns address of source to destination. This function generates code that looks like this, for simple conversions: <destination> <assignmentHandler> &<source>

or: <destination>Temp := convert(<source>) <destination> <assignmentHandler> &<destination>Temp

func AssignmentHandlerAssign

func AssignmentHandlerAssign(lhs dst.Expr, rhs dst.Expr) dst.Stmt

AssignmentHandlerAssign is an assignment handler for standard assignments to existing variables, using =

func AssignmentHandlerDefine

func AssignmentHandlerDefine(lhs dst.Expr, rhs dst.Expr) dst.Stmt

AssignmentHandlerDefine is an assignment handler for definitions, using :=

func ComparePathAndVersion

func ComparePathAndVersion(left string, right string) int

ComparePathAndVersion compares two paths containing versions and returns true if left should go before right

func ContainsPreviewVersionLabel

func ContainsPreviewVersionLabel(identifier string) bool

ContainsPreviewVersionLabel checks the passed identifier to see if it contains one of our special set, and if so returns true. If the passed identifier does not contain one, returns false.

func DebugDescription

func DebugDescription(t Type, pkgs ...InternalPackageReference) string

func DetermineDiscriminantAndValues

func DetermineDiscriminantAndValues(
	oneOf *ObjectType,
	definitions TypeDefinitionSet,
) (string, map[string]PropertyNameAndType, error)

func DiffTypes

func DiffTypes(x, y interface{}) string

func FileNameHint

func FileNameHint(name TypeName) string

FileNameHint returns what a file that contains this name (if any) should be called this is not always used as we often combine multiple definitions into one file

func GenerateKubebuilderComment

func GenerateKubebuilderComment(validation KubeBuilderValidation) string

GenerateKubebuilderComment converts the given validation to a Kubebuilder magic comment

func GetEnumValueId

func GetEnumValueId(name string, value EnumValue) string

func IdentityAssignPrimitiveType

func IdentityAssignPrimitiveType(
	_ *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

IdentityAssignPrimitiveType just assigns source to destination directly, no conversion needed. This function generates code that looks like this: <destination> <assignmentHandler> <source>

func IdentityAssignTypeName

func IdentityAssignTypeName(
	_ *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

IdentityAssignTypeName handles conversion for TypeName's that are the same Note that because this handler is dealing with TypeName's and not Optional<TypeName>, it is safe to perform a simple assignment rather than a copy. This function generates code that looks like this:

<destination> <assignmentHandler> <source>

func IdentityAssignValidatedTypeDestination

func IdentityAssignValidatedTypeDestination(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

IdentityAssignValidatedTypeDestination generates an assignment to the underlying validated type Element

func IdentityAssignValidatedTypeSource

func IdentityAssignValidatedTypeSource(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

IdentityAssignValidatedTypeSource generates an assignment to the underlying validated type Element

func IdentityConvertComplexArrayProperty

func IdentityConvertComplexArrayProperty(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

IdentityConvertComplexArrayProperty handles conversion for array properties with complex elements This function generates code that looks like this:

for _, item := range <source> {
	<code for producing result from destinationType.Element()>
	<destination> = append(<destination>, <result>)
}

func IdentityConvertComplexMapProperty

func IdentityConvertComplexMapProperty(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

IdentityConvertComplexMapProperty handles conversion for map properties with complex values. This function panics if the map keys are not primitive types. This function generates code that looks like this:

if <source> != nil {
	<destination> = make(map[<destinationType.KeyType()]<destinationType.ValueType()>, len(<source>))
	for key, value := range <source> {
		<code for producing result from destinationType.ValueType()>
		<destination>[key] = <result>
	}
}

func IdentityConvertComplexOptionalProperty

func IdentityConvertComplexOptionalProperty(
	builder *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

IdentityConvertComplexOptionalProperty handles conversion for optional properties with complex elements This function generates code that looks like this:

if <source> != nil {
	<code for producing result from destinationType.Element()>
	<destination> = &<result>
}

func IdentityDeepCopyJSON

func IdentityDeepCopyJSON(
	_ *ConversionFunctionBuilder,
	params ConversionParameters,
) ([]dst.Stmt, error)

IdentityDeepCopyJSON special cases copying JSON-type fields to call the DeepCopy method. It generates code that looks like:

<destination> = *<source>.DeepCopy()

func IdentityMakeContext

func IdentityMakeContext[C any](_ InternalTypeName, ctx C) (C, error)

IdentityMakeContext returns the context unmodified

func IdentityShouldRemoveCycle

func IdentityShouldRemoveCycle[C any](_ TypeDefinition, _ C) (bool, error)

IdentityShouldRemoveCycle is the default cycle removal behavior. It preserves all cycles unmodified.

func IsARMPackageReference

func IsARMPackageReference(reference PackageReference) bool

IsARMPackageReference returns true if the reference is to an ARM package OR to a subpackage of an ARM package, false otherwise.

func IsCompatPackageReference

func IsCompatPackageReference(reference PackageReference) bool

IsCompatPackageReference returns true if the reference is to a compat package

func IsExternalPackageReference

func IsExternalPackageReference(ref PackageReference) bool

IsExternalPackageReference returns true if the provided reference is external

func IsKubernetesResourceProperty

func IsKubernetesResourceProperty(name PropertyName) bool

IsKubernetesResourceProperty returns true if the supplied property name is one of the properties required by the KubernetesResource interface.

func IsLocalPackageReference

func IsLocalPackageReference(ref PackageReference) bool

IsLocalPackageReference returns true if the supplied reference is a local one

func IsObjectDefinition

func IsObjectDefinition(definition TypeDefinition) bool

IsObjectDefinition returns true if the passed definition is for an ARM type; false otherwise.

func IsResourceDefinition

func IsResourceDefinition(def TypeDefinition) bool

func IsResourceType

func IsResourceType(t Type) bool

func IsStoragePackageReference

func IsStoragePackageReference(reference PackageReference) bool

IsStoragePackageReference returns true if the reference is to a storage package OR to a subpackage for storage

func IsTypeResourceReference

func IsTypeResourceReference(t Type) bool

func IsTypeResourceReferenceMap

func IsTypeResourceReferenceMap(t Type) bool

func IsTypeResourceReferenceSlice

func IsTypeResourceReferenceSlice(t Type) bool

func IsTypeSecretReference

func IsTypeSecretReference(t Type) bool

func IsTypeSecretReferenceMap

func IsTypeSecretReferenceMap(t Type) bool

func IsTypeSecretReferenceSlice

func IsTypeSecretReferenceSlice(t Type) bool

func MakeIdentityVisitOfObjectType

func MakeIdentityVisitOfObjectType[C any](
	makeCtx MakePerPropertyContext[C],
) func(this *TypeVisitor[C], it *ObjectType, ctx C) (Type, error)

MakeIdentityVisitOfObjectType creates a visitor function which creates a per-property context before visiting each property of the ObjectType

func SortPackageReferencesByPathAndVersion

func SortPackageReferencesByPathAndVersion(packages []PackageReference)

func TypeEquals

func TypeEquals(left, right Type, overrides ...EqualityOverrides) bool

TypeEquals decides if the types are the same and handles the `nil` case overrides can be passed to customize the equality check.

Types

type AllOfType

type AllOfType struct {
	// contains filtered or unexported fields
}

AllOfType represents something that is the union of all the given types

func AsAllOfType

func AsAllOfType(t Type) (*AllOfType, bool)

AsAllOfType unwraps any wrappers around the provided type and returns either the underlying AllOfType and true, or nil and false.

func NewAllOfType

func NewAllOfType(types ...Type) *AllOfType

func (*AllOfType) AsDeclarations

func (allOf *AllOfType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

AsDeclarations always panics; AllOf cannot be represented by the Go AST and must be lowered to an object type

func (*AllOfType) AsTypeExpr

func (allOf *AllOfType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType always panics; AllOf cannot be represented by the Go AST and must be lowered to an object type

func (*AllOfType) AsZero

AsZero always panics; AllOf cannot be represented by the Go AST and must be lowered to an object type

func (*AllOfType) Equals

func (allOf *AllOfType) Equals(t Type, overrides EqualityOverrides) bool

Equals returns true if the other Type is a AllOf that contains the same set of types

func (*AllOfType) References

func (allOf *AllOfType) References() TypeNameSet

References returns any type referenced by the AllOf types

func (*AllOfType) RequiredPackageReferences

func (allOf *AllOfType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences always panics; AllOf cannot be represented by the Go AST and must be lowered to an object type

func (*AllOfType) String

func (allOf *AllOfType) String() string

String implements fmt.Stringer

func (*AllOfType) Types

func (allOf *AllOfType) Types() ReadonlyTypeSet

Types returns what types the AllOf can be. Exposed as ReadonlyTypeSet so caller can't break invariants.

func (*AllOfType) WriteDebugDescription

func (allOf *AllOfType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current AnyOf type to the passed builder. builder receives the full description, including nested types. definitions is a dictionary for resolving named types.

type ArrayType

type ArrayType struct {
	// contains filtered or unexported fields
}

ArrayType is used for properties that contain an array of values

func AsArrayType

func AsArrayType(aType Type) (*ArrayType, bool)

AsArrayType unwraps any wrappers around the provided type and returns either the underlying ArrayType and true, or nil and false.

func NewArrayType

func NewArrayType(element Type) *ArrayType

NewArrayType creates a new array with elements of the specified type

func (*ArrayType) AsDeclarations

func (array *ArrayType) AsDeclarations(codeGenerationContext *CodeGenerationContext, declContext DeclarationContext) ([]dst.Decl, error)

func (*ArrayType) AsTypeExpr

func (array *ArrayType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType renders the Go abstract syntax tree for an array type

func (*ArrayType) AsZero

func (array *ArrayType) AsZero(_ TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

AsZero renders an expression for the "zero" value of the array by calling make()

func (*ArrayType) Element

func (array *ArrayType) Element() Type

Element returns the element type of the array

func (*ArrayType) Equals

func (array *ArrayType) Equals(t Type, overrides EqualityOverrides) bool

Equals returns true if the passed type is an array type with the same kind of elements, false otherwise

func (*ArrayType) References

func (array *ArrayType) References() TypeNameSet

References returns the references of the type this array contains.

func (*ArrayType) RequiredPackageReferences

func (array *ArrayType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns a list of packages required by this

func (*ArrayType) String

func (array *ArrayType) String() string

String implements fmt.Stringer

func (*ArrayType) WithElement

func (array *ArrayType) WithElement(t Type) *ArrayType

WithElement returns an ArrayType with the specified element. the benefit of this is it allows reusing the same value if the element type is the same

func (*ArrayType) WriteDebugDescription

func (array *ArrayType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current array type to the passed builder builder receives the full description, including nested types definitions is a dictionary for resolving named types

type ArrayValidations

type ArrayValidations struct {
	MaxItems *int64
	MinItems *int64
}

func (ArrayValidations) Equals

func (av ArrayValidations) Equals(other Validations) bool

func (ArrayValidations) ToKubeBuilderValidations

func (av ArrayValidations) ToKubeBuilderValidations() []KubeBuilderValidation

type CodeGenerationContext

type CodeGenerationContext struct {
	// contains filtered or unexported fields
}

CodeGenerationContext stores context about the location code-generation is occurring. This is required because some things (such as specific field types) are impacted by the context in which the field declaration occurs - for example in a file with two conflicting package references a disambiguation must occur and field types must ensure they correctly refer to the disambiguated types

func NewCodeGenerationContext

func NewCodeGenerationContext(
	currentPackage InternalPackageReference,
	packageImports *PackageImportSet,
	generatedPackages map[InternalPackageReference]*PackageDefinition,
) *CodeGenerationContext

NewCodeGenerationContext creates a new immutable code generation context

func (*CodeGenerationContext) CurrentPackage

func (ctx *CodeGenerationContext) CurrentPackage() InternalPackageReference

CurrentPackage returns the current package being generated

func (*CodeGenerationContext) GetAllReachableDefinitions

func (ctx *CodeGenerationContext) GetAllReachableDefinitions() TypeDefinitionSet

GetAllReachableDefinitions returns the actual definitions from a specific package

func (*CodeGenerationContext) GetDefinition

func (ctx *CodeGenerationContext) GetDefinition(name InternalTypeName) (TypeDefinition, error)

GetDefinition looks up a particular type definition in a package available in this context

func (*CodeGenerationContext) GetDefinitionsInCurrentPackage

func (ctx *CodeGenerationContext) GetDefinitionsInCurrentPackage() TypeDefinitionSet

GetDefinitionsInCurrentPackage returns the actual definitions from a specific package

func (*CodeGenerationContext) GetDefinitionsInPackage

func (ctx *CodeGenerationContext) GetDefinitionsInPackage(packageRef InternalPackageReference) (TypeDefinitionSet, bool)

GetDefinitionsInPackage returns the actual definitions from a specific package

func (*CodeGenerationContext) GetGeneratedPackage

func (ctx *CodeGenerationContext) GetGeneratedPackage(reference InternalPackageReference) (*PackageDefinition, error)

GetGeneratedPackage gets a reference to the PackageDefinition referred to by the provided reference

func (*CodeGenerationContext) GetImportedPackageName

func (ctx *CodeGenerationContext) GetImportedPackageName(reference PackageReference) (string, error)

GetImportedPackageName gets the imported packages name or an error if the package was not imported

func (*CodeGenerationContext) MustGetDefinition

func (ctx *CodeGenerationContext) MustGetDefinition(name InternalTypeName) TypeDefinition

MustGetDefinition looks up a particular type definition in a package available in this context. If it cannot be found, MustGetDefinition panics.

func (*CodeGenerationContext) MustGetImportedPackageName

func (ctx *CodeGenerationContext) MustGetImportedPackageName(reference PackageReference) string

MustGetImportedPackageName gets the imported packages name or panics if the package was not imported Use this when you're absolutely positively sure the package will be there already

func (*CodeGenerationContext) PackageImports

func (ctx *CodeGenerationContext) PackageImports() *PackageImportSet

PackageImports returns the set of package imports in the current context

func (*CodeGenerationContext) UsedPackageImports

func (ctx *CodeGenerationContext) UsedPackageImports() *PackageImportSet

UsedPackageImports returns the set of package imports that have been used by the generated code

type ConversionFunctionBuilder

type ConversionFunctionBuilder struct {
	IDFactory             IdentifierFactory
	CodeGenerationContext *CodeGenerationContext

	// SupportExplicitEmptyCollectionsSerializationMode signals that collections can be initialized to a size 0 collection, rather than an empty collection
	SupportExplicitEmptyCollectionsSerializationMode bool
	// contains filtered or unexported fields
}

ConversionFunctionBuilder is used to build a function converting between two similar types. It has a set of built-in conversions and can be configured with additional conversions.

func NewConversionFunctionBuilder

func NewConversionFunctionBuilder(
	idFactory IdentifierFactory,
	codeGenerationContext *CodeGenerationContext,
) *ConversionFunctionBuilder

NewConversionFunctionBuilder creates a new ConversionFunctionBuilder with the default conversions already added.

func (*ConversionFunctionBuilder) AddConversionHandlers

func (builder *ConversionFunctionBuilder) AddConversionHandlers(conversionHandlers ...ConversionHandler)

AddConversionHandlers adds the specified conversion handlers to the end of the conversion list.

func (*ConversionFunctionBuilder) BuildConversion

func (builder *ConversionFunctionBuilder) BuildConversion(params ConversionParameters) ([]dst.Stmt, error)

BuildConversion creates a conversion between the source and destination defined by params.

func (*ConversionFunctionBuilder) CreateLocal

func (builder *ConversionFunctionBuilder) CreateLocal(locals *KnownLocalsSet, suffix string, nameHint string) string

CreateLocal creates an unused local variable name. Names are chosen according to the following rules:

  1. If there is no local variable with the <suffix> name, use that.
  2. If there is a local variable with the <suffix> name, create a variable name <nameHint><suffix>.

In the case that <nameHint><suffix> is also taken append numbers to the end in standard KnownLocalsSet fashion. Note that this function trims numbers on the right hand side of nameHint, so a nameHint of "item1" will get a local variable named item<suffix>.

func (*ConversionFunctionBuilder) PrependConversionHandlers

func (builder *ConversionFunctionBuilder) PrependConversionHandlers(conversionHandlers ...ConversionHandler)

PrependConversionHandlers adds the specified conversion handlers to the beginning of the conversion list.

func (*ConversionFunctionBuilder) ShouldInitializeCollectionToEmpty

func (builder *ConversionFunctionBuilder) ShouldInitializeCollectionToEmpty(prop *PropertyDefinition) bool

func (*ConversionFunctionBuilder) WithSupportExplicitEmptyCollectionsSerializationMode

func (builder *ConversionFunctionBuilder) WithSupportExplicitEmptyCollectionsSerializationMode() *ConversionFunctionBuilder

type ConversionHandler

type ConversionHandler func(builder *ConversionFunctionBuilder, params ConversionParameters) ([]dst.Stmt, error)

type ConversionParameters

type ConversionParameters struct {
	Source            dst.Expr
	Destination       dst.Expr
	SourceType        Type
	DestinationType   Type
	NameHint          string
	ConversionContext []Type
	AssignmentHandler func(destination, source dst.Expr) dst.Stmt
	Locals            *KnownLocalsSet

	// SourceProperty is the source property for this conversion. Note that for recursive conversions this still refers
	// to the source property that the conversion chain will ultimately be sourced from
	SourceProperty *PropertyDefinition
	// DestinationProperty is the destination property for this conversion. Note that for recursive conversions this still refers
	// to the destination property that the conversion chain will ultimately be assigned to
	DestinationProperty *PropertyDefinition
}

ConversionParameters are parameters for converting between a source type and a destination type.

func (ConversionParameters) AssignmentHandlerOrDefault

func (params ConversionParameters) AssignmentHandlerOrDefault() func(destination, source dst.Expr) dst.Stmt

AssignmentHandlerOrDefault returns the AssignmentHandler or a default assignment handler if AssignmentHandler was nil.

func (ConversionParameters) CountArraysAndMapsInConversionContext

func (params ConversionParameters) CountArraysAndMapsInConversionContext() int

CountArraysAndMapsInConversionContext returns the number of arrays/maps which are in the conversion context. This is to aid in situations where there are deeply nested conversions (i.e. array of map of maps). In these contexts, temporary variables need to be declared to store intermediate conversion results.

func (ConversionParameters) GetDestination

func (params ConversionParameters) GetDestination() dst.Expr

GetDestination gets the Destination field.

func (ConversionParameters) GetSource

func (params ConversionParameters) GetSource() dst.Expr

GetSource gets the Source field.

func (ConversionParameters) WithAssignmentHandler

func (params ConversionParameters) WithAssignmentHandler(
	assignmentHandler func(result dst.Expr, destination dst.Expr) dst.Stmt,
) ConversionParameters

WithAssignmentHandler returns a new ConversionParameters with the updated AssignmentHandler.

func (ConversionParameters) WithDestination

func (params ConversionParameters) WithDestination(destination dst.Expr) ConversionParameters

WithDestination returns a new ConversionParameters with the updated Destination.

func (ConversionParameters) WithDestinationType

func (params ConversionParameters) WithDestinationType(t Type) ConversionParameters

WithDestinationType returns a new ConversionParameters with the updated DestinationType.

func (ConversionParameters) WithSource

func (params ConversionParameters) WithSource(source dst.Expr) ConversionParameters

WithSource returns a new ConversionParameters with the updated Source.

func (ConversionParameters) WithSourceType

func (params ConversionParameters) WithSourceType(t Type) ConversionParameters

WithSourceType returns a new ConversionParameters with the updated SourceType.

type DeclarationContext

type DeclarationContext struct {
	Name        InternalTypeName
	Description []string
	Validations []KubeBuilderValidation
}

DeclarationContext represents some metadata about a specific declaration

type DerivedPackageReference

type DerivedPackageReference interface {
	Base() InternalPackageReference
}

DerivedPackageReference should be implemented by any package reference that's derived from another

type EnumType

type EnumType struct {
	// contains filtered or unexported fields
}

EnumType represents a set of mutually exclusive predefined options

func AsEnumType

func AsEnumType(aType Type) (*EnumType, bool)

AsEnumType unwraps any wrappers around the provided type and returns either the underlying EnumType and true, or nil and false.

func NewEnumType

func NewEnumType(baseType *PrimitiveType, options ...EnumValue) *EnumType

NewEnumType defines a new enumeration including the legal values

func (*EnumType) AsDeclarations

func (enum *EnumType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

AsDeclarations converts the EnumType to a series of Go AST Decls

func (*EnumType) AsTypeExpr

func (enum *EnumType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType implements Type for EnumType

func (*EnumType) AsZero

func (enum *EnumType) AsZero(definitions TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

AsZero renders an expression for the "zero" value of the type, based on the underlying type of the enumeration

func (*EnumType) BaseType

func (enum *EnumType) BaseType() *PrimitiveType

BaseType returns the base type of the enum

func (*EnumType) CreateValidation

func (enum *EnumType) CreateValidation() KubeBuilderValidation

CreateValidation creates the validation annotation for this Enum

func (*EnumType) Equals

func (enum *EnumType) Equals(t Type, overrides EqualityOverrides) bool

Equals will return true if the supplied type has the same base type and options

func (*EnumType) MapperVariableName

func (enum *EnumType) MapperVariableName(name InternalTypeName) string

MapperVariableName returns the name of the variable used to map enum values to strings. We check the values of the enum to ensure we don't have a name collision.

func (*EnumType) NeedsMappingConversion

func (enum *EnumType) NeedsMappingConversion(name InternalTypeName) bool

NeedsMappingConversion returns true if the enum needs a mapping conversion. A mapping conversion is needed if the base type is a string and the enum is *not* APIVersion (that enum isn't actually used on Spec or Status types).

func (*EnumType) Options

func (enum *EnumType) Options() []EnumValue

Options returns all the enum options A copy of the slice is returned to preserve immutability

func (*EnumType) References

func (enum *EnumType) References() TypeNameSet

References returns any types the underlying type refers to.

func (*EnumType) RequiredPackageReferences

func (enum *EnumType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences indicates that Enums never need additional imports

func (*EnumType) String

func (enum *EnumType) String() string

String implements fmt.Stringer

func (*EnumType) WithValidation

func (enum *EnumType) WithValidation() *EnumType

WithValidation returns a copy of this enum, with associated Kubebuilder annotations.

func (*EnumType) WithoutValidation

func (enum *EnumType) WithoutValidation() *EnumType

WithoutValidation returns a copy of this enum, without associated Kubebuilder annotations.

func (*EnumType) WriteDebugDescription

func (enum *EnumType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current enum type, including option names, to the passed builder. builder receives the full description. currentPackage is the package that the enum is being written into.

type EnumValue

type EnumValue struct {
	// Identifier is a Go identifier for the value
	Identifier string
	// Value is the actual value expected by ARM
	Value string
}

EnumValue captures a single value of the enumeration

func MakeEnumValue

func MakeEnumValue(id string, value string) EnumValue

MakeEnumValue makes a new EnumValue with the given identifier and value

func (*EnumValue) Equals

func (value *EnumValue) Equals(v *EnumValue) bool

Equals tests to see if the passed EnumValue has the same name and value

func (*EnumValue) String

func (value *EnumValue) String() string

String implements fmt.Stringer for debugging purposes

type EqualityOverrides

type EqualityOverrides struct {
	InternalTypeName func(left InternalTypeName, right InternalTypeName) bool
	ObjectType       func(left *ObjectType, right *ObjectType) bool
}

type ErroredType

type ErroredType struct {
	// contains filtered or unexported fields
}

func AsErroredType

func AsErroredType(t Type) (*ErroredType, bool)

func NewErroredType

func NewErroredType(t Type, errors []string, warnings []string) *ErroredType

func (*ErroredType) AsDeclarations

func (e *ErroredType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

func (*ErroredType) AsTypeExpr

func (e *ErroredType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

func (*ErroredType) AsZero

func (e *ErroredType) AsZero(definitions TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

AsZero renders an expression for the "zero" value of the type by delegating to the inner type

func (*ErroredType) Equals

func (e *ErroredType) Equals(t Type, overrides EqualityOverrides) bool

func (*ErroredType) Errors

func (e *ErroredType) Errors() []string

Errors returns the errors stored in this ErroredType

func (*ErroredType) InnerType

func (e *ErroredType) InnerType() Type

func (*ErroredType) References

func (e *ErroredType) References() TypeNameSet

func (*ErroredType) RequiredPackageReferences

func (e *ErroredType) RequiredPackageReferences() *PackageReferenceSet

func (*ErroredType) String

func (e *ErroredType) String() string

func (*ErroredType) Unwrap

func (e *ErroredType) Unwrap() Type

Unwrap returns the type contained within the error type

func (*ErroredType) Warnings

func (e *ErroredType) Warnings() []string

Warnings returns the warnings stored in this ErroredType

func (*ErroredType) WithType

func (e *ErroredType) WithType(t Type) *ErroredType

func (*ErroredType) WriteDebugDescription

func (e *ErroredType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current errored type to the passed builder, builder receives the full description, including the nested type, errors and warnings definitions is for resolving named types

type ExternalPackageReference

type ExternalPackageReference struct {
	// contains filtered or unexported fields
}

ExternalPackageReference indicates a package to be imported from an external source, such as from GitHub or the go standard library.

func MakeExternalPackageReference

func MakeExternalPackageReference(packagePath string) ExternalPackageReference

MakeExternalPackageReference creates a new package reference from a path

func (ExternalPackageReference) Equals

Equals returns true if the passed package reference references the same package, false otherwise

func (ExternalPackageReference) GroupVersion

func (pr ExternalPackageReference) GroupVersion() (string, string)

GroupVersion triggers a panic because external references don't have a group or version

func (ExternalPackageReference) ImportAlias

func (pr ExternalPackageReference) ImportAlias(style PackageImportStyle) string

ImportAlias returns the import alias to use for this package reference

func (ExternalPackageReference) ImportPath

func (pr ExternalPackageReference) ImportPath() string

ImportPath returns the path to use when importing this package

func (ExternalPackageReference) IsPreview

func (pr ExternalPackageReference) IsPreview() bool

IsPreview returns false because external references are never previews

func (ExternalPackageReference) PackageName

func (pr ExternalPackageReference) PackageName() string

PackageName returns the package name of this reference

func (ExternalPackageReference) String

func (pr ExternalPackageReference) String() string

String returns the string representation of the package reference

type ExternalTypeName

type ExternalTypeName struct {
	// contains filtered or unexported fields
}

ExternalTypeName is a name associated with a type that we don't own

func AsExternalTypeName

func AsExternalTypeName(aType Type) (ExternalTypeName, bool)

AsExternalTypeName unwraps any wrappers around the provided type and returns either the underlying TypeName and true, or a blank and false.

func MakeExternalTypeName

func MakeExternalTypeName(ref ExternalPackageReference, name string) ExternalTypeName

MakeExternalTypeName is a factory method for creating an ExternalTypeName

func (ExternalTypeName) AsDeclarations

func (tn ExternalTypeName) AsDeclarations(codeGenerationContext *CodeGenerationContext, declContext DeclarationContext) ([]dst.Decl, error)

func (ExternalTypeName) AsTypeExpr

func (tn ExternalTypeName) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType implements Type for TypeName

func (ExternalTypeName) AsZero

func (tn ExternalTypeName) AsZero(definitions TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

AsZero renders an expression for the "zero" value of the type. The exact thing we need to generate depends on the actual type we reference

func (ExternalTypeName) Equals

func (tn ExternalTypeName) Equals(t Type, _ EqualityOverrides) bool

Equals returns true if the passed type is the same TypeName, false otherwise

func (ExternalTypeName) Name

func (tn ExternalTypeName) Name() string

Name returns the package-local name of the type

func (ExternalTypeName) PackageReference

func (tn ExternalTypeName) PackageReference() PackageReference

PackageReference returns the package to which the type belongs

func (ExternalTypeName) References

func (tn ExternalTypeName) References() TypeNameSet

References returns a set containing this type name.

func (ExternalTypeName) RequiredPackageReferences

func (tn ExternalTypeName) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns all the imports required for this definition

func (ExternalTypeName) String

func (tn ExternalTypeName) String() string

String returns the string representation of the type name, and implements fmt.Stringer.

func (ExternalTypeName) WriteDebugDescription

func (tn ExternalTypeName) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder. builder receives the full description, including nested types. definitions is a dictionary for resolving named types.

type FileDefinition

type FileDefinition struct {
	// contains filtered or unexported fields
}

FileDefinition is the content of a file we're generating

func NewFileDefinition

func NewFileDefinition(
	packageRef InternalPackageReference,
	definitions []TypeDefinition,
	generatedPackages map[InternalPackageReference]*PackageDefinition,
) *FileDefinition

NewFileDefinition creates a file definition containing specified definitions. packageRef is the package to which this file belongs. definitions are the type definitions to include in this specific file. generatedPackages is a map of all other packages being generated (to allow for cross-package references).

func (*FileDefinition) AsAst

func (file *FileDefinition) AsAst() (result *dst.File, err error)

AsAst generates an AST node representing this file

type FlaggedType

type FlaggedType struct {
	// contains filtered or unexported fields
}

func NewFlaggedType

func NewFlaggedType(t Type, flags ...TypeFlag) *FlaggedType

NewFlaggedType applies flags to an existing type and returns a wrapper

func (*FlaggedType) AsDeclarations

func (ft *FlaggedType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

AsDeclarations renders as a Go abstract syntax tree for a declaration

func (*FlaggedType) AsTypeExpr

func (ft *FlaggedType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType renders as a Go abstract syntax tree for a type (yes this says ast.Expr but that is what the Go 'dst' package uses for types)

func (*FlaggedType) AsZero

func (ft *FlaggedType) AsZero(definitions TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

AsZero renders an expression for the "zero" value of the type by delegating to the wrapped type

func (*FlaggedType) Element

func (ft *FlaggedType) Element() Type

Element returns the underlying type that is flagged

func (*FlaggedType) Equals

func (ft *FlaggedType) Equals(t Type, overrides EqualityOverrides) bool

Equals returns true if the passed type is the same as this one, false otherwise

func (*FlaggedType) Flags

func (ft *FlaggedType) Flags() []TypeFlag

Flags returns all the flags present on this type

func (*FlaggedType) HasFlag

func (ft *FlaggedType) HasFlag(flag TypeFlag) bool

HasFlag tests to see if this flagged type has the specified flag

func (*FlaggedType) References

func (ft *FlaggedType) References() TypeNameSet

References returns the names of all types that this type references.

func (*FlaggedType) RequiredPackageReferences

func (ft *FlaggedType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns a set of packages imports required by this type

func (*FlaggedType) String

func (ft *FlaggedType) String() string

String returns the underlying flagged type plus the flags present For this to be useful, make sure all Types have a printable version for debugging/user info. This doesn't need to be a full representation of the type.

func (*FlaggedType) Unwrap

func (ft *FlaggedType) Unwrap() Type

Unwrap returns the type contained within the wrapper type

func (*FlaggedType) WithElement

func (ft *FlaggedType) WithElement(t Type) *FlaggedType

WithElement returns the flagged type with the same flags but a different element

func (*FlaggedType) WithFlag

func (ft *FlaggedType) WithFlag(flag TypeFlag) *FlaggedType

WithFlag returns a new FlaggedType with the specified flag added

func (*FlaggedType) WithoutFlag

func (ft *FlaggedType) WithoutFlag(flag TypeFlag) Type

WithoutFlag returns a new FlaggedType with the specified flag excluded If the flag is not present, the existing FlaggedType is returned unmodified If the last flag is removed, the underlying type is returned

func (*FlaggedType) WriteDebugDescription

func (ft *FlaggedType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder builder receives the full description, including nested types. definitions is a dictionary for resolving named types.

type Function

type Function interface {
	// Name is the unique name of this function
	// (You can't have two functions with the same name on the same object or resource)
	Name() string

	// RequiredPackageReferences returns a set of packages imports required by this type.
	// The set should *not* include the package in which the type is defined.
	RequiredPackageReferences() *PackageReferenceSet

	// References returns the set of types to which this function refers.
	// SHOULD include any types which this function references but its receiver doesn't.
	// SHOULD NOT include the receiver of this function.
	References() TypeNameSet

	// AsFunc renders the current instance as a Go abstract syntax tree
	AsFunc(codeGenerationContext *CodeGenerationContext, receiver InternalTypeName) (*dst.FuncDecl, error)

	// Equals determines if this Function is equal to another one
	Equals(f Function, overrides EqualityOverrides) bool
}

Function represents something that is an (unnamed) Go function

type FunctionContainer

type FunctionContainer interface {
	// Functions returns all the function implementations
	// A sorted slice is returned to preserve immutability and provide determinism
	Functions() []Function

	// HasFunctionWithName determines if this resource has a function with the given name
	HasFunctionWithName(name string) bool
}

FunctionContainer is implemented by Types that contain functions Provides readonly access as we need to use a TypeVisitor for modifications to preserve type wrapping

func AsFunctionContainer

func AsFunctionContainer(theType Type) (FunctionContainer, bool)

AsFunctionContainer converts a type into a function container Only use this readonly access as we must use a TypeVisitor for modifications to preserve type wrapping

type FunctionInjector

type FunctionInjector struct {
	// contains filtered or unexported fields
}

FunctionInjector is a utility for injecting function definitions into resources and objects

func NewFunctionInjector

func NewFunctionInjector() *FunctionInjector

NewFunctionInjector creates a new function injector for modifying resources and objects

func (*FunctionInjector) Inject

func (fi *FunctionInjector) Inject(def TypeDefinition, fns ...Function) (TypeDefinition, error)

Inject modifies the passed type definition by injecting the passed function

type GoSourceFile

type GoSourceFile interface {
	// AsAst transforms the file into a dst.File (you can think of this as the AST representation of the file)
	AsAst() (*dst.File, error)
}

GoSourceFile represents a file of Go code

type GoSourceFileWriter

type GoSourceFileWriter struct {
	// contains filtered or unexported fields
}

func NewGoSourceFileWriter

func NewGoSourceFileWriter(file GoSourceFile) *GoSourceFileWriter

NewGoSourceFileWriter creates a new writer for writing the given file

func (*GoSourceFileWriter) SaveToFile

func (w *GoSourceFileWriter) SaveToFile(filePath string) error

SaveToFile writes the given FileAst to the specified file path

func (*GoSourceFileWriter) SaveToWriter

func (w *GoSourceFileWriter) SaveToWriter(destination io.Writer) error

SaveToWriter writes the given FileAst to the destination

type IdentifierFactory

type IdentifierFactory interface {
	CreateIdentifier(name string, visibility Visibility) string

	// CreateStringIdentifier creates an identifier for use in a string literal. This differs from CreateIdentifier in
	// that string literals do not need to worry about collision with Golang reserved words
	CreateStringIdentifier(name string, visibility Visibility) string

	CreatePropertyName(propertyName string, visibility Visibility) PropertyName
	CreateGroupName(name string) string
	// CreateEnumIdentifier generates the canonical name for an enumeration
	CreateEnumIdentifier(namehint string) string
	// CreateLocal creates a local variable name
	CreateLocal(name string) string
	// CreateReceiver creates a name for a method receiver
	CreateReceiver(name string) string
}

IdentifierFactory is a factory for creating Go identifiers from Json schema names

func NewIdentifierFactory

func NewIdentifierFactory() IdentifierFactory

NewIdentifierFactory creates an IdentifierFactory ready for use

type InterfaceImplementation

type InterfaceImplementation struct {
	// contains filtered or unexported fields
}

InterfaceImplementation specifies how a type will satisfy an interface implementation

func NewInterfaceImplementation

func NewInterfaceImplementation(name TypeName, functions ...Function) *InterfaceImplementation

NewInterfaceImplementation creates a new interface implementation with the given name and set of functions

func (*InterfaceImplementation) Equals

func (iface *InterfaceImplementation) Equals(other *InterfaceImplementation, overrides EqualityOverrides) bool

Equals determines if this interface is equal to another interface

func (*InterfaceImplementation) FunctionCount

func (iface *InterfaceImplementation) FunctionCount() int

FunctionCount returns the number of included functions

func (*InterfaceImplementation) Functions

func (iface *InterfaceImplementation) Functions() []Function

Functions returns all the function implementations A sorted slice is returned to preserve immutability and provide determinism

func (*InterfaceImplementation) HasFunctionWithName

func (iface *InterfaceImplementation) HasFunctionWithName(functionName string) bool

HasFunctionWithName determines if this interface has a function with the given name

func (*InterfaceImplementation) Name

func (iface *InterfaceImplementation) Name() TypeName

Name returns the name of the interface

func (*InterfaceImplementation) References

func (iface *InterfaceImplementation) References() TypeNameSet

References indicates whether this type includes any direct references to the given type

func (*InterfaceImplementation) RequiredPackageReferences

func (iface *InterfaceImplementation) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns a list of packages required by this

func (*InterfaceImplementation) WithAnnotation

func (iface *InterfaceImplementation) WithAnnotation(annotation string) *InterfaceImplementation

type InterfaceImplementationInjector

type InterfaceImplementationInjector struct {
	// contains filtered or unexported fields
}

InterfaceImplementationInjector is a utility for injecting interface implementations into resources and objects

func NewInterfaceImplementationInjector

func NewInterfaceImplementationInjector() *InterfaceImplementationInjector

NewInterfaceImplementationInjector creates a new interface implementation injector for modifying resources & objects

func (*InterfaceImplementationInjector) Inject

func (injector *InterfaceImplementationInjector) Inject(
	def TypeDefinition, implementations ...*InterfaceImplementation,
) (TypeDefinition, error)

Inject modifies the passed type definition by injecting the passed interface implementation

type InterfaceImplementer

type InterfaceImplementer struct {
	// contains filtered or unexported fields
}

InterfaceImplementer represents a container that may contain multiple interface implementations Both resources and objects are examples of interface implementers

func MakeInterfaceImplementer

func MakeInterfaceImplementer() InterfaceImplementer

MakeInterfaceImplementer returns an interface implementer

func (InterfaceImplementer) AsDeclarations

func (i InterfaceImplementer) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	typeName InternalTypeName,
	_ []string,
) ([]dst.Decl, error)

func (InterfaceImplementer) Equals

func (InterfaceImplementer) FindInterface

func (i InterfaceImplementer) FindInterface(name TypeName) (*InterfaceImplementation, bool)

FindInterface is used to find a particular interface implementation when given the type name of the interface being implemented.

func (InterfaceImplementer) References

func (i InterfaceImplementer) References() TypeNameSet

func (InterfaceImplementer) RequiredPackageReferences

func (i InterfaceImplementer) RequiredPackageReferences() *PackageReferenceSet

func (InterfaceImplementer) WithInterface

WithInterface creates a new InterfaceImplementer with the specified implementation included. Any existing implementation of the same interface will be replaced.

func (InterfaceImplementer) WithoutInterface

func (i InterfaceImplementer) WithoutInterface(name TypeName) InterfaceImplementer

WithoutInterface returns a new interface implementer that doesn't contain the specified interface

type InterfaceInjector

type InterfaceInjector struct {
	// contains filtered or unexported fields
}

InterfaceInjector is a utility for injecting interface implementations into resources and objects

func NewInterfaceInjector

func NewInterfaceInjector() *InterfaceInjector

NewInterfaceInjector creates a new interface injector for modifying resources and objects

func (*InterfaceInjector) Inject

Inject modifies the passed type definition by injecting the passed function

type InterfaceType

type InterfaceType struct {
	// contains filtered or unexported fields
}

InterfaceType represents an interface

func AsInterfaceType

func AsInterfaceType(t Type) (*InterfaceType, bool)

AsInterfaceType unwraps any wrappers around the provided type and returns either the underlying InterfaceType and true, or nil and false.

func NewInterfaceType

func NewInterfaceType(functions ...Function) *InterfaceType

NewInterfaceType creates a new InterfaceType

func (*InterfaceType) AsDeclarations

func (i *InterfaceType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

func (*InterfaceType) AsTypeExpr

func (i *InterfaceType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType renders the Go abstract syntax tree for the interface type

func (*InterfaceType) AsZero

AsZero always panics; Interface does not have a zero type

func (*InterfaceType) Equals

func (i *InterfaceType) Equals(t Type, overrides EqualityOverrides) bool

func (*InterfaceType) Functions

func (i *InterfaceType) Functions() []Function

Functions returns all the function definitions A sorted slice is returned to preserve immutability and provide determinism

func (*InterfaceType) References

func (i *InterfaceType) References() TypeNameSet

References returns any type referenced by this interface

func (*InterfaceType) RequiredPackageReferences

func (i *InterfaceType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns the set of package references which this interface requires

func (*InterfaceType) String

func (i *InterfaceType) String() string

String implements fmt.Stringer

func (*InterfaceType) WithFunction

func (i *InterfaceType) WithFunction(function Function) *InterfaceType

WithFunction creates a new InterfaceType with a function (method) attached to it

func (*InterfaceType) WriteDebugDescription

func (i *InterfaceType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current InterfaceType to the passed builder.

type InternalPackageReference

type InternalPackageReference interface {
	PackageReference

	// IsPreview returns true if this package reference has a suffix indicating it's a preview
	// release, false otherwise
	IsPreview() bool

	// Group returns the group to which this package belongs.
	Group() string

	// PackagePath returns the fully qualified package path
	PackagePath() string

	// FolderPath returns the relative path to this package on disk.
	FolderPath() string

	// LocalPathPrefix returns the prefix (everything up to the group name)
	LocalPathPrefix() string

	// GroupVersion returns the group and version of this reference
	GroupVersion() (string, string)

	// Version returns the version of this reference
	Version() string
}

InternalPackageReference describes a package reference that points to a local package (either a storage package or a standard one). It can be used to abstract across the exact package type (storage vs local)

func MakeStoragePackageReference

func MakeStoragePackageReference(ref InternalPackageReference) InternalPackageReference

MakeStoragePackageReference creates a new storage package reference from a local package reference

type InternalTypeName

type InternalTypeName struct {
	// contains filtered or unexported fields
}

InternalTypeName is a name associated with another Type (it also is usable as a Type)

func AsInternalTypeName

func AsInternalTypeName(aType Type) (InternalTypeName, bool)

AsInternalTypeName unwraps any wrappers around the provided type and returns either the underlying TypeName and true, or a blank and false.

func CreateARMTypeName

func CreateARMTypeName(name InternalTypeName) InternalTypeName

CreateARMTypeName creates an ARM object type name

func ExtractTypeName

func ExtractTypeName(aType Type) (InternalTypeName, bool)

ExtractTypeName extracts a TypeName from the specified type if possible. This includes unwrapping MetaType's like ValidatedType as well as checking the element type of types such as ArrayType and MapType.

func IsUserAssignedIdentityProperty

func IsUserAssignedIdentityProperty(prop *PropertyDefinition) (InternalTypeName, bool)

func MakeInternalTypeName

func MakeInternalTypeName(ref InternalPackageReference, name string) InternalTypeName

MakeInternalTypeName is a factory method for creating a TypeName

func (InternalTypeName) AsDeclarations

func (tn InternalTypeName) AsDeclarations(codeGenerationContext *CodeGenerationContext, declContext DeclarationContext) ([]dst.Decl, error)

func (InternalTypeName) AsTypeExpr

func (tn InternalTypeName) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType implements Type for TypeName

func (InternalTypeName) AsZero

func (tn InternalTypeName) AsZero(definitions TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

AsZero renders an expression for the "zero" value of the type. The exact thing we need to generate depends on the actual type we reference

func (InternalTypeName) Equals

func (tn InternalTypeName) Equals(t Type, override EqualityOverrides) bool

Equals returns true if the passed type is the same TypeName, false otherwise

func (InternalTypeName) InternalPackageReference

func (tn InternalTypeName) InternalPackageReference() InternalPackageReference

InternalPackageReference returns the internal package to which the type belongs

func (InternalTypeName) IsARMType

func (tn InternalTypeName) IsARMType() bool

IsARMType returns true if the TypeName identifies an ARM specific type, false otherwise.

func (InternalTypeName) IsEmpty

func (tn InternalTypeName) IsEmpty() bool

func (InternalTypeName) IsSpec

func (tn InternalTypeName) IsSpec() bool

IsSpec returns true if the type name specifies a spec Sometimes we build type names by adding a suffix after _Spec, so we need to use a contains check

func (InternalTypeName) IsStatus

func (tn InternalTypeName) IsStatus() bool

IsStatus returns true if the type name specifies a status Sometimes we build type names by adding a suffix after _STATUS, so we need to use a contains check

func (InternalTypeName) Name

func (tn InternalTypeName) Name() string

Name returns the package-local name of the type

func (InternalTypeName) PackageReference

func (tn InternalTypeName) PackageReference() PackageReference

PackageReference returns the package to which the type belongs

func (InternalTypeName) Plural

func (tn InternalTypeName) Plural() InternalTypeName

Plural returns a TypeName with the name pluralized.

func (InternalTypeName) References

func (tn InternalTypeName) References() TypeNameSet

References returns a set containing this type name.

func (InternalTypeName) RequiredPackageReferences

func (tn InternalTypeName) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns all the imports required for this definition

func (InternalTypeName) Singular

func (tn InternalTypeName) Singular() InternalTypeName

Singular returns a TypeName with the name singularized.

func (InternalTypeName) String

func (tn InternalTypeName) String() string

String returns the string representation of the type name, and implements fmt.Stringer.

func (InternalTypeName) WithName

func (tn InternalTypeName) WithName(name string) InternalTypeName

WithName returns a new InternalTypeName in the same package but with a different name

func (InternalTypeName) WithPackageReference

func (tn InternalTypeName) WithPackageReference(ref InternalPackageReference) InternalTypeName

WithPackageReference returns a new InternalTypeName in a different package but with the same name

func (InternalTypeName) WriteDebugDescription

func (tn InternalTypeName) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder. builder receives the full description, including nested types definitions is a dictionary for resolving named types

type InternalTypeNameSet

type InternalTypeNameSet map[InternalTypeName]struct{}

InternalTypeNameSet stores type names in no particular order without duplicates.

func NewInternalTypeNameSet

func NewInternalTypeNameSet(initial ...InternalTypeName) InternalTypeNameSet

NewInternalTypeNameSet makes a InternalTypeNameSet containing the specified names. If no elements are passed it might be nil.

func (InternalTypeNameSet) Add

Add includes the passed name in the set

func (InternalTypeNameSet) AddAll

func (ts InternalTypeNameSet) AddAll(other InternalTypeNameSet)

AddAll adds the provided InternalTypeNameSet to the set

func (InternalTypeNameSet) Contains

func (ts InternalTypeNameSet) Contains(val InternalTypeName) bool

Contains returns whether this name is in the set. Works for nil sets too.

func (InternalTypeNameSet) ContainsAll

func (ts InternalTypeNameSet) ContainsAll(other InternalTypeNameSet) bool

ContainsAll returns whether all the names are in the set. Works for nil sets too.

func (InternalTypeNameSet) ContainsAny

func (ts InternalTypeNameSet) ContainsAny(other InternalTypeNameSet) bool

ContainsAny returns whether any item of other is contained in the set. Works for nil sets too.

func (InternalTypeNameSet) Copy

func (InternalTypeNameSet) Equals

func (InternalTypeNameSet) Remove

func (ts InternalTypeNameSet) Remove(val InternalTypeName)

Remove removes the specified item if it is in the set. If it is not in the set this is a no-op.

func (InternalTypeNameSet) Single

Single returns the single InternalTypeName in the set. This panics if there is not a single item in the set.

type KnownLocalsSet

type KnownLocalsSet struct {
	// contains filtered or unexported fields
}

func NewKnownLocalsSet

func NewKnownLocalsSet(idFactory IdentifierFactory) *KnownLocalsSet

NewKnownLocalsSet returns a new empty set of locals idFactory is a reference to an identifier factory for creating valid Go identifiers

func (*KnownLocalsSet) Add

func (locals *KnownLocalsSet) Add(identifiers ...string)

Add allows one or more identifiers that have already been used to be registered, avoiding duplicates

func (*KnownLocalsSet) Clone

func (locals *KnownLocalsSet) Clone() *KnownLocalsSet

Clone clones the KnownLocalsSet

func (*KnownLocalsSet) CreateLocal

func (locals *KnownLocalsSet) CreateLocal(nameHint string, suffixes ...string) string

CreateLocal creates a new unique Go local variable with one of the specified suffixes. Has to be deterministic, so we use an incrementing number to make them unique if necessary.

func (*KnownLocalsSet) CreatePluralLocal

func (locals *KnownLocalsSet) CreatePluralLocal(nameHint string, suffixes ...string) string

CreatePluralLocal creates a new unique Go local variable for multiple values with one of the specified suffixes.

func (*KnownLocalsSet) CreateSingularLocal

func (locals *KnownLocalsSet) CreateSingularLocal(nameHint string, suffixes ...string) string

CreateSingularLocal creates a new unique Go local variable for a single value with one of the specified suffixes.

func (*KnownLocalsSet) HasName

func (locals *KnownLocalsSet) HasName(name string) bool

HasName returns true if the specified name exists in the set, false otherwise

func (*KnownLocalsSet) TryCreateLocal

func (locals *KnownLocalsSet) TryCreateLocal(local string) bool

TryCreateLocal returns true if the specified local was successfully created, false if it already existed

type KubeBuilderValidation

type KubeBuilderValidation struct {
	// contains filtered or unexported fields
}

KubeBuilderValidation represents some kind of data validation on a property

func MakeEnumValidation

func MakeEnumValidation(permittedValues []interface{}) KubeBuilderValidation

MakeEnumValidation returns a Validation that requires the value be one of the passed 'permittedValues'

func MakeExclusiveMaxiumValidation

func MakeExclusiveMaxiumValidation() KubeBuilderValidation

func MakeExclusiveMinimumValidation

func MakeExclusiveMinimumValidation() KubeBuilderValidation

func MakeMaxItemsValidation

func MakeMaxItemsValidation(length int64) KubeBuilderValidation

func MakeMaxLengthValidation

func MakeMaxLengthValidation(length int64) KubeBuilderValidation

func MakeMaximumValidation

func MakeMaximumValidation(value *big.Rat) KubeBuilderValidation

func MakeMinItemsValidation

func MakeMinItemsValidation(length int64) KubeBuilderValidation

func MakeMinLengthValidation

func MakeMinLengthValidation(length int64) KubeBuilderValidation

func MakeMultipleOfValidation

func MakeMultipleOfValidation(value *big.Rat) KubeBuilderValidation

func MakePatternValidation

func MakePatternValidation(pattern *regexp.Regexp) KubeBuilderValidation

func MakeRequiredValidation

func MakeRequiredValidation() KubeBuilderValidation

MakeRequiredValidation returns a Validation that requires a value be present

func MaxMinimumValidation

func MaxMinimumValidation(value *big.Rat) KubeBuilderValidation

func (KubeBuilderValidation) Equals

func (KubeBuilderValidation) HasName

func (v KubeBuilderValidation) HasName(name string) bool

func (KubeBuilderValidation) String

func (v KubeBuilderValidation) String() string

type LocalPackageReference

type LocalPackageReference struct {
	// contains filtered or unexported fields
}

LocalPackageReference specifies a local package name or reference

func MakeLocalPackageReference

func MakeLocalPackageReference(prefix string, group string, versionPrefix string, version string) LocalPackageReference

MakeLocalPackageReference Creates a new local package reference from a group and version

func (LocalPackageReference) ApiVersion

func (pr LocalPackageReference) ApiVersion() string

ApiVersion returns the API version of this reference, separate from the generator version

func (LocalPackageReference) Equals

Equals returns true if the passed package reference references the same package, false otherwise

func (LocalPackageReference) FolderPath

func (pr LocalPackageReference) FolderPath() string

FolderPath returns the relative path to this package on disk.

func (LocalPackageReference) GeneratorVersion

func (pr LocalPackageReference) GeneratorVersion() string

GeneratorVersion returns the part of the package name refering to the version of the generator

func (LocalPackageReference) Group

func (pr LocalPackageReference) Group() string

Group returns the group of this local reference

func (LocalPackageReference) GroupVersion

func (pr LocalPackageReference) GroupVersion() (string, string)

GroupVersion returns the group and version of this local reference.

func (LocalPackageReference) HasApiVersion

func (pr LocalPackageReference) HasApiVersion(ver string) bool

HasApiVersion returns true if this reference has the specified API version

func (LocalPackageReference) HasVersionPrefix

func (pr LocalPackageReference) HasVersionPrefix(prefix string) bool

HasVersionPrefix returns true if we have the specified version prefix, false otherwise.

func (LocalPackageReference) ImportAlias

func (pr LocalPackageReference) ImportAlias(style PackageImportStyle) string

ImportAlias returns the import alias to use for this package reference

func (LocalPackageReference) ImportPath

func (pr LocalPackageReference) ImportPath() string

ImportPath returns the path to use when importing this package

func (LocalPackageReference) IsPreview

func (pr LocalPackageReference) IsPreview() bool

IsPreview returns true if this package reference is a preview We don't check the version prefix (which contains the version of the generator) as that may contain alpha or beta even if the ARM version is not preview.

func (LocalPackageReference) LocalPathPrefix

func (pr LocalPackageReference) LocalPathPrefix() string

LocalPathPrefix returns the prefix (everything up to the group name)

func (LocalPackageReference) PackageName

func (pr LocalPackageReference) PackageName() string

PackageName returns the package name of this reference

func (LocalPackageReference) PackagePath

func (pr LocalPackageReference) PackagePath() string

PackagePath returns the fully qualified package path

func (LocalPackageReference) String

func (pr LocalPackageReference) String() string

String returns the string representation of the package reference

func (LocalPackageReference) Version

func (pr LocalPackageReference) Version() string

Version returns the version of this local reference

func (LocalPackageReference) WithVersionPrefix

func (pr LocalPackageReference) WithVersionPrefix(prefix string) LocalPackageReference

WithVersionPrefix returns a new LocalPackageReference with a different version prefix

type MakePerPropertyContext

type MakePerPropertyContext[C any] func(ot *ObjectType, prop *PropertyDefinition, ctx C) (C, error)

type MapType

type MapType struct {
	// contains filtered or unexported fields
}

MapType is used to define properties that contain additional property values

func AsMapType

func AsMapType(aType Type) (*MapType, bool)

AsMapType unwraps any wrappers around the provided type and returns either the underlying MapType and true, or nil and false.

func NewMapType

func NewMapType(key Type, value Type) *MapType

NewMapType creates a new map with the specified key and value types

func NewStringMapType

func NewStringMapType(value Type) *MapType

NewStringMapType creates a new map with string keys and the specified value type

func (*MapType) AsDeclarations

func (m *MapType) AsDeclarations(codeGenerationContext *CodeGenerationContext, declContext DeclarationContext) ([]dst.Decl, error)

func (*MapType) AsTypeExpr

func (m *MapType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType implements Type for MapType to create the abstract syntax tree for a map

func (*MapType) AsZero

AsZero renders an expression for the "zero" value of a map by calling make()

func (*MapType) Equals

func (m *MapType) Equals(t Type, overrides EqualityOverrides) bool

Equals returns true if the passed type is a map type with the same kinds of keys and elements, false otherwise

func (*MapType) KeyType

func (m *MapType) KeyType() Type

KeyType returns the type of keys in the type represented by this MapType

func (*MapType) References

func (m *MapType) References() TypeNameSet

References returns all of the types referenced by either the the key or value types.

func (*MapType) RequiredPackageReferences

func (m *MapType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns a list of packages required by this

func (*MapType) String

func (m *MapType) String() string

String implements fmt.Stringer

func (*MapType) ValueType

func (m *MapType) ValueType() Type

ValueType returns the type of values in the type represented by this MapType

func (*MapType) WithKeyType

func (m *MapType) WithKeyType(t Type) *MapType

func (*MapType) WithValueType

func (m *MapType) WithValueType(t Type) *MapType

func (*MapType) WriteDebugDescription

func (m *MapType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder builder receives the full description, including nested types definitions is for resolving named types

type MergerFunc

type MergerFunc func(ctx interface{}, left, right Type) (Type, error)

type MetaType

type MetaType interface {
	// Unwrap returns the type contained within the wrapper type
	Unwrap() Type
}

A MetaType is a type wrapper that provide additional information/context about another type

type NumberValidations

type NumberValidations struct {
	// TODO: update to use doubles once newer version of controller-gen is released
	Maximum          *big.Rat
	Minimum          *big.Rat
	ExclusiveMaximum bool
	ExclusiveMinimum bool
	MultipleOf       *big.Rat
}

func (NumberValidations) Equals

func (nv NumberValidations) Equals(other Validations) bool

func (NumberValidations) ToKubeBuilderValidations

func (nv NumberValidations) ToKubeBuilderValidations() []KubeBuilderValidation

type ObjectType

type ObjectType struct {
	InterfaceImplementer
	// contains filtered or unexported fields
}

ObjectType represents an (unnamed) object type

func AsObjectType

func AsObjectType(aType Type) (*ObjectType, bool)

AsObjectType unwraps any wrappers around the provided type and returns either the underlying ObjectType and true, or nil and false.

func NewObjectType

func NewObjectType() *ObjectType

NewObjectType is a factory method for creating a new ObjectType

func (*ObjectType) AsDeclarations

func (objectType *ObjectType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

func (*ObjectType) AsTypeExpr

func (objectType *ObjectType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType implements Type for ObjectType

func (*ObjectType) AsZero

func (objectType *ObjectType) AsZero(_ TypeDefinitionSet, _ *CodeGenerationContext) dst.Expr

AsZero renders an expression for the "zero" value of the type We can only generate a zero value for a named object type (and that's handled by TypeName, so we'll only end up here if it is an anonymous type.)

func (*ObjectType) ClearResources

func (objectType *ObjectType) ClearResources() *ObjectType

func (*ObjectType) EmbeddedProperties

func (objectType *ObjectType) EmbeddedProperties() []*PropertyDefinition

EmbeddedProperties returns all the embedded properties A sorted slice is returned to preserve immutability and provide determinism

func (*ObjectType) Equals

func (objectType *ObjectType) Equals(t Type, overrides EqualityOverrides) bool

Equals returns true if the passed type is an object type with the same properties, false otherwise The order of the properties is not relevant

func (*ObjectType) FindAllPropertiesWithTagValue

func (objectType *ObjectType) FindAllPropertiesWithTagValue(tag string, value string) []*PropertyDefinition

FindAllPropertiesWithTagValue finds all the properties with the given tag and value if they exist.

func (*ObjectType) FindPropertyWithTagValue

func (objectType *ObjectType) FindPropertyWithTagValue(tag string, value string) (*PropertyDefinition, bool)

FindPropertyWithTagValue finds the property with the given tag and value if it exists. The boolean return is false if no match can be found.

func (*ObjectType) Functions

func (objectType *ObjectType) Functions() []Function

Functions returns all the function implementations A sorted slice is returned to preserve immutability and provide determinism

func (*ObjectType) HasFunctionWithName

func (objectType *ObjectType) HasFunctionWithName(name string) bool

HasFunctionWithName determines if this object has a function with the given name

func (*ObjectType) HasTestCases

func (objectType *ObjectType) HasTestCases() bool

func (*ObjectType) IsResource

func (objectType *ObjectType) IsResource() bool

func (*ObjectType) Properties

func (objectType *ObjectType) Properties() ReadOnlyPropertySet

Properties returns all the property definitions

func (*ObjectType) Property

func (objectType *ObjectType) Property(name PropertyName) (*PropertyDefinition, bool)

Property returns the details of a specific property based on its unique case-sensitive name

func (*ObjectType) References

func (objectType *ObjectType) References() TypeNameSet

References returns the set of all the types referred to by any property.

func (*ObjectType) RequiredPackageReferences

func (objectType *ObjectType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns a list of packages required by this

func (*ObjectType) Resources

func (objectType *ObjectType) Resources() TypeNameSet

func (*ObjectType) String

func (objectType *ObjectType) String() string

String implements fmt.Stringer

func (*ObjectType) TestCases

func (objectType *ObjectType) TestCases() []TestCase

func (*ObjectType) WithEmbeddedProperties

func (objectType *ObjectType) WithEmbeddedProperties(properties ...*PropertyDefinition) (*ObjectType, error)

WithEmbeddedProperties creates a new ObjectType with the additional embedded properties included

func (*ObjectType) WithEmbeddedProperty

func (objectType *ObjectType) WithEmbeddedProperty(property *PropertyDefinition) (*ObjectType, error)

WithEmbeddedProperty creates a new ObjectType with another embedded property

func (*ObjectType) WithFunction

func (objectType *ObjectType) WithFunction(function Function) *ObjectType

WithFunction creates a new ObjectType with a function (method) attached to it

func (*ObjectType) WithInterface

func (objectType *ObjectType) WithInterface(iface *InterfaceImplementation) *ObjectType

WithInterface creates a new ObjectType that's a copy with an interface implementation attached

func (*ObjectType) WithIsResource

func (objectType *ObjectType) WithIsResource(isResource bool) *ObjectType

func (*ObjectType) WithProperties

func (objectType *ObjectType) WithProperties(properties ...*PropertyDefinition) *ObjectType

WithProperties creates a new ObjectType that's a copy with additional properties included Properties are unique by name, so this can be used to both Add and Replace properties.

func (*ObjectType) WithProperty

func (objectType *ObjectType) WithProperty(property *PropertyDefinition) *ObjectType

WithProperty creates a new ObjectType with another property attached to it Properties are unique by name, so this can be used to Add and to Replace a property

func (*ObjectType) WithResource

func (objectType *ObjectType) WithResource(resource TypeName) *ObjectType

func (*ObjectType) WithResources

func (objectType *ObjectType) WithResources(resources TypeNameSet) *ObjectType

func (*ObjectType) WithTestCase

func (objectType *ObjectType) WithTestCase(testcase TestCase) *ObjectType

WithTestCase creates a new ObjectType that's a copy with an additional test case included

func (*ObjectType) WithoutEmbeddedProperties

func (objectType *ObjectType) WithoutEmbeddedProperties() *ObjectType

WithoutEmbeddedProperties creates a new ObjectType from this one but without any embedded properties.

func (*ObjectType) WithoutEmbeddedProperty

func (objectType *ObjectType) WithoutEmbeddedProperty(name TypeName) *ObjectType

WithoutEmbeddedProperty creates a new ObjectType that's a copy without the specified typeName embedded

func (*ObjectType) WithoutFunctions

func (objectType *ObjectType) WithoutFunctions() *ObjectType

WithoutFunctions creates a new ObjectType with no functions (useful for testing)

func (*ObjectType) WithoutInterface

func (objectType *ObjectType) WithoutInterface(name TypeName) *ObjectType

WithoutInterface removes the specified interface

func (*ObjectType) WithoutProperties

func (objectType *ObjectType) WithoutProperties() *ObjectType

WithoutProperties creates a new ObjectType from this one but without any properties.

func (*ObjectType) WithoutProperty

func (objectType *ObjectType) WithoutProperty(name PropertyName) *ObjectType

WithoutProperty creates a new ObjectType that's a copy without the specified property

func (*ObjectType) WithoutSpecificProperties

func (objectType *ObjectType) WithoutSpecificProperties(props ...PropertyName) *ObjectType

WithoutSpecificProperties creates a new ObjectType from this one but without any properties.

func (*ObjectType) WriteDebugDescription

func (objectType *ObjectType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder. builder receives the full description, including nested types.

type OneOfType

type OneOfType struct {
	// contains filtered or unexported fields
}

OneOfType represents something that can be any one of a number of selected types

func AsOneOfType

func AsOneOfType(t Type) (*OneOfType, bool)

AsOneOfType unwraps any wrappers around the provided type and returns either the underlying OneOfType and true, or nil and false.

func NewOneOfType

func NewOneOfType(name string, types ...Type) *OneOfType

NewOneOfType creates a new instance of a OneOfType

func (*OneOfType) AsDeclarations

func (oneOf *OneOfType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

AsDeclarations always panics; OneOf cannot be represented by the Go AST and must be lowered to an object type

func (*OneOfType) AsTypeExpr

func (oneOf *OneOfType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType always panics; OneOf cannot be represented by the Go AST and must be lowered to an object type

func (*OneOfType) AsZero

AsZero always panics; OneOf cannot be represented by the Go AST and must be lowered to an object type

func (*OneOfType) DiscriminatorProperty

func (oneOf *OneOfType) DiscriminatorProperty() string

DiscriminatorProperty returns the name of the discriminatorProperty property (if any)

func (*OneOfType) DiscriminatorValue

func (oneOf *OneOfType) DiscriminatorValue() string

DiscriminatorValue returns the discriminator value used to identify this subtype

func (*OneOfType) Equals

func (oneOf *OneOfType) Equals(t Type, overrides EqualityOverrides) bool

Equals returns true if the other Type is a OneOfType that contains the same set of types

func (*OneOfType) HasDiscriminatorProperty

func (oneOf *OneOfType) HasDiscriminatorProperty() bool

HasDiscriminatorProperty returns true if the OneOf has a discriminator property

func (*OneOfType) HasDiscriminatorValue

func (oneOf *OneOfType) HasDiscriminatorValue() bool

HasDiscriminatorValue returns true if the OneOf has a discriminator value

func (*OneOfType) Name

func (oneOf *OneOfType) Name() string

Name returns the internal (swagger) name of the OneOf

func (*OneOfType) PropertyObjects

func (oneOf *OneOfType) PropertyObjects() []*ObjectType

PropertyObjects returns all the ObjectTypes that define the properties of this OneOf

func (*OneOfType) References

func (oneOf *OneOfType) References() TypeNameSet

References returns any type referenced by the OneOf types

func (*OneOfType) RequiredPackageReferences

func (oneOf *OneOfType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns the union of the required imports of all the oneOf types

func (*OneOfType) String

func (oneOf *OneOfType) String() string

String implements fmt.Stringer

func (*OneOfType) Types

func (oneOf *OneOfType) Types() ReadonlyTypeSet

Types returns what subtypes the OneOf may be. Exposed as ReadonlyTypeSet so caller cannot break invariants.

func (*OneOfType) WithAdditionalPropertyObject

func (oneOf *OneOfType) WithAdditionalPropertyObject(propertyObject *ObjectType) *OneOfType

WithAdditionalPropertyObject returns a new OneOf that includes the specified properties as well as those already present

func (*OneOfType) WithDiscriminatorProperty

func (oneOf *OneOfType) WithDiscriminatorProperty(discriminator string) *OneOfType

WithDiscriminatorProperty returns a new OneOf object with the specified discriminatorProperty property

func (*OneOfType) WithDiscriminatorValue

func (oneOf *OneOfType) WithDiscriminatorValue(value string) *OneOfType

func (*OneOfType) WithType

func (oneOf *OneOfType) WithType(t Type) *OneOfType

WithType returns a new OneOf with the specified type included

func (*OneOfType) WithTypes

func (oneOf *OneOfType) WithTypes(types []Type) *OneOfType

WithTypes returns a new OneOf with only the specified types

func (*OneOfType) WithoutAnyPropertyObjects

func (oneOf *OneOfType) WithoutAnyPropertyObjects() *OneOfType

WithoutAnyPropertyObjects returns a new OneOf that has no Object properties

func (*OneOfType) WithoutType

func (oneOf *OneOfType) WithoutType(t Type) *OneOfType

WithoutType returns a new OneOf with the specified type removed

func (*OneOfType) WriteDebugDescription

func (oneOf *OneOfType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder. builder receives the full description, including nested types. definitions is a dictionary for resolving named types.

type OptionalType

type OptionalType struct {
	// contains filtered or unexported fields
}

OptionalType is used for items that may or may not be present

func AsOptionalType

func AsOptionalType(aType Type) (*OptionalType, bool)

AsOptionalType unwraps any wrappers around the provided type and returns either the underlying OptionalType and true, or nil and false.

func (*OptionalType) AsDeclarations

func (optional *OptionalType) AsDeclarations(codeGenerationContext *CodeGenerationContext, declContext DeclarationContext) ([]dst.Decl, error)

func (*OptionalType) AsTypeExpr

func (optional *OptionalType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType renders the Go abstract syntax tree for an optional type

func (*OptionalType) AsZero

AsZero renders an expression for the "zero" value of the type by returning a literal "nil"

func (*OptionalType) BaseType

func (optional *OptionalType) BaseType() Type

BaseType returns the underlying type

func (*OptionalType) Element

func (optional *OptionalType) Element() Type

Element returns the type which is optional

func (*OptionalType) Equals

func (optional *OptionalType) Equals(t Type, overrides EqualityOverrides) bool

Equals returns true if this type is equal to the other type

func (*OptionalType) References

func (optional *OptionalType) References() TypeNameSet

References returns the set of types that the underlying type refers to directly.

func (*OptionalType) RequiredPackageReferences

func (optional *OptionalType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns the imports required by the 'element' type

func (*OptionalType) String

func (optional *OptionalType) String() string

String implements fmt.Stringer

func (*OptionalType) Unwrap

func (optional *OptionalType) Unwrap() Type

Unwrap returns the type contained within the wrapper type

func (*OptionalType) WithElement

func (optional *OptionalType) WithElement(t Type) Type

func (*OptionalType) WriteDebugDescription

func (optional *OptionalType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder instance. builder receives the full description, including nested types. definitions is a dictionary for resolving named types.

type PackageDefinition

type PackageDefinition struct {
	PackageName string // Name  of the package
	GroupName   string // Group to which the package belongs
	Version     string // Kubernetes version of this package
	Path        string // relative Path to the package
	// contains filtered or unexported fields
}

PackageDefinition is the definition of a package

func NewPackageDefinition

func NewPackageDefinition(ref InternalPackageReference) *PackageDefinition

NewPackageDefinition constructs a new package definition

func (*PackageDefinition) AddDefinition

func (p *PackageDefinition) AddDefinition(def TypeDefinition)

AddDefinition adds a Definition to the PackageDefinition

func (*PackageDefinition) DefinitionCount

func (p *PackageDefinition) DefinitionCount() int

DefinitionCount returns the count of definitions that have been sorted into this package

func (*PackageDefinition) Definitions

func (p *PackageDefinition) Definitions() TypeDefinitionSet

func (*PackageDefinition) EmitDefinitions

func (p *PackageDefinition) EmitDefinitions(
	outputDir string,
	generatedPackages map[InternalPackageReference]*PackageDefinition,
	emitDocFiles bool,
) (int, error)

EmitDefinitions emits the PackageDefinition to an output directory

func (*PackageDefinition) GetDefinition

func (p *PackageDefinition) GetDefinition(typeName InternalTypeName) (TypeDefinition, error)

type PackageImport

type PackageImport struct {
	// contains filtered or unexported fields
}

PackageImport represents an import of a name from a package

func NewPackageImport

func NewPackageImport(packageReference PackageReference) PackageImport

NewPackageImport creates a new package import from a reference

func (PackageImport) AsImportSpec

func (pi PackageImport) AsImportSpec() *dst.ImportSpec

func (PackageImport) Equals

func (pi PackageImport) Equals(ref PackageImport) bool

Equals returns true if the passed package import references the same package with the same name, false otherwise

func (PackageImport) HasExplicitName

func (pi PackageImport) HasExplicitName() bool

HasExplicitName returns true if this package import has an explicitly defined name

func (PackageImport) PackageName

func (pi PackageImport) PackageName() string

PackageName is the package name of the package reference

func (PackageImport) String

func (pi PackageImport) String() string

func (PackageImport) WithImportAlias

func (pi PackageImport) WithImportAlias(style PackageImportStyle) PackageImport

WithImportAlias creates a copy of this import with a name following the specified rules

func (PackageImport) WithName

func (pi PackageImport) WithName(name string) PackageImport

WithName creates a new package reference with a friendly name

type PackageImportSet

type PackageImportSet struct {
	// contains filtered or unexported fields
}

func NewPackageImportSet

func NewPackageImportSet() *PackageImportSet

NewPackageImportSet creates a new empty set of PackageImport references

func (*PackageImportSet) AddImport

func (set *PackageImportSet) AddImport(packageImport PackageImport)

AddImport ensures the set includes a specified import If packageImport has an explicit name, we use it (this allows updating the set to use a different name for the import); if it doesn't have an explicit name, we only use it if we don't already have the reference (ensuring that we keep any existing named import if we have one).

func (*PackageImportSet) AddImportOfReference

func (set *PackageImportSet) AddImportOfReference(ref PackageReference)

AddImportOfReference ensures this set includes an import of the specified reference Adding a reference already in the set is fine.

func (*PackageImportSet) AddImportsOfReferences

func (set *PackageImportSet) AddImportsOfReferences(refs ...PackageReference)

AddImportsOfReferences ensures this set includes an import of all the specified references Adding a reference already in the set is fine.

func (*PackageImportSet) ApplyName

func (set *PackageImportSet) ApplyName(ref PackageReference, name string)

ApplyName replaces any existing PackageImport for the specified reference with one using the specified name

func (*PackageImportSet) AsImportSpecs

func (set *PackageImportSet) AsImportSpecs() []dst.Spec

AsImportSpecs returns the abstract syntax tree representation for importing the packages in this set

func (*PackageImportSet) AsSlice

func (set *PackageImportSet) AsSlice() []PackageImport

AsSlice returns a slice containing all the imports

func (*PackageImportSet) AsSortedSlice

func (set *PackageImportSet) AsSortedSlice() []PackageImport

AsSortedSlice return a sorted slice containing all the imports

func (*PackageImportSet) ContainsImport

func (set *PackageImportSet) ContainsImport(packageImport PackageImport) bool

ContainsImport allows checking to see if an import is included

func (*PackageImportSet) ImportFor

func (set *PackageImportSet) ImportFor(ref PackageReference) (PackageImport, bool)

ImportFor looks up a package reference and returns its import, if any

func (*PackageImportSet) Length

func (set *PackageImportSet) Length() int

Length returns the number of unique imports in this set

func (*PackageImportSet) Merge

func (set *PackageImportSet) Merge(other *PackageImportSet)

Merge ensures that all imports specified in other are included

func (*PackageImportSet) Remove

func (set *PackageImportSet) Remove(packageImport PackageImport)

Remove ensures the specified item is not present Removing an item not in the set is not an error.

type PackageImportStyle

type PackageImportStyle string

PackageImportStyle is used to determine how to define a unique package import alias in a given context

const (
	// Name is used when the name of the package is sufficient to uniquely identify it
	Name PackageImportStyle = "Name"
	// VersionOnly is used when using just the version of the package is sufficiently unique
	VersionOnly PackageImportStyle = "VersionOnly"
	// GroupOnly is used when using just the group of the package sufficiently unique
	GroupOnly PackageImportStyle = "GroupOnly"
	// GroupAndVersion is used when both the group and version of the package are required for it to be unique
	GroupAndVersion PackageImportStyle = "GroupAndVersion"
)

type PackageReference

type PackageReference interface {
	// PackageName returns the package name of this reference
	PackageName() string

	// Equals returns true if the passed package reference references the same package, false otherwise
	Equals(ref PackageReference) bool

	// String returns the string representation of the package reference
	String() string

	// ImportAlias returns the import alias to use for this package reference
	ImportAlias(style PackageImportStyle) string

	// ImportPath returns the path to use when importing this package.
	ImportPath() string
}

type PackageReferenceSet

type PackageReferenceSet struct {
	// contains filtered or unexported fields
}

PackageReferenceSet represents a set of distinct PackageReferences

func NewPackageReferenceSet

func NewPackageReferenceSet(refs ...PackageReference) *PackageReferenceSet

NewPackageReferenceSet creates a new empty set of PackageReferences

func (*PackageReferenceSet) AddReference

func (set *PackageReferenceSet) AddReference(ref PackageReference)

AddReference ensures the set includes a specified Reference

func (*PackageReferenceSet) AsSlice

func (set *PackageReferenceSet) AsSlice() []PackageReference

AsSlice returns a slice containing all the imports

func (*PackageReferenceSet) AsSortedSlice

func (set *PackageReferenceSet) AsSortedSlice(
	compare func(PackageReference, PackageReference) int,
) []PackageReference

AsSortedSlice return a sorted slice containing all the references less specifies how to order the imports

func (*PackageReferenceSet) Clear

func (set *PackageReferenceSet) Clear()

Clear removes everything from the set

func (*PackageReferenceSet) Contains

func (set *PackageReferenceSet) Contains(ref PackageReference) bool

Contains allows checking to see if an import is included

func (*PackageReferenceSet) Length

func (set *PackageReferenceSet) Length() int

Length returns the number of unique imports in this set

func (*PackageReferenceSet) Merge

func (set *PackageReferenceSet) Merge(other *PackageReferenceSet)

Merge ensures that all references specified in other are included

func (*PackageReferenceSet) Remove

func (set *PackageReferenceSet) Remove(ref PackageReference)

Remove ensures the specified item is not present Removing an item not in the set is not an error.

type PrimitiveType

type PrimitiveType struct {
	// contains filtered or unexported fields
}

PrimitiveType represents a Go primitive type

func AsPrimitiveType

func AsPrimitiveType(aType Type) (*PrimitiveType, bool)

AsPrimitiveType unwraps any wrappers around the provided type and returns either the underlying PrimitiveType and true, or nil and false.

func LookupPrimitiveType

func LookupPrimitiveType(name string) (*PrimitiveType, bool)

LookupPrimitiveType allows finding a primitive type by name in contexts where direct access to variables like IntType is not possible; typically this occurs when handling a type name during YAML deserialization.

func (*PrimitiveType) AsDeclarations

func (prim *PrimitiveType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

func (*PrimitiveType) AsTypeExpr

func (prim *PrimitiveType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType implements Type for PrimitiveType returning an abstract syntax tree

func (*PrimitiveType) AsZero

func (prim *PrimitiveType) AsZero(definitions TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

AsZero renders an expression for the "zero" value of the type definitions allows TypeName to resolve to the underlying type ctx allows current imports to be correctly identified where needed

func (*PrimitiveType) Equals

func (prim *PrimitiveType) Equals(t Type, _ EqualityOverrides) bool

Equals returns true if the passed type is another primitive type the same name, false otherwise

func (*PrimitiveType) Name

func (prim *PrimitiveType) Name() string

Name returns the name of the primitive type

func (*PrimitiveType) References

func (prim *PrimitiveType) References() TypeNameSet

References always returns nil because primitive types don't refer to any other types.

func (*PrimitiveType) RequiredPackageReferences

func (prim *PrimitiveType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns a list of package required by this

func (*PrimitiveType) String

func (prim *PrimitiveType) String() string

String implements fmt.Stringer

func (*PrimitiveType) WriteDebugDescription

func (prim *PrimitiveType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of this primitive type to the passed builder

type PropertyContainer

type PropertyContainer interface {
	// Properties returns all the properties in this container
	Properties() ReadOnlyPropertySet

	// Property returns the property and true if the named property is found, nil and false otherwise
	Property(name PropertyName) (*PropertyDefinition, bool)

	// EmbeddedProperties returns all the embedded properties in this container
	EmbeddedProperties() []*PropertyDefinition
}

PropertyContainer is implemented by Types that contain properties Provides readonly access as we need to use a TypeVisitor for modifications to preserve type wrapping

func AsPropertyContainer

func AsPropertyContainer(theType Type) (PropertyContainer, bool)

AsPropertyContainer converts a type into a property container Only use this readonly access as we must use a TypeVisitor for modifications to preserve type wrapping

type PropertyDefinition

type PropertyDefinition struct {
	// contains filtered or unexported fields
}

PropertyDefinition encapsulates the definition of a property

func NewPropertyDefinition

func NewPropertyDefinition(propertyName PropertyName, jsonName string, propertyType Type) *PropertyDefinition

NewPropertyDefinition is a factory method for creating a new PropertyDefinition name is the name for the new property (mandatory) propertyType is the type for the new property (mandatory)

func (*PropertyDefinition) AddFlattenedFrom

func (property *PropertyDefinition) AddFlattenedFrom(name PropertyName) *PropertyDefinition

func (*PropertyDefinition) AsField

func (property *PropertyDefinition) AsField(
	codeGenerationContext *CodeGenerationContext,
) (*dst.Field, error)

AsField generates a Go AST field node representing this property definition

func (*PropertyDefinition) Description

func (property *PropertyDefinition) Description() string

Description returns the property description

func (*PropertyDefinition) Equals

func (property *PropertyDefinition) Equals(o *PropertyDefinition, overrides EqualityOverrides) bool

Equals tests to see if the specified PropertyDefinition specifies the same property

func (*PropertyDefinition) Flatten

func (property *PropertyDefinition) Flatten() bool

Flatten returns true iff the property is marked with 'flatten'.

func (*PropertyDefinition) FlattenedFrom

func (property *PropertyDefinition) FlattenedFrom() []PropertyName

func (*PropertyDefinition) HasName

func (property *PropertyDefinition) HasName(name PropertyName) bool

HasName returns true if the property has the given name

func (*PropertyDefinition) HasTag

func (property *PropertyDefinition) HasTag(key string) bool

HasTag returns true if the property has the specified tag

func (*PropertyDefinition) HasTagValue

func (property *PropertyDefinition) HasTagValue(key string, value string) bool

HasTagValue returns true if the property has the specified tag value

func (*PropertyDefinition) IsRequired

func (property *PropertyDefinition) IsRequired() bool

IsRequired returns true if the property is required; returns false otherwise.

func (*PropertyDefinition) IsSecret

func (property *PropertyDefinition) IsSecret() bool

IsSecret returns true iff the property is a secret.

func (*PropertyDefinition) JSONName

func (property *PropertyDefinition) JSONName() (string, bool)

JSONName returns the JSON name of the property, or false if there is no json name

func (*PropertyDefinition) MakeOptional

func (property *PropertyDefinition) MakeOptional() *PropertyDefinition

MakeOptional returns a new PropertyDefinition that has an optional value

func (*PropertyDefinition) MakeRequired

func (property *PropertyDefinition) MakeRequired() *PropertyDefinition

MakeRequired returns a new PropertyDefinition that is marked as required

func (*PropertyDefinition) MakeTypeOptional

func (property *PropertyDefinition) MakeTypeOptional() *PropertyDefinition

MakeTypeOptional makes this properties Type optional. Note that this does NOT impact the kubebuilder:validation:Required annotation. For that, see MakeOptional.

func (*PropertyDefinition) MakeTypeRequired

func (property *PropertyDefinition) MakeTypeRequired() *PropertyDefinition

MakeTypeRequired makes this properties Type required (non-optional). Note that this does NOT impact the kubebuilder:validation:Required annotation. For that, see MakeRequired.

func (*PropertyDefinition) PropertyName

func (property *PropertyDefinition) PropertyName() PropertyName

PropertyName returns the name of the property

func (*PropertyDefinition) PropertyType

func (property *PropertyDefinition) PropertyType() Type

PropertyType returns the data type of the property

func (*PropertyDefinition) ReadOnly

func (property *PropertyDefinition) ReadOnly() bool

ReadOnly returns true iff the property is a secret.

func (*PropertyDefinition) Renamed

func (property *PropertyDefinition) Renamed() (PropertyName, bool)

Renamed allows checking to see if the property has been renamed. Returns the original name, and true if a rename has occurred; otherwise returns an undefined value and false.

func (*PropertyDefinition) SetFlatten

func (property *PropertyDefinition) SetFlatten(flatten bool) *PropertyDefinition

SetFlatten sets if the property should be flattened or not

func (*PropertyDefinition) String

func (property *PropertyDefinition) String() string

func (*PropertyDefinition) Tag

func (property *PropertyDefinition) Tag(key string) ([]string, bool)

Tag returns the tag values of a given tag key

func (*PropertyDefinition) WasFlattened

func (property *PropertyDefinition) WasFlattened() bool

func (*PropertyDefinition) WasFlattenedFrom

func (property *PropertyDefinition) WasFlattenedFrom(name PropertyName) bool

func (*PropertyDefinition) WithDescription

func (property *PropertyDefinition) WithDescription(description string) *PropertyDefinition

WithDescription returns a new PropertyDefinition with the specified description

func (*PropertyDefinition) WithIsSecret

func (property *PropertyDefinition) WithIsSecret(secret bool) *PropertyDefinition

WithIsSecret returns a new PropertyDefinition with IsSecret set to the specified value

func (*PropertyDefinition) WithJsonName

func (property *PropertyDefinition) WithJsonName(jsonName string) *PropertyDefinition

WithName returns a new PropertyDefinition with the JSON name

func (*PropertyDefinition) WithName

func (property *PropertyDefinition) WithName(name PropertyName) *PropertyDefinition

WithName returns a new PropertyDefinition with the given name

func (*PropertyDefinition) WithReadOnly

func (property *PropertyDefinition) WithReadOnly(readOnly bool) *PropertyDefinition

WithReadOnly returns a new PropertyDefinition with ReadOnly set to the specified value

func (*PropertyDefinition) WithTag

func (property *PropertyDefinition) WithTag(key string, value string) *PropertyDefinition

WithTag adds the given tag to the field

func (*PropertyDefinition) WithType

func (property *PropertyDefinition) WithType(
	newType Type,
) *PropertyDefinition

WithType clones the property and returns it with a new type

func (*PropertyDefinition) WithoutTag

func (property *PropertyDefinition) WithoutTag(key string, value string) *PropertyDefinition

WithoutTag removes the given tag (or value of tag) from the field. If value is empty, remove the entire tag. if value is not empty, remove just that value.

type PropertyInjector

type PropertyInjector struct {
	// contains filtered or unexported fields
}

PropertyInjector is a utility for injecting property definitions into resources and objects

func NewPropertyInjector

func NewPropertyInjector() *PropertyInjector

NewPropertyInjector creates a new property injector for modifying resources and objects

func (*PropertyInjector) Inject

Inject modifies the passed type definition by injecting the passed property

type PropertyName

type PropertyName string

PropertyName is a semantic type

func (PropertyName) String

func (pn PropertyName) String() string

Implement Stringer for easy fmt printing

type PropertyNameAndType

type PropertyNameAndType struct {
	PropertyName PropertyName
	TypeName     InternalTypeName // the name of the type inside the pointer type
}

type PropertyReference

type PropertyReference struct {
	// contains filtered or unexported fields
}

PropertyReference is a fully qualified reference to where a property may be found

func MakePropertyReference

func MakePropertyReference(declaringType InternalTypeName, property PropertyName) PropertyReference

MakePropertyReference creates a new property reference identifying both the containing type and the property name.

func (PropertyReference) DeclaringType

func (ref PropertyReference) DeclaringType() InternalTypeName

DeclaringType returns the type name of the type declaring the property

func (PropertyReference) IsEmpty

func (ref PropertyReference) IsEmpty() bool

IsEmpty returns true if the reference is empty, false otherwise.

func (PropertyReference) Property

func (ref PropertyReference) Property() PropertyName

Property returns the actual name of the property

func (PropertyReference) String

func (ref PropertyReference) String() string

String returns a string representation of this property reference

type PropertyReferenceSet

type PropertyReferenceSet struct {
	// contains filtered or unexported fields
}

PropertyReferenceSet is a set of property references

func NewPropertyReferenceSet

func NewPropertyReferenceSet() *PropertyReferenceSet

NewPropertyReferenceSet returns a new empty property reference set

func (*PropertyReferenceSet) Add

func (set *PropertyReferenceSet) Add(refs ...PropertyReference)

Add ensures the set contains the specified references.

func (*PropertyReferenceSet) AsSlice

func (set *PropertyReferenceSet) AsSlice() []PropertyReference

AsSlice returns a slice (in random order) of all the property references in this set

func (*PropertyReferenceSet) Contains

func (set *PropertyReferenceSet) Contains(ref PropertyReference) bool

Contains returns true if the set contains the specified reference, false otherwise.

func (*PropertyReferenceSet) Except

Except returns a new PropertyReferenceSet containing only the items in this set that are not in the provided set

func (*PropertyReferenceSet) IsEmpty

func (set *PropertyReferenceSet) IsEmpty() bool

IsEmpty returns true if the set is empty, false otherwise.

type PropertyRemover

type PropertyRemover struct {
	// contains filtered or unexported fields
}

PropertyRemover is a utility for removing property definitions from objects

func NewPropertyRemover

func NewPropertyRemover() *PropertyRemover

NewPropertyRemover creates a new property remover for modifying objects

func (*PropertyRemover) Remove

Remove modifies the passed type definition by removing the passed property

type PropertySet

type PropertySet map[PropertyName]*PropertyDefinition

PropertySet wraps a set of property definitions, indexed by name, along with some convenience methods

func NewPropertySet

func NewPropertySet(properties ...*PropertyDefinition) PropertySet

NewPropertySet creates a new set of properties

func (PropertySet) Add

func (p PropertySet) Add(property *PropertyDefinition)

Add updates the set by including the provided property Any existing definition by that name will be overwritten if present

func (PropertySet) AsSlice

func (p PropertySet) AsSlice() []*PropertyDefinition

AsSlice returns all the properties in a slice, sorted alphabetically by name

func (PropertySet) ContainsProperty

func (p PropertySet) ContainsProperty(name PropertyName) bool

func (PropertySet) Copy

func (p PropertySet) Copy() PropertySet

Copy returns a new property set with the same properties as this one

func (PropertySet) Equals

func (p PropertySet) Equals(other ReadOnlyPropertySet, overrides EqualityOverrides) bool

func (PropertySet) Find

func (p PropertySet) Find(predicate func(*PropertyDefinition) bool) (*PropertyDefinition, bool)

func (PropertySet) FindAll

func (p PropertySet) FindAll(predicate func(*PropertyDefinition) bool) []*PropertyDefinition

func (PropertySet) First

func (p PropertySet) First() *PropertyDefinition

func (PropertySet) ForEach

func (p PropertySet) ForEach(f func(*PropertyDefinition))

func (PropertySet) ForEachError

func (p PropertySet) ForEachError(f func(*PropertyDefinition) error) error

func (PropertySet) Get

func (PropertySet) IsEmpty

func (p PropertySet) IsEmpty() bool

func (PropertySet) Len

func (p PropertySet) Len() int

type ReachableTypes

type ReachableTypes map[TypeName]int // int = depth

func (ReachableTypes) Contains

func (reachable ReachableTypes) Contains(tn TypeName) bool

type ReadOnlyPropertySet

type ReadOnlyPropertySet interface {
	AsSlice() []*PropertyDefinition
	ContainsProperty(name PropertyName) bool
	Get(name PropertyName) (*PropertyDefinition, bool)
	Find(predicate func(*PropertyDefinition) bool) (*PropertyDefinition, bool)
	FindAll(predicate func(*PropertyDefinition) bool) []*PropertyDefinition
	Copy() PropertySet
	Equals(other ReadOnlyPropertySet, overrides EqualityOverrides) bool
	First() *PropertyDefinition
	ForEach(func(def *PropertyDefinition))
	ForEachError(func(def *PropertyDefinition) error) error
	IsEmpty() bool
	Len() int
}

type ReadonlyObjectType

type ReadonlyObjectType interface {
	// Properties returns all the property definitions
	Properties() ReadOnlyPropertySet

	// Property returns the details of a specific property based on its unique case-sensitive name
	Property(name PropertyName) (*PropertyDefinition, bool)

	// EmbeddedProperties returns all the embedded properties
	// A sorted slice is returned to preserve immutability and provide determinism
	EmbeddedProperties() []*PropertyDefinition

	IsResource() bool
	Resources() TypeNameSet

	// Functions returns all the function implementations
	// A sorted slice is returned to preserve immutability and provide determinism
	Functions() []Function

	// HasFunctionWithName determines if this object has a function with the given name
	HasFunctionWithName(name string) bool

	TestCases() []TestCase
}

ReadonlyObjectType allows exposing an ObjectType for querying while prohibiting any modification. This is useful as a convenience to consumers for working with ObjectTypes, while ensuring they make any modifications using a TypeVisitor (or one of the Injectors based on TypeVisitor).

type ReadonlyTypeDefinitions

type ReadonlyTypeDefinitions interface {
	MustGetDefinition(name InternalTypeName) TypeDefinition
	GetDefinition(name InternalTypeName) (TypeDefinition, error)
}

ReadonlyTypeDefinitions is a restricted interface to indicate that the consumer won’t modify the contained types.

type ReadonlyTypeSet

type ReadonlyTypeSet interface {
	Contains(Type, EqualityOverrides) bool
	ForEach(func(t Type, ix int))
	ForEachError(func(t Type, ix int) error) error
	Len() int
	Single() (Type, bool)
	AsSlice() []Type
}

ReadonlyTypeSet is a readonly version of the TypeSet API.

type ReferenceGraph

type ReferenceGraph struct {
	// contains filtered or unexported fields
}

ReferenceGraph is a graph of references between types

func MakeReferenceGraph

func MakeReferenceGraph(roots TypeNameSet, references map[TypeName]TypeNameSet) ReferenceGraph

MakeReferenceGraph produces a new ReferenceGraph with the given roots and references

func MakeReferenceGraphWithResourcesAsRoots

func MakeReferenceGraphWithResourcesAsRoots(definitions TypeDefinitionSet) ReferenceGraph

MakeReferenceGraphWithResourcesAsRoots produces a ReferenceGraph for the given set of definitions, where the Resource types (and their ARM spec/status) are the roots.

func MakeReferenceGraphWithRoots

func MakeReferenceGraphWithRoots(roots TypeNameSet, definitions TypeDefinitionSet) ReferenceGraph

MakeReferenceGraphWithRoots produces a ReferenceGraph with the given roots, and references derived from the provided types collection.

func (ReferenceGraph) Connected

func (c ReferenceGraph) Connected() ReachableTypes

Connected returns the set of types that are reachable from the roots.

type RenamingVisitor

type RenamingVisitor struct {
	// contains filtered or unexported fields
}

RenamingVisitor is a visitor for performing simple TypeName renames

func NewRenamingVisitor

func NewRenamingVisitor(renames map[InternalTypeName]InternalTypeName) *RenamingVisitor

NewRenamingVisitor creates a new visitor which performs the renames specified

func NewRenamingVisitorFromLambda

func NewRenamingVisitorFromLambda(f func(name InternalTypeName) InternalTypeName) *RenamingVisitor

NewRenamingVisitorFromLambda creates a new visitor which performs renames using the specified lambda

func (*RenamingVisitor) Rename

func (r *RenamingVisitor) Rename(t Type) (Type, error)

Rename applies the renames to the Type whose definition is passed in.

func (*RenamingVisitor) RenameAll

func (r *RenamingVisitor) RenameAll(definitions TypeDefinitionSet) (TypeDefinitionSet, error)

RenameAll applies the renames to all the type definitions in the provided set

func (*RenamingVisitor) RenameDefinition

func (r *RenamingVisitor) RenameDefinition(td TypeDefinition) (TypeDefinition, error)

RenameDefinition applies the renames to the TypeDefinition’s Type and TypeName.

type ResourceOperation

type ResourceOperation string

type ResourceScope

type ResourceScope string

ResourceScope is the scope the resource is deployed at.

type ResourceSpecAndStatusResult

type ResourceSpecAndStatusResult struct {
	ResourceDef  TypeDefinition
	ResourceType *ResourceType

	SpecDef  TypeDefinition
	SpecType ReadonlyObjectType

	StatusDef  TypeDefinition
	StatusType ReadonlyObjectType
}

func ResolveResourceSpecAndStatus

func ResolveResourceSpecAndStatus(defs ReadonlyTypeDefinitions, resourceDef TypeDefinition) (*ResourceSpecAndStatusResult, error)

ResolveResourceSpecAndStatus takes a TypeDefinition that is a ResourceType and looks up its Spec and Status (as well as the TypeDefinition's corresponding to them) and returns a ResourceSpecAndStatusResult

type ResourceType

type ResourceType struct {
	InterfaceImplementer
	// contains filtered or unexported fields
}

ResourceType represents a Kubernetes CRD resource which has both spec (the user-requested state) and status (the current state)

func AsResourceType

func AsResourceType(aType Type) (*ResourceType, bool)

AsResourceType unwraps any wrappers around the provided type and returns either the underlying ResourceType and true, or a nil and false.

func MustBeResourceType

func MustBeResourceType(aType Type) *ResourceType

func NewAzureResourceType

func NewAzureResourceType(
	specType Type,
	statusType Type,
	typeName TypeName,
	scope ResourceScope,
	supportedOperations set.Set[ResourceOperation],
) *ResourceType

NewAzureResourceType defines a new resource type for Azure. It ensures that the resource has certain expected properties such as type and name. The typeName parameter is just used for logging.

func NewResourceType

func NewResourceType(specType Type, statusType Type) *ResourceType

NewResourceType defines a new resource type

func (*ResourceType) APIVersionEnumValue

func (resource *ResourceType) APIVersionEnumValue() EnumValue

APIVersionEnumValue returns the enum value representing the ARM API version of the resource.

func (*ResourceType) APIVersionTypeName

func (resource *ResourceType) APIVersionTypeName() InternalTypeName

APIVersionTypeName returns the type name of the API version

func (*ResourceType) ARMType

func (resource *ResourceType) ARMType() string

ARMType returns the ARM Type of the resource. The ARM type is something like Microsoft.Batch/batchAccounts

func (*ResourceType) ARMURI

func (resource *ResourceType) ARMURI() string

ARMURI gets the ARMURI

func (*ResourceType) AsDeclarations

func (resource *ResourceType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

AsDeclarations converts the resource type to a set of go declarations

func (*ResourceType) AsTypeExpr

func (resource *ResourceType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType always panics because a resource has no direct AST representation

func (*ResourceType) AsZero

AsZero always panics because a resource has no direct AST representation

func (*ResourceType) EmbeddedProperties

func (resource *ResourceType) EmbeddedProperties() []*PropertyDefinition

EmbeddedProperties returns all the embedded properties for this resource type An ordered slice is returned to preserve immutability and provide determinism

func (*ResourceType) Equals

func (resource *ResourceType) Equals(other Type, override EqualityOverrides) bool

Equals returns true if the other type is also a ResourceType and has Equal fields

func (*ResourceType) Functions

func (resource *ResourceType) Functions() []Function

Functions returns all the function implementations A sorted slice is returned to preserve immutability and provide determinism

func (*ResourceType) HasAPIVersion

func (resource *ResourceType) HasAPIVersion() bool

func (*ResourceType) HasFunctionWithName

func (resource *ResourceType) HasFunctionWithName(name string) bool

HasFunctionWithName determines if this resource has a function with the given name

func (*ResourceType) HasTestCases

func (resource *ResourceType) HasTestCases() bool

func (*ResourceType) IsStorageVersion

func (resource *ResourceType) IsStorageVersion() bool

IsStorageVersion returns true if the resource is a storage version

func (*ResourceType) MarkAsStorageVersion

func (resource *ResourceType) MarkAsStorageVersion() *ResourceType

MarkAsStorageVersion marks the resource as the Kubebuilder storage version

func (*ResourceType) Owner

func (resource *ResourceType) Owner() InternalTypeName

Owner returns the name of the owner type

func (*ResourceType) Properties

func (resource *ResourceType) Properties() ReadOnlyPropertySet

Properties returns all the properties from this resource type

func (*ResourceType) Property

func (resource *ResourceType) Property(name PropertyName) (*PropertyDefinition, bool)

Property returns the property and true if the named property is found, nil and false otherwise

func (*ResourceType) References

func (resource *ResourceType) References() TypeNameSet

References returns the types referenced by Status or Spec parts of the resource

func (*ResourceType) RequiredPackageReferences

func (resource *ResourceType) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns a list of packages required by this

func (*ResourceType) SchemeTypes

func (resource *ResourceType) SchemeTypes(name InternalTypeName) []TypeName

SchemeTypes returns the types represented by this resource which must be registered with the controller Scheme

func (*ResourceType) Scope

func (resource *ResourceType) Scope() ResourceScope

Scope returns the ResourceScope of the resource

func (*ResourceType) SpecType

func (resource *ResourceType) SpecType() Type

SpecType returns the type used for specification

func (*ResourceType) StatusType

func (resource *ResourceType) StatusType() Type

StatusType returns the type used for current status

func (*ResourceType) String

func (*ResourceType) String() string

String implements fmt.Stringer

func (*ResourceType) SupportedOperations

func (resource *ResourceType) SupportedOperations() set.Set[ResourceOperation]

SupportedOperations gets the set of supported operations SupportedOperations

func (*ResourceType) TestCases

func (resource *ResourceType) TestCases() []TestCase

TestCases returns a new slice containing all the test cases associated with this resource

func (*ResourceType) WithAPIVersion

func (resource *ResourceType) WithAPIVersion(
	apiVersionTypeName InternalTypeName,
	apiVersionEnumValue EnumValue,
) *ResourceType

WithAPIVersion returns a new ResourceType with the specified API version (type and value).

func (*ResourceType) WithARMType

func (resource *ResourceType) WithARMType(armType string) *ResourceType

WithARMType returns a new ResourceType containing the type of the ARM resource, such as Microsoft.Batch/batchAccounts

func (*ResourceType) WithARMURI

func (resource *ResourceType) WithARMURI(armURI string) *ResourceType

WithARMURI sets the ARMURI

func (*ResourceType) WithAnnotation

func (resource *ResourceType) WithAnnotation(annotation string) *ResourceType

WithAnnotation adds the annotation to the resource and returns a copy of the resource

func (*ResourceType) WithFunction

func (resource *ResourceType) WithFunction(function Function) *ResourceType

WithFunction creates a new Resource with a function (method) attached to it

func (*ResourceType) WithInterface

func (resource *ResourceType) WithInterface(iface *InterfaceImplementation) *ResourceType

WithInterface creates a new Resource with a function (method) attached to it

func (*ResourceType) WithOwner

func (resource *ResourceType) WithOwner(owner InternalTypeName) *ResourceType

WithOwner updates the owner of the resource and returns a copy of the resource

func (*ResourceType) WithScope

func (resource *ResourceType) WithScope(scope ResourceScope) *ResourceType

WithScope returns a new ResourceType with the specified scope

func (*ResourceType) WithSpec

func (resource *ResourceType) WithSpec(specType Type) *ResourceType

WithSpec returns a new resource that has the specified spec type

func (*ResourceType) WithStatus

func (resource *ResourceType) WithStatus(statusType Type) *ResourceType

WithStatus returns a new resource that has the specified status type

func (*ResourceType) WithSupportedOperations

func (resource *ResourceType) WithSupportedOperations(operations set.Set[ResourceOperation]) *ResourceType

WithSupportedOperations sets the SupportedOperations

func (*ResourceType) WithTestCase

func (resource *ResourceType) WithTestCase(testcase TestCase) *ResourceType

WithTestCase creates a new Resource that's a copy with an additional test case included

func (*ResourceType) WithoutFunction

func (resource *ResourceType) WithoutFunction(name string) *ResourceType

WithoutFunction returns a new Resource without the specific function

func (*ResourceType) WithoutFunctions

func (resource *ResourceType) WithoutFunctions() *ResourceType

WithoutFunctions creates a new Resource with no functions (useful for testing)

func (*ResourceType) WithoutInterface

func (resource *ResourceType) WithoutInterface(name TypeName) *ResourceType

func (*ResourceType) WriteDebugDescription

func (resource *ResourceType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder. builder receives the full description, including nested types. definitions is a dictionary for resolving named types.

type StringValidations

type StringValidations struct {
	MaxLength *int64
	MinLength *int64
	Patterns  []*regexp.Regexp
}

func (StringValidations) Equals

func (sv StringValidations) Equals(other Validations) bool

func (StringValidations) ToKubeBuilderValidations

func (sv StringValidations) ToKubeBuilderValidations() []KubeBuilderValidation

type SubPackageReference

type SubPackageReference struct {
	// contains filtered or unexported fields
}

func MakeCompatPackageReference

func MakeCompatPackageReference(pkg InternalPackageReference) SubPackageReference

MakeCompatPackageReference creates a subpackage reference using the standard name 'compat'. We use subpackages of this form to contain compatibility types we create to handle skipping properties.

func MakeSubPackageReference

func MakeSubPackageReference(
	name string,
	parent InternalPackageReference,
) SubPackageReference

MakeSubPackageReference creates a new SubPackageReference, representing a nested but distinct package. name is the name of the sub-package. parent is the parent package.

func (SubPackageReference) Base

Base returns the parent of this subpackge for DerivedPackageReference.

func (SubPackageReference) Equals

Equals returns true if the passed package reference is a sub-package reference with the same name and an equal parent.

func (SubPackageReference) FolderPath

func (s SubPackageReference) FolderPath() string

FolderPath returns the relative path to this package on disk.

func (SubPackageReference) Group

func (s SubPackageReference) Group() string

Group returns the group of the package reference. Subpackages have the same group as their parent.

func (SubPackageReference) GroupVersion

func (s SubPackageReference) GroupVersion() (string, string)

GroupVersion returns the group and version of the package reference. Subpackages have the same group/version as their parent.

func (SubPackageReference) ImportAlias

func (s SubPackageReference) ImportAlias(style PackageImportStyle) string

ImportAlias returns the import alias to use for this package reference.

func (SubPackageReference) ImportPath

func (s SubPackageReference) ImportPath() string

ImportPath returns the path to use when importing this package.

func (SubPackageReference) IsPreview

func (s SubPackageReference) IsPreview() bool

IsPreview returns true if the package reference is a preview version.

func (SubPackageReference) LocalPathPrefix

func (s SubPackageReference) LocalPathPrefix() string

func (SubPackageReference) PackageName

func (s SubPackageReference) PackageName() string

PackageName returns the name of the package.

func (SubPackageReference) PackagePath

func (s SubPackageReference) PackagePath() string

PackagePath returns the fully qualified package path.

func (SubPackageReference) Parent

Parent returns the parent package reference.

func (SubPackageReference) String

func (s SubPackageReference) String() string

String returns the string representation of the package reference, and implements fmt.Stringer.

func (SubPackageReference) Version

func (s SubPackageReference) Version() string

type TestCase

type TestCase interface {
	// Name returns the unique name of this test case
	Name() string

	// References returns the set of types to which this test case refers.
	References() TypeNameSet

	// RequiredImports returns a set of the package imports required by this test case
	RequiredImports() *PackageImportSet

	// AsFuncs renders the current test case and any supporting methods as Go abstract syntax trees
	// subject is the name of the type under test
	// codeGenerationContext contains reference material to use when generating
	AsFuncs(subject TypeName, codeGenerationContext *CodeGenerationContext) ([]dst.Decl, error)

	// Equals determines if this TestCase is equal to another one
	Equals(f TestCase, overrides EqualityOverrides) bool
}

TestCase represents a test we generate to ensure the generated code works as expected

type TestCaseContainer

type TestCaseContainer interface {
	TestCases() []TestCase
}

TestCaseContainer represents types that can contain test cases These types allow us to generate tests to verify the generated code does the right thing

func AsTestCaseContainer

func AsTestCaseContainer(theType Type) (TestCaseContainer, bool)

AsTestCaseContainer unwraps a type into a TestCaseContainer if it is one. Returns the container and true if the type is (or wraps) a TestContainer; nil and false if not. Only use this for readonly access. A TypeVisitor must be used for modifications to preserve type wrapping.

type TestCaseInjector

type TestCaseInjector struct {
	// contains filtered or unexported fields
}

TestCaseInjector is a utility for injecting function definitions into resources and objects

func NewTestCaseInjector

func NewTestCaseInjector() *TestCaseInjector

NewTestCaseInjector creates a new function injector for modifying resources and objects

func (*TestCaseInjector) Inject

func (fi *TestCaseInjector) Inject(def TypeDefinition, cases ...TestCase) (TypeDefinition, error)

Inject modifies the passed type definition by injecting the passed function

type TestFileDefinition

type TestFileDefinition struct {
	// contains filtered or unexported fields
}

TestFileDefinition defines the content of a test file we're generating

func NewTestFileDefinition

func NewTestFileDefinition(
	packageRef InternalPackageReference,
	definitions []TypeDefinition,
	generatedPackages map[InternalPackageReference]*PackageDefinition,
) *TestFileDefinition

NewTestFileDefinition creates a file definition containing test cases from the specified definitions packageRef is the package to which this file belongs. definitions are the type definitions to include in this specific file. generatedPackages is a map of all other packages being generated (to allow for cross-package references).

func (*TestFileDefinition) AsAst

func (file *TestFileDefinition) AsAst() (*dst.File, error)

AsAst generates an array of declarations for the content of the file

func (*TestFileDefinition) TestCaseCount

func (file *TestFileDefinition) TestCaseCount() int

TestCaseCount returns the number of test cases included in the file

type Type

type Type interface {
	// RequiredPackageReferences returns a set of packages imports required by this type.
	// The set should *not* include the package in which the type is defined.
	RequiredPackageReferences() *PackageReferenceSet

	// References returns the names of all types that this type
	// references. For example, an Array of Persons references a
	// Person.
	References() TypeNameSet

	// AsTypeExpr renders as the Go abstract syntax tree to reference this type
	// (Yes, this returns dst.Expr but that is what the Go 'dst' package uses
	// for type references).
	AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

	// AsDeclarations renders as a Go abstract syntax tree for a declaration
	AsDeclarations(codeGenerationContext *CodeGenerationContext, declContext DeclarationContext) ([]dst.Decl, error)

	// AsZero renders an expression for the "zero" value of the type
	// definitions allows TypeName to resolve to the underlying type
	// ctx allows current imports to be correctly identified where needed
	AsZero(definitions TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

	// Equals returns true if the passed type is the same as this one, false otherwise
	Equals(t Type, overrides EqualityOverrides) bool

	// Stringer ensures all Type implementations have a printable version for debugging/user info.
	// This doesn't need to be a full representation of the type.
	fmt.Stringer

	// WriteDebugDescription adds a description of the current type to the passed builder.
	// builder receives the full description, including nested types.
	// definitions is a dictionary for resolving named types.
	WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)
}

Type represents something that is a Go type

func BuildAllOfType

func BuildAllOfType(types ...Type) Type

BuildAllOfType is a smart constructor for AllOfType, maintaining the invariants. If only one unique type is passed, then the result will be that type, not an AllOf.

func IdentityVisitOfAllOfType

func IdentityVisitOfAllOfType[C any](this *TypeVisitor[C], it *AllOfType, ctx C) (Type, error)

func IdentityVisitOfArrayType

func IdentityVisitOfArrayType[C any](this *TypeVisitor[C], it *ArrayType, ctx C) (Type, error)

func IdentityVisitOfEnumType

func IdentityVisitOfEnumType[C any](_ *TypeVisitor[C], it *EnumType, _ C) (Type, error)

func IdentityVisitOfErroredType

func IdentityVisitOfErroredType[C any](this *TypeVisitor[C], e *ErroredType, ctx C) (Type, error)

func IdentityVisitOfFlaggedType

func IdentityVisitOfFlaggedType[C any](this *TypeVisitor[C], ft *FlaggedType, ctx C) (Type, error)

func IdentityVisitOfInterfaceType

func IdentityVisitOfInterfaceType[C any](_ *TypeVisitor[C], it *InterfaceType, _ C) (Type, error)

func IdentityVisitOfMapType

func IdentityVisitOfMapType[C any](this *TypeVisitor[C], it *MapType, ctx C) (Type, error)

func IdentityVisitOfObjectType

func IdentityVisitOfObjectType[C any](this *TypeVisitor[C], it *ObjectType, ctx C) (Type, error)

func IdentityVisitOfOneOfType

func IdentityVisitOfOneOfType[C any](this *TypeVisitor[C], it *OneOfType, ctx C) (Type, error)

func IdentityVisitOfOptionalType

func IdentityVisitOfOptionalType[C any](this *TypeVisitor[C], it *OptionalType, ctx C) (Type, error)

func IdentityVisitOfPrimitiveType

func IdentityVisitOfPrimitiveType[C any](_ *TypeVisitor[C], it *PrimitiveType, _ C) (Type, error)

func IdentityVisitOfResourceType

func IdentityVisitOfResourceType[C any](this *TypeVisitor[C], it *ResourceType, ctx C) (Type, error)

func IdentityVisitOfTypeName

func IdentityVisitOfTypeName[C any](_ *TypeVisitor[C], it TypeName, _ C) (Type, error)

func IdentityVisitOfValidatedType

func IdentityVisitOfValidatedType[C any](this *TypeVisitor[C], v *ValidatedType, ctx C) (Type, error)

func IgnoringErrors

func IgnoringErrors(t Type) Type

IgnoringErrors returns the type stripped of any ErroredType wrapper

func NewOptionalType

func NewOptionalType(element Type) Type

NewOptionalType creates a new optional type that may or may not have the specified 'element' type

func OrderedIdentityVisitOfObjectType

func OrderedIdentityVisitOfObjectType[C any](this *TypeVisitor[C], it *ObjectType, ctx C) (Type, error)

func Unwrap

func Unwrap(aType Type) Type

Unwrap unwraps the type and returns the underlying unwrapped type

type TypeAssociation

type TypeAssociation map[InternalTypeName]InternalTypeName

TypeAssociation defines an association between two internal types

func (TypeAssociation) Equals

func (ts TypeAssociation) Equals(other TypeAssociation) bool

type TypeDefinition

type TypeDefinition struct {
	// contains filtered or unexported fields
}

TypeDefinition is a name paired with a type

func IdentityAfterVisit

func IdentityAfterVisit[C any](_ TypeDefinition, updated TypeDefinition, _ C) (TypeDefinition, error)

IdentityAfterVisit is the default AfterVisit function for TypeWalker. It returns the TypeDefinition from Visit unmodified.

func MakeTypeDefinition

func MakeTypeDefinition(name InternalTypeName, theType Type) TypeDefinition

func ResolveResourceSpecDefinition

func ResolveResourceSpecDefinition(defs ReadonlyTypeDefinitions, resourceType *ResourceType) (TypeDefinition, error)

ResolveResourceSpecDefinition finds the TypeDefinition associated with the resource Spec.

func ResolveResourceStatusDefinition

func ResolveResourceStatusDefinition(defs ReadonlyTypeDefinitions, resourceType *ResourceType) (TypeDefinition, error)

ResolveResourceStatusDefinition finds the TypeDefinition associated with the resource Status.

func (TypeDefinition) ApplyObjectTransformation

func (def TypeDefinition) ApplyObjectTransformation(transform func(*ObjectType) (Type, error)) (TypeDefinition, error)

ApplyObjectTransformation applies a specific transformation to the ObjectType contained by this definition, returning a new definition If the definition does not contain an object, an error will be returned

func (TypeDefinition) ApplyObjectTransformations

func (def TypeDefinition) ApplyObjectTransformations(transforms ...func(*ObjectType) (*ObjectType, error)) (TypeDefinition, error)

ApplyObjectTransformations applies multiple transformations to the ObjectType contained by this definition, returning a new definition. If the definition does not contain an object, an error will be returned The transformations are constrained to return ObjectType results to allow them to be chained together.

func (TypeDefinition) AsDeclarations

func (def TypeDefinition) AsDeclarations(codeGenerationContext *CodeGenerationContext) ([]dst.Decl, error)

func (TypeDefinition) Description

func (def TypeDefinition) Description() []string

Description returns the description to be attached to this type definition (as a comment) We return a new slice to preserve immutability

func (TypeDefinition) HasTestCases

func (def TypeDefinition) HasTestCases() bool

func (TypeDefinition) Name

func (def TypeDefinition) Name() InternalTypeName

Name returns the name being associated with the type

func (TypeDefinition) References

func (def TypeDefinition) References() TypeNameSet

func (TypeDefinition) RequiredPackageReferences

func (def TypeDefinition) RequiredPackageReferences() *PackageReferenceSet

RequiredPackageReferences returns a list of packages required by this type

func (TypeDefinition) Type

func (def TypeDefinition) Type() Type

Type returns the type being associated with the name

func (TypeDefinition) WithDescription

func (def TypeDefinition) WithDescription(desc ...string) TypeDefinition

WithDescription replaces the description of the definition with a new one (if any)

func (TypeDefinition) WithName

func (def TypeDefinition) WithName(typeName InternalTypeName) TypeDefinition

WithName returns an updated TypeDefinition with the specified name

func (TypeDefinition) WithType

func (def TypeDefinition) WithType(t Type) TypeDefinition

WithType returns an updated TypeDefinition with the specified type

type TypeDefinitionSet

type TypeDefinitionSet map[InternalTypeName]TypeDefinition

TypeDefinitionSet is a map of TypeName to TypeDefinition, representing a set of type definitions.

func FindConnectedDefinitions

func FindConnectedDefinitions(definitions TypeDefinitionSet, roots TypeDefinitionSet) (TypeDefinitionSet, error)

FindConnectedDefinitions finds all types reachable from the provided definitions TODO: This is very similar to ReferenceGraph.Connected.

func FindResourceDefinitions

func FindResourceDefinitions(definitions TypeDefinitionSet) TypeDefinitionSet

FindResourceDefinitions walks the provided set of TypeDefinitions and returns all the resource definitions

func FindSpecConnectedDefinitions

func FindSpecConnectedDefinitions(definitions TypeDefinitionSet) (TypeDefinitionSet, error)

FindSpecConnectedDefinitions finds all spec definitions and all types referenced by those spec definitions. This differs from FindSpecDefinitions in that it finds not only the top level spec definitions but also the types which the top level types are built out of.

func FindSpecDefinitions

func FindSpecDefinitions(definitions TypeDefinitionSet) TypeDefinitionSet

FindSpecDefinitions walks the provided set of TypeDefinitions and returns all the spec definitions

func FindStatusConnectedDefinitions

func FindStatusConnectedDefinitions(definitions TypeDefinitionSet) (TypeDefinitionSet, error)

FindStatusConnectedDefinitions finds all status definitions and all types referenced by those spec definitions. This differs from FindStatusDefinitions in that it finds not only the top level status definitions but also the types which the top level types are built out of.

func FindStatusDefinitions

func FindStatusDefinitions(definitions TypeDefinitionSet) TypeDefinitionSet

FindStatusDefinitions walks the provided set of TypeDefinitions and returns all the status definitions

func MakeTypeDefinitionSet

func MakeTypeDefinitionSet(types map[InternalTypeName]Type) TypeDefinitionSet

MakeTypeDefinitionSet makes it easier to declare a TypeDefinitionSet from a map

func MakeTypeDefinitionSetFromDefinitions

func MakeTypeDefinitionSetFromDefinitions(definitions ...TypeDefinition) TypeDefinitionSet

MakeTypeDefinitionSetFromDefinitions makes it easier to declare a TypeDefinitionSet from a collection of definitions

func TypesDisjointUnion

func TypesDisjointUnion(s1 TypeDefinitionSet, s2 TypeDefinitionSet) TypeDefinitionSet

TypesDisjointUnion merges this and other, with a safety check that no type is overwritten. If an attempt is made to overwrite a type, this function panics

func (TypeDefinitionSet) Add

func (set TypeDefinitionSet) Add(def TypeDefinition)

Add adds a type to the set, with safety check that it has not already been defined

func (TypeDefinitionSet) AddAll

func (set TypeDefinitionSet) AddAll(otherDefinitions ...TypeDefinition)

AddAll adds multiple definitions to the set, with the same safety check as Add() to panic if a duplicate is included

func (TypeDefinitionSet) AddAllAllowDuplicates

func (set TypeDefinitionSet) AddAllAllowDuplicates(otherDefinitions []TypeDefinition) error

AddAllAllowDuplicates adds multiple definitions to the set. Multiple adds of a type with the same shape are allowed, but attempting to add two types with the same name but different shape will trigger an error.

func (TypeDefinitionSet) AddAllowDuplicates

func (set TypeDefinitionSet) AddAllowDuplicates(def TypeDefinition) error

AddAllowDuplicates attempts to add the specified definition to the collection of types. Multiple adds of a type with the same shape are allowed, but attempting to add two types with the same name but different shape will trigger an error.

func (TypeDefinitionSet) AddTypes

func (set TypeDefinitionSet) AddTypes(definitions TypeDefinitionSet)

AddTypes adds multiple types to the set, with the same safety check as Add() to panic if a duplicate is included

func (TypeDefinitionSet) AddTypesAllowDuplicates

func (set TypeDefinitionSet) AddTypesAllowDuplicates(definitions TypeDefinitionSet) error

AddTypesAllowDuplicates adds multiple types to the set. Multiple adds of a type with the same shape are allowed, but attempting to add two types with the same name but different shape will trigger an error.

func (TypeDefinitionSet) AsSlice

func (set TypeDefinitionSet) AsSlice() []TypeDefinition

AsSlice creates a new slice containing all the definitions

func (TypeDefinitionSet) Contains

func (set TypeDefinitionSet) Contains(name InternalTypeName) bool

Contains returns true if the set contains a definition for the specified name

func (TypeDefinitionSet) Copy

Copy makes an independent copy of this set of types

func (TypeDefinitionSet) Except

func (set TypeDefinitionSet) Except(definitions TypeDefinitionSet) TypeDefinitionSet

Except returns a new set of types including only those not defined in otherTypes

func (TypeDefinitionSet) FullyResolve

func (set TypeDefinitionSet) FullyResolve(t Type) (Type, error)

FullyResolve turns something that might be a TypeName into something that isn't

func (TypeDefinitionSet) FullyResolveDefinition

func (set TypeDefinitionSet) FullyResolveDefinition(def TypeDefinition) (TypeDefinition, error)

FullyResolveDefinition turns a definition that might point to a TypeName that into a definition something that doesn't

func (TypeDefinitionSet) GetDefinition

func (set TypeDefinitionSet) GetDefinition(name InternalTypeName) (TypeDefinition, error)

GetDefinition attempts to look up a type definition based on the name. An error is returned if it cannot be found

func (TypeDefinitionSet) Intersect

func (set TypeDefinitionSet) Intersect(definitions TypeDefinitionSet) TypeDefinitionSet

Intersect returns a new set of types including only those defined in both types and otherTypes.

func (TypeDefinitionSet) MustGetDefinition

func (set TypeDefinitionSet) MustGetDefinition(name InternalTypeName) TypeDefinition

MustGetDefinition looks up a type definition and panics if it cannot be found

func (TypeDefinitionSet) Names

func (set TypeDefinitionSet) Names() TypeNameSet

Names returns the names of all types in the set

func (TypeDefinitionSet) OverlayWith

OverlayWith creates a new set containing all the type definitions from both this and the provided set. Any name collisions are resolved in favour of the provided set. Returns a new independent set, leaving the original unmodified.

func (TypeDefinitionSet) Process

func (set TypeDefinitionSet) Process(transformation func(definition TypeDefinition) (*TypeDefinition, error)) (TypeDefinitionSet, error)

Process applies a func to transform all members of this set of type definitions, returning a new set of type definitions containing the results of the transformation, or possibly an error Only definitions returned by the func will be included in the results of the function. The func may return a nil TypeDefinition if it doesn't want to include anything in the output set.

func (TypeDefinitionSet) ResolveEnumDefinition

func (set TypeDefinitionSet) ResolveEnumDefinition(definition *TypeDefinition) (EnumType, bool)

ResolveEnumDefinition returns true if the passed definition is for an Enum type or names an Enum type; false otherwise.

func (TypeDefinitionSet) ResolveEnumType

func (set TypeDefinitionSet) ResolveEnumType(aType Type) (EnumType, bool)

ResolveEnumType returns true if the passed type is an enum type or names an enum type; false otherwise.

func (TypeDefinitionSet) ResolveObjectType

func (set TypeDefinitionSet) ResolveObjectType(aType Type) (*ObjectType, bool)

ResolveObjectType returns the underlying resource type if the definition contains one or names one

func (TypeDefinitionSet) ResolveResourceSpecAndStatus

func (set TypeDefinitionSet) ResolveResourceSpecAndStatus(resourceDef TypeDefinition) (*ResourceSpecAndStatusResult, error)

ResolveResourceSpecAndStatus takes a TypeDefinition that is a ResourceType and looks up its Spec and Status (as well as the TypeDefinition's corresponding to them) and returns a ResourceSpecAndStatusResult

func (TypeDefinitionSet) ResolveResourceSpecDefinition

func (set TypeDefinitionSet) ResolveResourceSpecDefinition(resourceType *ResourceType) (TypeDefinition, error)

ResolveResourceSpecDefinition finds the TypeDefinition associated with the resource Spec.

func (TypeDefinitionSet) ResolveResourceStatusDefinition

func (set TypeDefinitionSet) ResolveResourceStatusDefinition(resourceType *ResourceType) (TypeDefinition, error)

ResolveResourceStatusDefinition finds the TypeDefinition associated with the resource Status.

func (TypeDefinitionSet) ResolveResourceType

func (set TypeDefinitionSet) ResolveResourceType(aType Type) (*ResourceType, bool)

ResolveResourceType returns the underlying resource type if the definition contains one or names one

func (TypeDefinitionSet) Where

func (set TypeDefinitionSet) Where(predicate func(definition TypeDefinition) bool) TypeDefinitionSet

Where returns a new set of types including only those that satisfy the predicate

type TypeFlag

type TypeFlag string

func (TypeFlag) ApplyTo

func (f TypeFlag) ApplyTo(t Type) *FlaggedType

ApplyTo applies the tag to the provided type

func (TypeFlag) IsOn

func (f TypeFlag) IsOn(theType Type) bool

IsOn returns true if t is or contains a flagged type that has this flag

func (TypeFlag) RemoveFrom

func (f TypeFlag) RemoveFrom(t Type) (Type, error)

RemoveFrom applies the tag to the provided type

func (TypeFlag) String

func (f TypeFlag) String() string

String renders the tag as a string

type TypeMerger

type TypeMerger struct {
	// contains filtered or unexported fields
}

TypeMerger is like a visitor for 2 types.

Conceptually it takes (via Add) a list of functions of the form:

func ([ctx interface{},] left {some Type}, right {some Type}) (Type, error)

where `left` and `right` can be concrete types that implement the `Type` interface.

When `TypeMerger.Merge(Type, Type)` is invoked, it will iterate through the provided functions and invoke the first one that matches the concrete types passed. If none match then the fallback provided to `NewTypeMerger` will be invoked.

The `ctx` argument can optionally be used to “smuggle” additional data down the call-chain.

func NewTypeMerger

func NewTypeMerger(fallback MergerFunc) *TypeMerger

func (*TypeMerger) Add

func (m *TypeMerger) Add(mergeFunc interface{})

Add adds a handler function to be invoked if applicable. See the docs on TypeMerger above for a full explanation.

func (*TypeMerger) AddUnordered

func (m *TypeMerger) AddUnordered(mergeFunc interface{})

AddUnordered adds a handler function that doesn’t care what order the two type parameters are in. e.g. if it has type `(A, B) -> (Type, error)`, it can match either `(A, B)` or `(B, A)`. This is useful when the merger is symmetric and handles two different types.

func (*TypeMerger) Merge

func (m *TypeMerger) Merge(left, right Type) (Type, error)

Merge merges the two types according to the provided mergers and fallback, with nil context

func (*TypeMerger) MergeWithContext

func (m *TypeMerger) MergeWithContext(ctx interface{}, left, right Type) (Type, error)

MergeWithContext merges the two types according to the provided mergers and fallback, with the provided context

type TypeName

type TypeName interface {
	Type
	Name() string
	PackageReference() PackageReference
}

func AsTypeName

func AsTypeName(aType Type) (TypeName, bool)

AsTypeName unwraps any wrappers around the provided type and returns either the underlying TypeName and true, or a blank and false.

type TypeNameSet

type TypeNameSet map[TypeName]struct{}

TypeNameSet stores type names in no particular order without duplicates.

func CollectARMSpecAndStatusDefinitions

func CollectARMSpecAndStatusDefinitions(definitions TypeDefinitionSet) TypeNameSet

CollectARMSpecAndStatusDefinitions returns a TypeNameSet of all the ARM spec definitions passed in.

func CollectUnreferencedTypes

func CollectUnreferencedTypes(defs TypeDefinitionSet) TypeNameSet

func NewTypeNameSet

func NewTypeNameSet(initial ...TypeName) TypeNameSet

NewTypeNameSet makes a TypeNameSet containing the specified names. If no elements are passed it might be nil.

func SetUnion

func SetUnion(s1, s2 TypeNameSet) TypeNameSet

SetUnion returns a new set with all of the names in s1 or s2.

func (TypeNameSet) Add

func (ts TypeNameSet) Add(val TypeName)

Add includes the passed name in the set

func (TypeNameSet) AddAll

func (ts TypeNameSet) AddAll(other TypeNameSet)

AddAll adds the provided TypeNameSet to the set

func (TypeNameSet) Contains

func (ts TypeNameSet) Contains(val TypeName) bool

Contains returns whether this name is in the set. Works for nil sets too.

func (TypeNameSet) ContainsAll

func (ts TypeNameSet) ContainsAll(other TypeNameSet) bool

ContainsAll returns whether all the names are in the set. Works for nil sets too.

func (TypeNameSet) ContainsAny

func (ts TypeNameSet) ContainsAny(other TypeNameSet) bool

ContainsAny returns whether any item of other is contained in the set. Works for nil sets too.

func (TypeNameSet) Copy

func (ts TypeNameSet) Copy() TypeNameSet

func (TypeNameSet) Equals

func (ts TypeNameSet) Equals(set TypeNameSet) bool

func (TypeNameSet) Remove

func (ts TypeNameSet) Remove(val TypeName)

Remove removes the specified item if it is in the set. If it is not in the set this is a no-op.

func (TypeNameSet) Single

func (ts TypeNameSet) Single() TypeName

Single returns the single TypeName in the set. This panics if there is not a single item in the set.

type TypeSet

type TypeSet struct {
	// contains filtered or unexported fields
}

TypeSet represents a set of types

func MakeTypeSet

func MakeTypeSet(types ...Type) TypeSet

MakeTypeSet makes a new TypeSet containing the given types

func (*TypeSet) Add

func (ts *TypeSet) Add(t Type) bool

Add adds the type to the set if it does not already exist and returns if it was added or not

func (TypeSet) AsSlice

func (ts TypeSet) AsSlice() []Type

AsSlice returns the content of this set as a slice

func (TypeSet) Contains

func (ts TypeSet) Contains(t Type, overrides EqualityOverrides) bool

Contains checks if the set already contains the type

func (TypeSet) Copy

func (ts TypeSet) Copy() TypeSet

Copy returns a copy of this set that can then be modified.

func (TypeSet) Equals

func (ts TypeSet) Equals(other TypeSet, overrides ...EqualityOverrides) bool

Equals returns true if both sets contain the same types

func (TypeSet) ForEach

func (ts TypeSet) ForEach(action func(t Type, ix int))

ForEach executes the action for each type in the set this works around not having `range` on custom types

func (TypeSet) ForEachError

func (ts TypeSet) ForEachError(action func(t Type, ix int) error) error

ForEachError executes the action for each type in the set, with the possibility to fail. This works around not having `range` on custom types.

func (TypeSet) Len

func (ts TypeSet) Len() int

Len returns the number of items in the set

func (*TypeSet) Remove

func (ts *TypeSet) Remove(t Type) bool

Remove removes the type from the set if it exists, and returns whether it was removed or not

func (TypeSet) Single

func (ts TypeSet) Single() (Type, bool)

Single returns the only item in the set, and true, if it contains exactly one; otherwise it returns nil and false.

type TypeVisitor

type TypeVisitor[C any] struct {
	// contains filtered or unexported fields
}

TypeVisitor represents a visitor for a tree of types. The `ctx` argument can be used to “smuggle” additional data down the call-chain.

func (*TypeVisitor[C]) Visit

func (tv *TypeVisitor[C]) Visit(t Type, ctx C) (Type, error)

Visit invokes the appropriate VisitX on TypeVisitor

func (*TypeVisitor[C]) VisitDefinition

func (tv *TypeVisitor[C]) VisitDefinition(td TypeDefinition, ctx C) (TypeDefinition, error)

VisitDefinition invokes the TypeVisitor on both the name and type of the definition NB: this is only valid if visitTypeName returns a TypeName and not generally a Type

func (*TypeVisitor[C]) VisitDefinitions

func (tv *TypeVisitor[C]) VisitDefinitions(definitions TypeDefinitionSet, ctx C) (TypeDefinitionSet, error)

func (*TypeVisitor[C]) VisitInternalTypeName

func (tv *TypeVisitor[C]) VisitInternalTypeName(name InternalTypeName, ctx C) (InternalTypeName, error)

VisitInternalTypeName invokes the TypeVisitor on the InternalTypeName, returning an InternalTypeName. name is the InternalTypeName to visit. This is a convenience method for when an InternalTypeName is expected as the result.

type TypeVisitorBuilder

type TypeVisitorBuilder[C any] struct {
	VisitInternalTypeName any
	VisitExternalTypeName any
	VisitOneOfType        any
	VisitAllOfType        any
	VisitArrayType        any
	VisitPrimitive        any
	VisitObjectType       any
	VisitMapType          any
	VisitOptionalType     any
	VisitEnumType         any
	VisitResourceType     any
	VisitFlaggedType      any
	VisitValidatedType    any
	VisitErroredType      any
	VisitInterfaceType    any
}

TypeVisitorBuilder provides a flexible way to create a TypeVisitor. C is the type to use for the context parameter in each visit method. Fields should be initialized with funcs matching one of the following forms:

func(this *TypeVisitor, it <sometype>, ctx any) (Type, error) func(it <sometype>) (Type, error) func(it <sometype>) Type

o Must always return Type, and optionally an error o <sometype> must match the type for the field being initialized

Some examples:

VisitInternalTypeName = func(it InternalTypeName) Type // Works VisitInternalTypeName = func(this TypeVisitor, it InternalTypeName, ctx C) (Type, error) // Works VisitInternalTypeName = func(it *ObjectType) Type // Fails - parameter is not a TypeName VisitInternalTypeName = func(it TypeName) TypeName // Fails - return type is not Type

VisitObjectType = func(it *ObjectType) Type // Works VisitObjectType = func(this TypeVisitor, it *ObjectType, ctx C) (Type, error) // Works VisitObjectType = func(it TypeName) Type // Fails - parameter is not an *ObjectType VisitObjectType = func(this TypeVisitor, it TypeName, ctx C) (ObjectType, error) // Fails -return is not Type

func (TypeVisitorBuilder[C]) Build

func (b TypeVisitorBuilder[C]) Build() TypeVisitor[C]

type TypeWalker

type TypeWalker[C any] struct {

	// MakeContext is called before any type is visited - including before the root type is visited. It is given the current context and returns
	// a new context for use in the upcoming Visit. When visiting the root type, the ctx parameter is always nil.
	MakeContext func(it InternalTypeName, ctx C) (C, error)

	// AfterVisit is called after the type walker has applied the visitor to a TypeDefinition.
	AfterVisit func(original TypeDefinition, updated TypeDefinition, ctx C) (TypeDefinition, error)

	// ShouldRemoveCycle is called if a cycle is detected. If true is returned the cycle will be pruned, otherwise it will be preserved as-is.
	ShouldRemoveCycle func(def TypeDefinition, ctx C) (bool, error)
	// contains filtered or unexported fields
}

TypeWalker performs a depth first traversal across the types provided, applying the visitor to each TypeDefinition. MakeContext is called before each visit, and AfterVisit is called after each visit. ShouldRemoveCycle is called if a cycle is detected.

func NewTypeWalker

func NewTypeWalker[C any](allDefs TypeDefinitionSet, visitor TypeVisitor[C]) *TypeWalker[C]

NewTypeWalker returns a TypeWalker. The provided visitor visitTypeName function must return a TypeName and visitObjectType must return an ObjectType or calls to Walk will panic.

func (*TypeWalker[C]) Walk

func (t *TypeWalker[C]) Walk(def TypeDefinition) (TypeDefinitionSet, error)

Walk returns a type definition collection constructed by applying the Visitor to each type in the graph of types reachable from the provided TypeDefinition 'def'. TypeDefinitionSet are visited in a depth-first order. Cycles are not followed (so each type in a cycle will be visited only once).

type ValidatedType

type ValidatedType struct {
	// contains filtered or unexported fields
}

ValidatedType is used for schema validation attributes

func NewValidatedType

func NewValidatedType(element Type, validations Validations) *ValidatedType

func (*ValidatedType) AsDeclarations

func (v *ValidatedType) AsDeclarations(
	codeGenerationContext *CodeGenerationContext,
	declContext DeclarationContext,
) ([]dst.Decl, error)

func (*ValidatedType) AsTypeExpr

func (v *ValidatedType) AsTypeExpr(codeGenerationContext *CodeGenerationContext) (dst.Expr, error)

AsType panics because validated types should always be named

func (*ValidatedType) AsZero

func (v *ValidatedType) AsZero(definitions TypeDefinitionSet, ctx *CodeGenerationContext) dst.Expr

AsZero returns the zero for our underlying type

func (*ValidatedType) ElementType

func (v *ValidatedType) ElementType() Type

func (*ValidatedType) Equals

func (v *ValidatedType) Equals(t Type, overrides EqualityOverrides) bool

func (*ValidatedType) References

func (v *ValidatedType) References() TypeNameSet

func (*ValidatedType) RequiredPackageReferences

func (v *ValidatedType) RequiredPackageReferences() *PackageReferenceSet

func (*ValidatedType) String

func (v *ValidatedType) String() string

func (ValidatedType) Unwrap

func (v ValidatedType) Unwrap() Type

Unwrap returns the type contained within the validated type

func (*ValidatedType) Validations

func (v *ValidatedType) Validations() Validations

func (*ValidatedType) WithElement

func (v *ValidatedType) WithElement(t Type) Type

func (*ValidatedType) WithType

func (v *ValidatedType) WithType(newElement Type) *ValidatedType

func (ValidatedType) WriteDebugDescription

func (v ValidatedType) WriteDebugDescription(builder *strings.Builder, currentPackage InternalPackageReference)

WriteDebugDescription adds a description of the current type to the passed builder builder receives the full description, including nested types definitions is a dictionary for resolving named types

type Validations

type Validations interface {
	Equals(other Validations) bool
	ToKubeBuilderValidations() []KubeBuilderValidation
}

type ValueFunction

type ValueFunction interface {
	Function

	// ReturnType specifies the return type of the function
	ReturnType() Type
}

ValueFunction defines a function that returns a single value suitable for storing in a property

type Visibility

type Visibility string

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL