utils

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: MIT Imports: 34 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	KPUCreatedByLabel = "created-by"
	KPUIdentity       = "kpu"
)

Variables

View Source
var (
	// LabelKeyExistsRegex matches a label selector in the form of <key> (label exists) or !<key> (label does not exist).
	LabelKeyExistsRegex = regexp.MustCompile(fmt.Sprintf(`^(?P<mod>\!?)%s$`, rawLabelKeyRegex))
	// LabelKeyOperatorValueRegex matches a label selector in the form of <key><operator><value>.
	LabelKeyOperatorValuesRegex = regexp.MustCompile(fmt.Sprintf(`^%s%s%s$`, rawLabelKeyRegex, rawLabelOperatorRegex, rawLabelMultiValueRegex))

	// indices for the capture groups in the LabelKeyExistsRegex
	LabelKeyExistsRegex_ModIndex = -1
	LabelKeyExistsRegex_KeyIndex = -1

	// indices for the capture groups in the LabelKeyOperatorValueRegex
	LabelKeyOperatorValueRegex_KeyIndex      = -1
	LabelKeyOperatorValueRegex_OperatorIndex = -1
	LabelKeyOperatorValueRegex_ValueIndex    = -1
)
View Source
var (
	TimeStringRegex    = regexp.MustCompile(fmt.Sprintf(`^(%s)+$`, rawTimeSubstringRegex))
	TimeSubstringRegex = regexp.MustCompile(rawTimeSubstringRegex)

	TimeSubstringRegex_TimeIndex = -1
	TimeSubstringRegex_UnitIndex = -1
)
View Source
var DefaultOutputFormats = []OutputFormat{OUTPUT_JSON, OUTPUT_TEXT, OUTPUT_YAML}

Functions

func AddDefaultK8sInteractionFlags

func AddDefaultK8sInteractionFlags(fs *pflag.FlagSet, ko *K8sInteractionOptions)

AddDefaultK8sInteractionFlags adds default flags for k8s cluster interaction to the given flagset. The flags bind to variables in the given K8sInteractionOptions struct.

func AddK8sImpersonationFlags added in v1.1.0

func AddK8sImpersonationFlags(fs *pflag.FlagSet, ko *K8sInteractionOptions)

AddK8sImpersonationFlags adds default flags for impersonation to the given flagset. The flags bind the ImpersonationConfig in the given K8sInteractionOptions struct.

func AddOutputFlag

func AddOutputFlag(fs *pflag.FlagSet, outputVar *OutputFormat, defaultOutput OutputFormat, validOutputs ...OutputFormat)

AddOutputFlag adds a --output/-o flag to the given FlagSet, binding the result to the given string variable.

func AddScopeFlag

func AddScopeFlag(fs *pflag.FlagSet, scopeVar *Scope)

AddScopeFlag adds a --scope flag to the given FlagSet, binding the result to the given string variable.

func Fatal

func Fatal(code int, format string, values ...any)

Fatal prints the given error message to stderr and then exits with the given exit code.

func FilterSlice

func FilterSlice[X any](data []X, predicate func(X) bool) []X

FilterSlice takes a slice and filters it using the given predicate function. Does not modify the original slice, but values are not deep-copied, so changes to the values might influence the original slice, depending on the type.

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration is the inverse to StringToDuration and formats a time.Duration into a human-readable string. Note that it neither prints months nor weeks, because a year is defined based on days and the corresponding number of weeks or months does not add up to the defined 365 days per year.

func GVKToString

func GVKToString(gvk schema.GroupVersionKind) string

func GetFinalizerIndices

func GetFinalizerIndices(obj client.Object, fins ...string) []int

GetFinalizerIndices takes an k8s object and a list of finalizers and returns the indices of the corresponding entries in the object's finalizers. If a given finalizer doesn't exist on the object, not index is returned for it. This means that from the resulting list of indices, it cannot be reconstructed which finalizer is at a specific index, just that it is one of the given ones.

func NaturalLanguageJoin

func NaturalLanguageJoin(data []string, separator string, oxfordComma bool) string

NaturalLanguageJoin works like strings.Join, but it separates the last element via ' and ' instead of comma. For exactly two elements, the result is '<elem> and <elem>'.

func ParseLabelSelectors

func ParseLabelSelectors(selectors []string) (labels.Selector, error)

ParseLabelSelectors parses a list of label selectors into a labels.Selector. Each individual selector must be in the form of <key><operator><value> or [!]<key>. Possible values for <operator> are ==, =, !=.

func Project

func Project[X any, Y any](data []X, project func(X) Y) []Y

Project takes a list and converts/projects each element of the list to another type using the given project function.

func PromptForConfirmation

func PromptForConfirmation(prompt string, newline bool) bool

PromptForConfirmation prompts the user for confirmation.

func PromptForInput

func PromptForInput(prompt string, newline bool, transform func(string) string) string

PromptForInput asks the user for information and returns it.

func ResourceIdentifier

func ResourceIdentifier(obj client.Object) string

func StringPadding

func StringPadding(s string, l int) string

StringPadding returns the given string filled with spaces to the given length. If the string already has the required or a greater length, it is returned unmodified.

func StringToDuration

func StringToDuration(s string) (time.Duration, error)

StringToDuration parses a string into a time.Duration. Accepted time units are: - s: seconds - m: minutes - h: hours - d: days (24 hours) - w: weeks (7 days) - M: months (30 days) - y: years (365 days)

func UnknownOutputFatal

func UnknownOutputFatal(output OutputFormat)

UnknownOutputFatal prints an error message that the specified output format is not known and then exits with status 1.

func UnknownScopeFatal

func UnknownScopeFatal(scope string)

UnknownScopeFatal prints an error message that the specified scope is not known and then exits with status 1.

func ValidateOutputFormat

func ValidateOutputFormat(output OutputFormat, validOutputs ...OutputFormat)

ValidateOutputFormat verifies that a valid output format was specified and exits with error otherwise.

func ValidateScope

func ValidateScope(scope string)

ValidateScope verifies that a valid scope was specified and exits with error otherwise.

Types

type K8sInteractionOptions

type K8sInteractionOptions struct {
	KubeconfigPath      string
	Namespace           string
	AllNamespaces       bool
	LabelSelector       []string
	ImpersonationConfig rest.ImpersonationConfig
}

type Kubeconfig

type Kubeconfig struct {
	client.Client
	DiscoveryClient   *discovery.DiscoveryClient
	ShortNameExpander meta.RESTMapper
	DefaultNamespace  string
	RESTConfig        *rest.Config
	Path              string
	Raw               k8sapi.Config
}

Kubeconfig stores information loaded from the kubeconfig. It is a wrapper around client.Client and can be used to communicate with the cluster.

func LoadKubeconfig

func LoadKubeconfig(kcfgPath string) (*Kubeconfig, error)

LoadKubeconfig loads a kubeconfig from the given path. If the path is empty, it is defaulted to the value of the KUBECONFIG env var first, and then to $HOME/.kube/config, if it is still empty.

func LoadKubeconfigWithImpersonation added in v1.1.0

func LoadKubeconfigWithImpersonation(kcfgPath string, impersonationConfig rest.ImpersonationConfig) (*Kubeconfig, error)

func (*Kubeconfig) ConstructListOptions

func (k *Kubeconfig) ConstructListOptions(opts *K8sInteractionOptions) []client.ListOption

func (*Kubeconfig) CreateServiceAccountToken

func (k *Kubeconfig) CreateServiceAccountToken(ctx context.Context, sa *corev1.ServiceAccount, desiredValiditySeconds int64) (*authenticationv1.TokenRequest, error)

CreateServiceAccountToken is a convenience function that wraps the creation of a serviceaccount token.

func (*Kubeconfig) CreateStaticTokenKubeconfig

func (k *Kubeconfig) CreateStaticTokenKubeconfig(ctx context.Context, namespace, serviceaccount, clusterrolebinding, clusterrole string, desiredValiditySeconds int64, minify bool) (*k8sapiv1.Config, time.Time, error)

CreateStaticTokenKubeconfig creates a kubeconfig that uses a serviceaccount token for authentication. For this, it performs the following steps: - create the namespace if it does not exist - create the serviceaccount if it does not exist - create/update the clusterrolebinding (if it exists and was not created by kpu, an error is returned) - create a serviceaccount token It then returns a copy of the currently used kubeconfig with the currently active authentication method replaced by the token. If minify is true, it removes all unused contexts, clusters, and authinfos from the kubeconfig.

func (*Kubeconfig) DiscoverAPIResources

func (k *Kubeconfig) DiscoverAPIResources() ([]metav1.APIResource, error)

DiscoverAPIResources takes a rest config and returns all discovered api resources. The resources are sorted by group, then by kind, then by version.

func (*Kubeconfig) GetAllResources

func (k *Kubeconfig) GetAllResources(ctx context.Context, scope Scope, k8sOptions *K8sInteractionOptions) ([]unstructured.Unstructured, []error)

GetAllResources fetches all resources. Scope determines if only namespace-scoped, cluster-scoped, or all resources are fetched. k8sOptions are used to limit the search to specific namespaces or similar.

func (*Kubeconfig) GetGVKForResource

func (k *Kubeconfig) GetGVKForResource(resource string) (schema.GroupVersionKind, error)

GetGVKForResource resolves a shortname to a GroupVersionKind.

func (*Kubeconfig) GetNamespaces

func (k *Kubeconfig) GetNamespaces(ctx context.Context) ([]corev1.Namespace, error)

GetNamespaces lists all k8s namespaces.

func (*Kubeconfig) ListResources

func (k *Kubeconfig) ListResources(ctx context.Context, resourceTypes []string, resourceNames []string, scope Scope, k8sOptions *K8sInteractionOptions) ([]unstructured.Unstructured, []error)

ListResources lists all resources matching the specified criteria. If resourceTypes is empty, all resources are listed (filtered by scope). Otherwise, only the specified types are listed. If resourceNames is empty, all resources are listed. Otherwise, only the resources with names contained in the specified list are listed.

func (*Kubeconfig) PatchAnnotations

func (k *Kubeconfig) PatchAnnotations(ctx context.Context, obj client.Object, anns map[string]string) (bool, error)

PatchAnnotations patches the object to ensure that the specified annotations exist. Does not patch if all annotations already have their expected values.

func (*Kubeconfig) RemoveFinalizers

func (k *Kubeconfig) RemoveFinalizers(ctx context.Context, obj client.Object, fins ...string) (bool, error)

RemoveFinalizers removes all instances of all specified finalizers from the given object and patches it in the cluster. If fins is empty, all finalizers are removed.

type OutputFormat

type OutputFormat string
const (
	OUTPUT_TEXT OutputFormat = "text"
	OUTPUT_YAML OutputFormat = "yaml"
	OUTPUT_JSON OutputFormat = "json"
)

func (*OutputFormat) Set

func (o *OutputFormat) Set(val string) error

Set implements pflag.Value

func (*OutputFormat) String

func (o *OutputFormat) String() string

String implements pflag.Value

func (*OutputFormat) Type

func (o *OutputFormat) Type() string

Type implements pflag.Value

type Scope

type Scope string
const (
	SCOPE_ALL        Scope = "all"
	SCOPE_CLUSTER    Scope = "cluster"
	SCOPE_NAMESPACED Scope = "namespaced"
)

func (*Scope) IncludesCluster

func (s *Scope) IncludesCluster() bool

IncludesCluster returns true if the scope includes cluster-scoped resources.

func (*Scope) IncludesNamespaced

func (s *Scope) IncludesNamespaced() bool

IncludesNamespaced returns true if the scope includes namespaced resources.

func (*Scope) Set

func (s *Scope) Set(val string) error

Set implements pflag.Value

func (*Scope) String

func (s *Scope) String() string

String implements pflag.Value

func (*Scope) Type

func (s *Scope) Type() string

Type implements pflag.Value

type Table

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

Table is a helper struct to format output as table.

func NewOutputTable

func NewOutputTable[T any]() *Table[T]

NewOutputTable returns a new Table for constructing output formatted as a table.

func (*Table[T]) String

func (t *Table[T]) String() string

func (*Table[T]) WithColumn

func (t *Table[T]) WithColumn(name string, getValue func(obj T) string) *Table[T]

WithColumn adds a new column with the given name and getter function to the table.

func (*Table[T]) WithData

func (t *Table[T]) WithData(obj ...T) *Table[T]

WithData adds a one or more new rows to the table.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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