utils

package
v0.7.8 Latest Latest
Warning

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

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

README

pkg/utils

utils is a general-purpose utility package for the Orkestra control plane. It groups helpers that are too small to warrant their own packages but are used across multiple layers of the system.

File organisation

File Purpose
utils.go Sleep, BoolPtr, Retry, IsRunningInCluster, status constants, HTTP content-type constants
yaml.go YAML marshal/unmarshal helpers, multi-document YAML splitting
rawmap.go map[string]interface{} navigation helpers (Get, Set, Delete, Navigate)
http.go HTTP client helpers used by external call integrations
loadfile.go File loading helpers with path normalisation
orkestra.go Orkestra-specific utilities (version strings, resource name helpers)
printer.go CLI output formatting helpers
prune_yaml.go YAML pruning — removes zero-value fields before applying to the cluster
gvk.go GroupVersionKind parsing and formatting helpers
crd.go CRD discovery utilities — REST mapper construction, GVR lookup by kind

Key utilities

Retry(fn func() error, opts RetryOptions) error — retries fn up to opts.Attempts times with exponential backoff capped at opts.Delay. Returns the last error when all attempts are exhausted.

IsRunningInCluster() bool — detects in-cluster execution by checking for the service account token file at /var/run/secrets/kubernetes.io/serviceaccount/token. Used by pkg/konfig for namespace resolution.

Navigate(m map[string]interface{}, path string) (interface{}, bool) — walks a dot-separated path through nested maps. Powers the {{ .spec.someField }} template resolver.

Developer documentation

Topic Go to
How the REST mapper and CRD discovery client work docs/crd.md
How dot-path navigation works pkg/types/docs/navigate-dot-path.md

Documentation

Overview

pkg/utils/gvk.go

pkg/utils/loadfile.go

pkg/utils/printer.go

pkg/utils/rawmap.go

Index

Constants

View Source
const (
	ColorReset     = "\033[0m"
	ColorRed       = "\033[31m"
	ColorGreen     = "\033[32m"
	ColorYellow    = "\033[33m"
	ColorBlue      = "\033[34m"
	ColorMagenta   = "\033[35m"
	ColorCyan      = "\033[36m"
	ColorBold      = "\033[1m"
	ColorDim       = "\033[2m"
	ColorItalic    = "\033[3m"
	ColorUnderline = "\033[4m"
	ColorBlink     = "\033[5m"
	ColorReverse   = "\033[7m"
	ColorHidden    = "\033[8m"
	ColorGray      = "\033[90m"
)

Variables

View Source
View Source
var OrkestraLogoCLI = `` /* 174-byte string literal not displayed */

Functions

func Blue added in v0.4.0

func Blue(text string) string

func Bold added in v0.2.0

func Bold(text string) string

func BoolPtr

func BoolPtr(b bool) *bool

func BuildAnnotationPatch

func BuildAnnotationPatch(key, value string) map[string]interface{}

BuildAnnotationPatch constructs a JSON merge patch that sets one annotation.

func Center

func Center(text string) string

Center text to 60 columns

func Colorize added in v0.4.0

func Colorize(color, text string) string

func Cyan added in v0.2.0

func Cyan(text string) string

func Dim added in v0.4.0

func Dim(text string) string

func Exit

func Exit(err error)

Exit exits in error with a code

func ExtractStatus added in v0.2.0

func ExtractStatus(obj *unstructured.Unstructured) string

ExtractStatus extracts a status phase or condition from an unstructured object. Returns "Unknown" if no status is found.

func FailureMark added in v0.4.0

func FailureMark() string

FailureMark returns a red cross symbol for failed operations.

func FailureMarkPlain added in v0.4.9

func FailureMarkPlain() string

func FormatDuration added in v0.2.0

func FormatDuration(d time.Duration) string

FormatDuration formats a duration in human-readable short form. Exported so CLI commands and tests can use it directly.

func FormatYAMLError

func FormatYAMLError(err error, data []byte) string

func FormatYAMLFile added in v0.4.3

func FormatYAMLFile(path string) error

FormatYAMLFile reads path, parses into a yaml.Node and writes it back with consistent indentation and preserved comments/order.

func Gray added in v0.4.0

func Gray(text string) string

func Green added in v0.4.0

func Green(text string) string

func HealthIcon added in v0.2.0

func HealthIcon(status string) string

HealthIcon returns a coloured status icon based on a status string.

func HealthIconActive added in v0.5.3

func HealthIconActive() string

HealthIconActive returns the green "active" icon.

func HealthIconDegraded added in v0.5.3

func HealthIconDegraded() string

HealthIconDegraded returns the red "degraded" icon.

func HealthIconError added in v0.5.3

func HealthIconError() string

HealthIconError returns the red "error" icon.

func HealthIconFailed added in v0.5.3

func HealthIconFailed() string

HealthIconFailed returns the red "failed" icon.

func HealthIconHealthy added in v0.5.3

func HealthIconHealthy() string

HealthIconHealthy returns the green "healthy" icon.

func HealthIconPending added in v0.5.3

func HealthIconPending() string

HealthIconPending returns the yellow "pending" icon.

func HealthIconProgressing added in v0.5.3

func HealthIconProgressing() string

HealthIconProgressing returns the yellow "progressing" icon.

func HealthIconReady added in v0.5.3

func HealthIconReady() string

HealthIconReady returns the green "healthy" icon.

func HealthIconRunning added in v0.5.3

func HealthIconRunning() string

HealthIconRunning returns the green "running" icon.

func HealthIconUnhealthy added in v0.5.3

func HealthIconUnhealthy() string

HealthIconUnhealthy returns the red "unhealthy" icon.

func HealthIconUnknown added in v0.5.3

func HealthIconUnknown() string

HealthIconUnknown returns the gray "unknown" icon.

func HealthIconWarning added in v0.5.3

func HealthIconWarning() string

HealthIconWarning returns the yellow "warning" icon.

func HumanAge added in v0.2.0

func HumanAge(t metav1.Time) string

HumanAge returns a human-readable age string from a Kubernetes timestamp. Format matches kubectl: 5s, 2m, 3h, 4d, 2w

func InfoMark added in v0.4.0

func InfoMark() string

InfoMark returns a cyan arrow symbol for informational messages.

func InfoMarkPlain added in v0.4.9

func InfoMarkPlain() string

func Int64Ptr added in v0.5.4

func Int64Ptr(i int64) *int64

func IsRunningInCluster added in v0.1.9

func IsRunningInCluster() bool

IsRunningInCluster returns true when running inside a Kubernetes pod. The service account token is always present inside a pod.

func Jitter

func Jitter(d time.Duration) time.Duration

func LoadFile

func LoadFile(path string) ([]byte, error)

LoadFile loads a file from local disk or HTTP(S).

For remote files, auth is optional. When nil, an unauthenticated GET is performed. When set, the appropriate Authorization header is added based on auth.Type.

For local files, auth is ignored.

func LoadFileWithAuth

func LoadFileWithAuth(path string, auth *FileAuth) ([]byte, error)

LoadFileWithAuth loads a file with optional authentication. Called by the merger when a source declares an auth block.

func Magenta added in v0.4.0

func Magenta(text string) string

func Merge

func Merge(target *string, incoming, sep string)

Used to merge labels

func MetaField added in v0.1.9

func MetaField(objMap map[string]interface{}, field string) string

MetaField extracts a string field from objMap["metadata"]. Returns "" when the field is absent or not a string.

func NoSecurityMark added in v0.5.3

func NoSecurityMark() string

NoSecurityMark returns a cross mark indicating no security protection. Used when deletion protection is completely disabled for a resource (e.g., security.deletionProtection.enabled = false or per‑CRD protectCRs=false).

func PrintError added in v0.2.0

func PrintError(msg string)

PrintError prints a red error line.

func PrintField added in v0.2.0

func PrintField(label, value string)

PrintField prints a label: value line used in describe output.

func PrintInfo added in v0.2.0

func PrintInfo(msg string)

PrintInfo prints a dim informational line.

func PrintNestedMap added in v0.2.0

func PrintNestedMap(m map[string]interface{}, indent int)

PrintNestedMap prints a nested map as indented key: value lines. Used by describe to print spec and status sections.

func PrintSection added in v0.2.0

func PrintSection(title string)

PrintSection prints a bold section header with a separator.

func PrintSuccess added in v0.2.0

func PrintSuccess(msg string)

PrintSuccess prints a green checkmark line.

func PrintTable added in v0.2.0

func PrintTable(w io.Writer, header []string, rows [][]string)

PrintTable prints a header + rows to stdout, flushed and aligned.

func PrintWarning added in v0.2.0

func PrintWarning(msg string)

PrintWarning prints a yellow warning line.

func RawToMap added in v0.1.9

func RawToMap(raw interface{}) (map[string]interface{}, error)

RawToMap converts a raw informer cache object to map[string]interface{}. Works for *unstructured.Unstructured, any typed runtime.Object, and any JSON-serializable value. No type assertion required.

Fast path: *unstructured.Unstructured already has the map — returned directly with zero allocation. General path: JSON round-trip.

func Red added in v0.4.0

func Red(text string) string

func RequireStrParams

func RequireStrParams(required map[string]string) error

func Reset added in v0.4.0

func Reset(text string) string

Reset removes all styling from the given text.

func Retry

func Retry(fn func() error, opts RetryOptions) error

func RetryBackoff

func RetryBackoff(fn func() error, opts RetryOptions) error

func Reversed

func Reversed[T any](s []T) []T

Reversed reverses any given slice

func SecureMark added in v0.5.3

func SecureMark() string

SecureMark returns a shield emoji indicating full security protection. Used in CLI output to show that deletion protection is enabled and active.

func SetGroupVersionKindObj

func SetGroupVersionKindObj(gvk schema.GroupVersionKind) string

func Sleep

func Sleep(n int)

func SomeSecureMark added in v0.5.3

func SomeSecureMark() string

SomeSecureMark returns an unlocked padlock emoji indicating partial or no security protection. Used in CLI output to show that deletion protection is disabled or only partially active (e.g., protectCRD=false but protectCRs=true).

func StrictUnmarshal

func StrictUnmarshal(data []byte, out any) error

func SuccessMark added in v0.4.0

func SuccessMark() string

SuccessMark returns a green checkmark symbol for successful operations.

func SuccessMarkPlain added in v0.4.9

func SuccessMarkPlain() string

func Underline added in v0.4.0

func Underline(text string) string

func WaitForCRD

func WaitForCRD(cfg *rest.Config, group, kind, version string) error

Wait for CRD creation

func WarningMark added in v0.4.0

func WarningMark() string

WarningMark returns a yellow warning symbol for non-fatal issues.

func WarningMarkPlain added in v0.4.9

func WarningMarkPlain() string

func WriteFileAndFormat added in v0.4.3

func WriteFileAndFormat(path string, data []byte, perm os.FileMode) error

WriteFileAndFormat writes data to path and then formats the YAML file. It preserves a simple, consistent workflow: write -> format -> return error if any.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, data interface{})

func WriteJSONPruned

func WriteJSONPruned(w http.ResponseWriter, status int, v interface{})

WriteJSONPruned writes a JSON response with null/empty values removed

func Yellow added in v0.4.0

func Yellow(text string) string

Types

type FileAuth

type FileAuth struct {
	// Type — authentication scheme.
	// Supported: "bearer", "github", "basic"
	Type string

	// BearerToken — used when Type is "bearer" or "github".
	// Resolved from the environment variable named in the source declaration.
	BearerToken string

	// Username and Password — used when Type is "basic".
	// Each resolved from its own environment variable.
	Username string
	Password string
}

FileAuth holds optional authentication for a remote file source. Constructed from the Katalog source declaration and resolved from environment variables at load time — credentials never appear in YAML.

type GroupVersionKind

type GroupVersionKind string

GroupVersionKind is a consistent string key for GVK-keyed maps and logs.

func SetGroupVersionKind

func SetGroupVersionKind(group, version, kind string) GroupVersionKind

SetGroupVersionKind formats a GVK as the canonical string used internally. Mirrors runtime.Object.GetObjectKind().GroupVersionKind().String() output.

func (GroupVersionKind) String

func (g GroupVersionKind) String() string

type H

type H map[string]interface{}

type RetryOptions

type RetryOptions struct {
	Attempts int
	Delay    time.Duration
}

type Spinner added in v0.7.8

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

Spinner animates a terminal progress indicator with a message.

func StartSpinner added in v0.7.8

func StartSpinner(msg string) *Spinner

StartSpinner begins the spinner; on non-TTY it prints once and finalizes.

func (*Spinner) Failure added in v0.7.8

func (s *Spinner) Failure()

Failure prints a red ✗ and finalizes the spinner.

func (*Spinner) Stop added in v0.7.8

func (s *Spinner) Stop()

Stop halts animation and clears the line.

func (*Spinner) Success added in v0.7.8

func (s *Spinner) Success()

Success prints a green ✓ and finalizes the spinner.

func (*Spinner) Update added in v0.7.8

func (s *Spinner) Update(msg string)

Update changes the spinner's message while running.

type Status

type Status string
const (
	// Status
	StatusReady   Status = "ready"
	StatusRunning Status = "running"
	StatusHealthy Status = "healthy"
	StatusOnline  Status = "online"

	StatusNotReady   Status = "not ready"
	StatusNotRunning Status = "not running"
	StatusNotHealthy Status = "not healthy"
	StatusOffline    Status = "offline"

	// HTTP
	ContentType     = "Content-Type"
	JSONContentType = "application/json"
)

type TableWriter added in v0.2.0

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

TableWriter wraps tabwriter for consistent aligned output.

func NewTableWriter added in v0.2.0

func NewTableWriter() *TableWriter

NewTableWriter returns a TableWriter writing to stdout.

func (*TableWriter) Flush added in v0.2.0

func (t *TableWriter) Flush()

Flush flushes the tabwriter buffer.

func (*TableWriter) Header added in v0.2.0

func (t *TableWriter) Header(cols ...string)

Header prints a bold header row.

func (*TableWriter) Row added in v0.2.0

func (t *TableWriter) Row(cols ...string)

Row prints one data row.

Jump to

Keyboard shortcuts

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