gvk

package
v0.2.0-beta.21 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

GVK - Group/Version/Kind Type System

Go Reference

The gvk package provides shared infrastructure for Group, Version, Kind (GVK) based type systems within Kure. It implements version-aware type registration, unmarshaling, and conversion similar to Kubernetes' own GVK system but tailored for Kure's needs.

Core Components

Component Description
GVK Group, Version, Kind tuple that uniquely identifies a type
Registry[T] Type-safe registration and factory pattern for GVK types
TypedWrapper[T] Automatic type detection during YAML unmarshaling
ConversionRegistry Version conversion system for type migrations

Usage

Each block below is the body of an Example function in example_test.go, which go test runs: it imports this package as gvk, gopkg.in/yaml.v3 (the YAML library whose yaml.Node the wrapper decodes from), and fmt for the line that prints what the example built. The same file declares the example spec types MyConfigType (one Replicas int field), and OldType and NewType, whose one field is Name and DisplayName respectively.

Type Registration
myGVK := gvk.GVK{
    Group:   "generators.gokure.dev",
    Version: "v1alpha1",
    Kind:    "MyGenerator",
}

registry := gvk.NewRegistry[MyConfigType]()
registry.Register(myGVK, func() MyConfigType {
    return MyConfigType{Replicas: 1}
})

instance, err := registry.Create(myGVK)
if err != nil {
    panic(err)
}
fmt.Println(myGVK.APIVersion(), instance.Replicas)
YAML Unmarshaling with Type Detection
registry := gvk.NewRegistry[MyConfigType]()
registry.Register(gvk.GVK{Group: "generators.gokure.dev", Version: "v1alpha1", Kind: "MyGenerator"},
    func() MyConfigType { return MyConfigType{} })

data := []byte(`
apiVersion: generators.gokure.dev/v1alpha1
kind: MyGenerator
metadata:
  name: web
spec:
  replicas: 3
`)

wrapper := gvk.NewTypedWrapper(registry)
if err := yaml.Unmarshal(data, wrapper); err != nil {
    panic(err)
}
// wrapper.Spec contains the correctly typed instance
fmt.Println(wrapper.GetName(), wrapper.Spec.Replicas)
Version Conversion

A converter receives and returns any: RegisterFunc takes a ConversionFunc, and Register takes any Converter.

oldGVK := gvk.GVK{Group: "generators.gokure.dev", Version: "v1alpha1", Kind: "MyGenerator"}
newGVK := gvk.GVK{Group: "generators.gokure.dev", Version: "v1beta1", Kind: "MyGenerator"}

conversions := gvk.NewConversionRegistry()
conversions.RegisterFunc(oldGVK, newGVK, func(from any) (any, error) {
    old := from.(OldType)
    return NewType{DisplayName: old.Name}, nil
})

converted, err := conversions.Convert(oldGVK, newGVK, OldType{Name: "web"})
if err != nil {
    panic(err)
}
fmt.Printf("%+v\n", converted)

Key Interfaces

  • VersionedType - Types that carry GVK metadata
  • NamedType - Types with a name field
  • NamespacedType - Types with a namespace field
  • MetadataType - Types with full metadata (name + namespace)
  • Convertible - Types that support version conversion

Documentation

Overview

Package gvk provides shared infrastructure for Group, Version, Kind (GVK) based type systems within Kure.

This package implements the foundational components needed for version-aware type registration, unmarshaling, and conversion - similar to Kubernetes' own GVK system but tailored for Kure's specific needs.

Core Components

GVK represents the Group, Version, Kind tuple that uniquely identifies a type:

gvk := GVK{
    Group:   "generators.gokure.dev",
    Version: "v1alpha1",
    Kind:    "AppWorkload",
}

Registry provides type-safe registration and factory pattern for GVK types:

registry := NewRegistry[MyConfigType]()
registry.Register(gvk, func() MyConfigType {
    return MyConfigType{}
})

instance, err := registry.Create(gvk)

TypedWrapper enables automatic type detection during YAML unmarshaling:

wrapper := NewTypedWrapper(registry)
err := yaml.Unmarshal(data, wrapper)
// wrapper.Spec contains the correctly typed instance

Key Features

- Type-safe generics for compile-time checking - Automatic YAML unmarshaling with type detection - Version comparison and migration support - Extensible conversion system for version upgrades - Thread-safe registry operations

Usage Patterns

The package is designed to be used by higher-level packages that need GVK-based type systems:

// In a generator package
type MyGenerator struct { ... }

var registry = gvk.NewRegistry[MyGenerator]()

func init() {
    registry.Register(gvk.GVK{
        Group: "example.gokure.dev",
        Version: "v1alpha1",
        Kind: "MyGenerator",
    }, func() MyGenerator { return MyGenerator{} })
}

// For YAML parsing
func ParseConfig(data []byte) (*MyGenerator, error) {
    wrapper := gvk.NewTypedWrapper(registry)
    err := yaml.Unmarshal(data, wrapper)
    if err != nil {
        return nil, err
    }
    return &wrapper.Spec, nil
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultParseOptions = ParseOptions{
	StrictGVK:         true,
	AllowUnknownTypes: false,
}

DefaultParseOptions provides sensible defaults for parsing

Functions

func ValidateGVK

func ValidateGVK(gvk GVK) error

ValidateGVK validates that a GVK is properly formed

Types

type BaseMetadata

type BaseMetadata struct {
	Name      string `yaml:"name" json:"name"`
	Namespace string `yaml:"namespace,omitempty" json:"namespace,omitempty"`
}

BaseMetadata provides common metadata fields for GVK types

func (*BaseMetadata) GetName

func (m *BaseMetadata) GetName() string

GetName returns the name

func (*BaseMetadata) GetNamespace

func (m *BaseMetadata) GetNamespace() string

GetNamespace returns the namespace

func (*BaseMetadata) SetName

func (m *BaseMetadata) SetName(name string)

SetName sets the name

func (*BaseMetadata) SetNamespace

func (m *BaseMetadata) SetNamespace(namespace string)

SetNamespace sets the namespace

type ConversionFunc

type ConversionFunc func(from any) (any, error)

ConversionFunc is a function-based converter

func (ConversionFunc) Convert

func (f ConversionFunc) Convert(from any) (any, error)

Convert implements the Converter interface

type ConversionPath

type ConversionPath struct {
	From      GVK
	To        GVK
	Converter Converter
}

ConversionPath represents a path from one version to another

type ConversionRegistry

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

ConversionRegistry manages version conversion paths. It is safe for concurrent use.

func NewConversionRegistry

func NewConversionRegistry() *ConversionRegistry

NewConversionRegistry creates a new conversion registry

func (*ConversionRegistry) Convert

func (r *ConversionRegistry) Convert(from, to GVK, obj any) (any, error)

Convert converts from one GVK to another.

func (*ConversionRegistry) HasConversion

func (r *ConversionRegistry) HasConversion(from, to GVK) bool

HasConversion checks if a conversion path exists.

func (*ConversionRegistry) ListConversions

func (r *ConversionRegistry) ListConversions(from GVK) []GVK

ListConversions returns all available conversion paths for a given GVK.

func (*ConversionRegistry) Register

func (r *ConversionRegistry) Register(from, to GVK, converter Converter)

Register registers a conversion path.

func (*ConversionRegistry) RegisterFunc

func (r *ConversionRegistry) RegisterFunc(from, to GVK, converter ConversionFunc)

RegisterFunc registers a conversion function

Example
package main

import (
	"fmt"

	"github.com/go-kure/kure/pkg/gvk"
)

// OldType and NewType are two versions of one spec, for the conversion example:
// the newer version renamed the field.
type OldType struct{ Name string }

type NewType struct{ DisplayName string }

func main() {
	oldGVK := gvk.GVK{Group: "generators.gokure.dev", Version: "v1alpha1", Kind: "MyGenerator"}
	newGVK := gvk.GVK{Group: "generators.gokure.dev", Version: "v1beta1", Kind: "MyGenerator"}

	conversions := gvk.NewConversionRegistry()
	conversions.RegisterFunc(oldGVK, newGVK, func(from any) (any, error) {
		old := from.(OldType)
		return NewType{DisplayName: old.Name}, nil
	})

	converted, err := conversions.Convert(oldGVK, newGVK, OldType{Name: "web"})
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", converted)
}
Output:
{DisplayName:web}

type Converter

type Converter interface {
	Convert(from any) (any, error)
}

Converter defines the interface for converting between versions

type Convertible

type Convertible interface {
	ConvertTo(version string) (any, error)
	ConvertFrom(from any) error
}

Convertible allows for version migration between different versions of the same kind

type Factory

type Factory[T any] func() T

Factory is a function that creates a new instance of type T

type GVK

type GVK struct {
	Group   string
	Version string
	Kind    string
}

GVK represents a Group, Version, Kind tuple for identifying types

func ParseAPIVersion

func ParseAPIVersion(apiVersion, kind string) GVK

ParseAPIVersion parses an apiVersion and kind into a GVK

func (GVK) APIVersion

func (g GVK) APIVersion() string

APIVersion returns the apiVersion string (group/version)

func (GVK) String

func (g GVK) String() string

String returns the string representation of GVK

type MetadataType

type MetadataType interface {
	NamedType
	NamespacedType
}

MetadataType combines name and namespace interfaces

type NamedType

type NamedType interface {
	GetName() string
	SetName(string)
}

NamedType is a type that has a name

type NamespacedType

type NamespacedType interface {
	GetNamespace() string
	SetNamespace(string)
}

NamespacedType is a type that has a namespace

type ParseOptions

type ParseOptions struct {
	// StrictGVK requires apiVersion and kind to be present
	StrictGVK bool
	// AllowUnknownTypes allows parsing of unregistered types
	AllowUnknownTypes bool
}

ParseOptions configures how GVK parsing behaves

type Registry

type Registry[T any] struct {
	// contains filtered or unexported fields
}

Registry manages type factories for GVK-based types

func NewRegistry

func NewRegistry[T any]() *Registry[T]

NewRegistry creates a new registry for type T

func (*Registry[T]) Count

func (r *Registry[T]) Count() int

Count returns the number of registered types

func (*Registry[T]) Create

func (r *Registry[T]) Create(gvk GVK) (T, error)

Create creates a new instance for the given GVK

Example
package main

import (
	"fmt"

	"github.com/go-kure/kure/pkg/gvk"
)

// MyConfigType is the spec type the examples register.
type MyConfigType struct {
	Replicas int `yaml:"replicas"`
}

func main() {
	myGVK := gvk.GVK{
		Group:   "generators.gokure.dev",
		Version: "v1alpha1",
		Kind:    "MyGenerator",
	}

	registry := gvk.NewRegistry[MyConfigType]()
	registry.Register(myGVK, func() MyConfigType {
		return MyConfigType{Replicas: 1}
	})

	instance, err := registry.Create(myGVK)
	if err != nil {
		panic(err)
	}
	fmt.Println(myGVK.APIVersion(), instance.Replicas)
}
Output:
generators.gokure.dev/v1alpha1 1

func (*Registry[T]) CreateFromAPIVersion

func (r *Registry[T]) CreateFromAPIVersion(apiVersion, kind string) (T, error)

CreateFromAPIVersion creates a new instance for the given apiVersion and kind

func (*Registry[T]) HasAPIVersion

func (r *Registry[T]) HasAPIVersion(apiVersion, kind string) bool

HasAPIVersion checks if an apiVersion and kind combination is registered

func (*Registry[T]) HasGVK

func (r *Registry[T]) HasGVK(gvk GVK) bool

HasGVK checks if a GVK is registered

func (*Registry[T]) ListGVKs

func (r *Registry[T]) ListGVKs() []GVK

ListGVKs returns all registered GVKs

func (*Registry[T]) Register

func (r *Registry[T]) Register(gvk GVK, factory Factory[T])

Register adds a new type factory to the registry

type TypedWrapper

type TypedWrapper[T any] struct {
	APIVersion string         `yaml:"apiVersion" json:"apiVersion"`
	Kind       string         `yaml:"kind" json:"kind"`
	Metadata   map[string]any `yaml:"metadata" json:"metadata"`
	Spec       T              `yaml:"-" json:"-"`
	// contains filtered or unexported fields
}

TypedWrapper provides type detection and unmarshaling for GVK-based types

func NewTypedWrapper

func NewTypedWrapper[T any](registry *Registry[T]) *TypedWrapper[T]

NewTypedWrapper creates a new typed wrapper with the given registry

Example
package main

import (
	"fmt"

	"gopkg.in/yaml.v3"

	"github.com/go-kure/kure/pkg/gvk"
)

// MyConfigType is the spec type the examples register.
type MyConfigType struct {
	Replicas int `yaml:"replicas"`
}

func main() {
	registry := gvk.NewRegistry[MyConfigType]()
	registry.Register(gvk.GVK{Group: "generators.gokure.dev", Version: "v1alpha1", Kind: "MyGenerator"},
		func() MyConfigType { return MyConfigType{} })

	data := []byte(`
apiVersion: generators.gokure.dev/v1alpha1
kind: MyGenerator
metadata:
  name: web
spec:
  replicas: 3
`)

	wrapper := gvk.NewTypedWrapper(registry)
	if err := yaml.Unmarshal(data, wrapper); err != nil {
		panic(err)
	}
	// wrapper.Spec contains the correctly typed instance
	fmt.Println(wrapper.GetName(), wrapper.Spec.Replicas)
}
Output:
web 3

func ParseMultiple

func ParseMultiple[T any](data []byte, registry *Registry[T], options *ParseOptions) ([]*TypedWrapper[T], error)

ParseMultiple parses multiple GVK-enabled types from YAML data (separated by ---)

func ParseSingle

func ParseSingle[T any](data []byte, registry *Registry[T], options *ParseOptions) (*TypedWrapper[T], error)

ParseSingle parses a single GVK-enabled type from YAML data

func ParseStream

func ParseStream[T any](reader io.Reader, registry *Registry[T], options *ParseOptions) ([]*TypedWrapper[T], error)

ParseStream parses a stream of YAML documents

func (*TypedWrapper[T]) GetGVK

func (w *TypedWrapper[T]) GetGVK() GVK

GetGVK returns the GVK for this wrapper

func (*TypedWrapper[T]) GetName

func (w *TypedWrapper[T]) GetName() string

GetName returns the name from metadata if available

func (*TypedWrapper[T]) GetNamespace

func (w *TypedWrapper[T]) GetNamespace() string

GetNamespace returns the namespace from metadata if available

func (*TypedWrapper[T]) MarshalYAML

func (w *TypedWrapper[T]) MarshalYAML() (any, error)

MarshalYAML implements custom YAML marshaling

func (*TypedWrapper[T]) SetName

func (w *TypedWrapper[T]) SetName(name string)

SetName sets the name in metadata

func (*TypedWrapper[T]) SetNamespace

func (w *TypedWrapper[T]) SetNamespace(namespace string)

SetNamespace sets the namespace in metadata

func (*TypedWrapper[T]) UnmarshalYAML

func (w *TypedWrapper[T]) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements custom YAML unmarshaling with type detection

type TypedWrappers

type TypedWrappers[T any] []TypedWrapper[T]

TypedWrappers is a slice of TypedWrapper for unmarshaling multiple configs

func (*TypedWrappers[T]) UnmarshalYAML

func (ws *TypedWrappers[T]) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements custom YAML unmarshaling for slices

type VersionComparator

type VersionComparator struct{}

VersionComparator compares version strings using semantic versioning

func (*VersionComparator) Compare

func (vc *VersionComparator) Compare(v1, v2 string) int

Compare compares two version strings Returns: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2

func (*VersionComparator) GetLatestVersion

func (vc *VersionComparator) GetLatestVersion(gvks []GVK) (GVK, error)

GetLatestVersion returns the latest version from a list of GVKs with the same group/kind

type VersionedType

type VersionedType interface {
	GetAPIVersion() string // Returns "group/version"
	GetKind() string
}

VersionedType is a type that supports GVK identification

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL