util

package
v0.3.1 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultBackoff = BackoffPolicy{
	Millis: []int{
		500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000,
		5500, 5750, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500, 10000,
		10500, 10750, 11000, 11500, 12000, 12500, 13000, 13500, 14000, 14500, 15000,
		15500, 15750, 16000, 16500, 17000, 17500, 18000, 18500, 19000, 19500, 20000,
	},
}

DefaultBackoff is the default backoff policy to use

View Source
var ProgressUnitsIBytes = progress.Units{
	Notation:         "",
	NotationPosition: progress.UnitsNotationPositionBefore,
	Formatter:        func(v int64) string { return humanize.IBytes(uint64(v)) },
}

Functions

func AskOne

func AskOne(p survey.Prompt, response any, opts ...survey.AskOpt) error

AskOne asks a single question using Prompt

func BarGraph

func BarGraph(w io.Writer, data map[string]float64, caption string, width int, bytes bool) error

BarGraph generates a bar group based on data, copied from choria-io/appbuilder

func Base64IfNotPrintable

func Base64IfNotPrintable(val []byte) string

Base64IfNotPrintable returns the bytes are all printable else a b64 encoded version

func ClearScreen

func ClearScreen()

ClearScreen tries to ensure resetting original state of screen

func CompactStrings

func CompactStrings(source []string) []string

CompactStrings looks through a list of strings like hostnames and chops off the common parts like domains

func ConfigDir

func ConfigDir() (string, error)

ConfigDir is the directory holding configuration files

func DecodeHeadersMsg

func DecodeHeadersMsg(data []byte) (nats.Header, error)

DecodeHeadersMsg parses the data that includes headers into a header. Copied from nats.go

func EditFile

func EditFile(f string) error

EditFile edits the file at filepath f using the environment variable EDITOR command.

func FileExists

func FileExists(f string) bool

FileExists checks if a file exist regardless of file kind

func Int64RangeValidator added in v0.3.0

func Int64RangeValidator(min int64, max int64) fisk.OptionValidator

Int64RangeValidator validates an integer is in a range inclusive of the given values

func IsDirectory

func IsDirectory(path string) bool

IsDirectory returns true when path is a directory

func IsFileAccessible

func IsFileAccessible(f string) (bool, error)

IsFileAccessible checks if f is a file and accessible, errors for non file arguments

func IsJsonObjectString

func IsJsonObjectString(s string) bool

IsJsonObjectString checks if a string is a JSON document starting and ending with {}

func IsPrintable

func IsPrintable(s string) bool

IsPrintable checks if a string is made of only printable characters

func IsTerminal

func IsTerminal() bool

IsTerminal checks if stdin and stdout are both normal terminals

func JSONString

func JSONString(s string) string

JSONString returns a quoted string to be used as a JSON object

func MapKeys

func MapKeys[M ~map[K]V, K comparable, V any](m M) []K

MapKeys extracts the keys from a map

func NewProgress

func NewProgress(opts *options.Options, tracker *progress.Tracker) (progress.Writer, *progress.Tracker, error)

func ParentDir

func ParentDir() (string, error)

ParentDir is the parent, controlled by XDG_CONFIG_HOME, for any configuration

func ParseApiLevel added in v0.3.0

func ParseApiLevel(lvl string) uint

ParseApiLevel takes an api level string and converts it to an unsigned int for comparison. An empty level will be converted into 0

func ParseStringAsBytes

func ParseStringAsBytes(s string, bitSize int) (int64, error)

ParseStringAsBytes nats-server derived string parse, empty string and any negative is -1,others are parsed as 1024 based bytes.

Bitsize should be set to control the resulting number and will be passed to strconv.ParseInt.

func ParseStringsToHeader

func ParseStringsToHeader(hdrs []string, seq int) (nats.Header, error)

ParseStringsToHeader creates a nats.Header from a list of strings like X:Y

func ParseStringsToMsgHeader

func ParseStringsToMsgHeader(hdrs []string, seq int, msg *nats.Msg) error

ParseStringsToMsgHeader parsers strings of headers like X:Y into a supplied msg headers

func PrintJSON

func PrintJSON(d any) error

PrintJSON prints any to stdout as json

func ProgressWidth

func ProgressWidth() int

ProgressWidth calculates progress bar width for uiprogress:

if it cant figure out the width, assume 80 if the width is too small, set it to minWidth and just live with the overflow

this ensures a reasonable progress size, ideally we should switch over to a spinner for < minWidth rather than cause overflows, but thats for later.

func PubReplyBodyTemplate

func PubReplyBodyTemplate(body string, request string, ctr int) ([]byte, error)

PubReplyBodyTemplate parses a message body using the usual template functions we support as standard

func RandomPassword

func RandomPassword(length int) string

RandomPassword generates a random string like RandomString() but includes some special characters

func RandomString

func RandomString(shortest uint, longest uint) string

RandomString generates a random string that includes only a-zA-Z0-9

func ReadKeyFile

func ReadKeyFile(filename string) ([]byte, error)

ReadKeyFile reads a nkey from a file

func RemoveReservedMetadata

func RemoveReservedMetadata(metadata map[string]string) map[string]string

RemoveReservedMetadata returns a new version of metadata with reserved keys starting with _nats. removed

func RenderMetaApi

func RenderMetaApi(cols *columns.Writer, metadata map[string]string)

RenderMetaApi draws the _nats.* metadata on streams and consumers

func RequireAPILevel

func RequireAPILevel(m *jsm.Manager, lvl int, format string, a ...any) error

RequireAPILevel asserts if the meta leader supports api level lvl

func SaveConfig

func SaveConfig(cfg *Config) error

func SelectPageSize

func SelectPageSize(count int) int

SelectPageSize is the size of selection lists influence by screen size

func ServerMinVersion

func ServerMinVersion(nc *nats.Conn, major, minor, patch int) bool

ServerMinVersion checks if the connected server meets certain version constraints

func SliceGroups

func SliceGroups(input []string, size int, fn func(group []string))

SliceGroups calls fn repeatedly with a subset of input up to size big

func SortMultiSort

func SortMultiSort[V cmp.Ordered, S string | cmp.Ordered](i1 V, j1 V, i2 S, j2 S) bool

func SplitCLISubjects

func SplitCLISubjects(subjects []string) []string

SplitCLISubjects splits a subject list by comma, tab, space, unicode space etc

func SplitCommand

func SplitCommand(s string) (string, []string, error)

SplitCommand Split the string into a command and its arguments.

func SplitString

func SplitString(s string) []string

SplitString splits a string by unicode space or comma

func StructWithoutOmitEmpty

func StructWithoutOmitEmpty(s any) any

StructWithoutOmitEmpty given a non pointer instance of a type with a lot of omitempty json tags will return a new instance without those

does not handle nested values

func SurveyColors

func SurveyColors() []survey.AskOpt

SurveyColors determines colors for the survey package based on context and options set

func ToJSON

func ToJSON(d any) (string, error)

ToJSON converts any to json string

func ValidStyles

func ValidStyles() []string

ValidStyles are valid color styles this package supports

func WipeSlice

func WipeSlice(buf []byte)

WipeSlice overwrites the contents of slice with 'x'

func XdgShareHome

func XdgShareHome() (string, error)

XdgShareHome is where to store data like nsc stored

Types

type BackoffPolicy added in v0.2.4

type BackoffPolicy struct {
	Millis []int
}

BackoffPolicy implements a backoff policy, randomizing its delays and saturating at the final value in Millis.

func (BackoffPolicy) Duration added in v0.2.4

func (b BackoffPolicy) Duration(n int) time.Duration

Duration returns the time duration of the n'th wait cycle in a backoff policy. This is b.Millis[n], randomized to avoid thundering herds.

func (BackoffPolicy) For added in v0.2.4

func (b BackoffPolicy) For(ctx context.Context, cb func(try int) error) error

For is a for{} loop that stops on context and has a backoff based sleep between loops if the context completes the loop ends returning the context error

func (BackoffPolicy) Sleep added in v0.2.4

func (b BackoffPolicy) Sleep(ctx context.Context, t time.Duration) error

Sleep sleeps for the duration t and can be interrupted by ctx. An error is returns if the context cancels the sleep

func (BackoffPolicy) TrySleep added in v0.2.4

func (b BackoffPolicy) TrySleep(ctx context.Context, n int) error

TrySleep sleeps for the duration of the n'th try cycle in a way that can be interrupted by the context. An error is returned if the context cancels the sleep

type Config

type Config struct {
	SelectedOperator string `json:"select_operator"`
}

func LoadConfig

func LoadConfig() (*Config, error)

type Table

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

func NewTableWriter

func NewTableWriter(opts *options.Options, title string) *Table

func NewTableWriterf added in v0.3.0

func NewTableWriterf(opts *options.Options, format string, a ...any) *Table

func (*Table) AddFooter

func (t *Table) AddFooter(items ...any)

func (*Table) AddHeaders

func (t *Table) AddHeaders(items ...any)

func (*Table) AddRow

func (t *Table) AddRow(items ...any)

func (*Table) AddSeparator

func (t *Table) AddSeparator()

func (*Table) Render

func (t *Table) Render() string

func (*Table) RenderCSV

func (t *Table) RenderCSV() string

Jump to

Keyboard shortcuts

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