kutils

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2025 License: AGPL-3.0 Imports: 37 Imported by: 1

README

kutils

kutils

Documentation

Index

Constants

View Source
const DefaultEditor = "vi"

DefaultEditor is vi because we're adults ;)

View Source
const LatestVersionAlias = "latest"

LatestVersionAlias represents the latest build (excluding nightly versions).

View Source
const NextgenVersionAlias = "nextgen"

NextgenVersionAlias represents latest build of nextgen branch.

View Source
const NightlyVersionAlias = "nightly"

NightlyVersionAlias represents latest build of master branch.

Variables

View Source
var (
	// ErrPropSuggestion is a property of an Error that will be printed as the suggestion.
	ErrPropSuggestion = errorx.RegisterProperty("suggestion")

	// ErrTraitPreCheck means that the Error is a pre-check error so that no error logs will be outputted directly.
	ErrTraitPreCheck = errorx.RegisterTrait("pre_check")
)
View Source
var (
	// ErrValidateChecksum is an empty HashValidationErr object, useful for type checking
	ErrValidateChecksum = &HashValidationErr{}
)

Functions

func Base52Decode added in v0.2.1

func Base52Decode(encoded string) (int64, error)

Decode will decode the string and return the id The input string should be a valid one with only characters in the space

func Base52Encode added in v0.2.1

func Base52Encode(id int64) string

Encode returns a string by encoding the id over a 51 characters space

func Base62Tag

func Base62Tag() string

Base62Tag returns a tag based on time

func CheckSHA256

func CheckSHA256(reader io.Reader, sha string) error

CheckSHA256 returns an error if the hash of reader mismatches `sha`

func Checksum

func Checksum(file string) (string, error)

Checksum returns the sha1 sum of target file

func Copy

func Copy(src, dst string) error

Copy copies a file or directory from src to dst

func CurrentUser

func CurrentUser() string

CurrentUser returns current login user

func FmtVer

func FmtVer(ver string) (string, error)

FmtVer converts a version string to SemVer format, if the string is not a valid SemVer and fails to parse and convert it, an error is raised.

func IsEmptyDir

func IsEmptyDir(path string) (bool, error)

IsEmptyDir check whether a path is an empty directory

func IsExecBinary

func IsExecBinary(path string) bool

IsExecBinary check whether a path is a valid executable

func IsExist

func IsExist(path string) bool

IsExist check whether a path is exist

func IsFlagSetByUser

func IsFlagSetByUser(flagSet *pflag.FlagSet, flagName string) bool

IsFlagSetByUser check if the a flag is set by user explicitly

func IsNotExist

func IsNotExist(path string) bool

IsNotExist check whether a path is not exist

func IsSubDir

func IsSubDir(parent, sub string) bool

IsSubDir returns if sub is a sub directory of parent

func IsSymExist

func IsSymExist(path string) bool

IsSymExist check whether a symbol link is exist

func IsTimeoutOrMaxRetry

func IsTimeoutOrMaxRetry(err error) bool

IsTimeoutOrMaxRetry return true if it's timeout or reach max retry.

func JoinHostPort

func JoinHostPort(host string, port int) string

JoinHostPort return host and port

func JoinInt

func JoinInt(nums []int, delim string) string

JoinInt joins a slice of int to string

func MatchGroups

func MatchGroups(r *regexp.Regexp, str string) map[string]string

MatchGroups turns a slice of matched string to a map according to capture group name

func MkdirAll

func MkdirAll(path string, minPerm os.FileMode) error

MkdirAll basically copied from os.MkdirAll, but use max(parent permission,minPerm)

func Move

func Move(src, dst string) error

Move moves a file from src to dst, this is done by copying the file and then delete the old one. Use os.Rename() to rename file within the same filesystem instead this, it's more lightweight but can not be used across devices.

func MustAtoI

func MustAtoI(a string) int

MustAtoI calls strconv.Atoi and ignores error

func MustGetFreePort

func MustGetFreePort(host string, defaultPort int, portOffset int) int

MustGetFreePort asks the kernel for a free open port that is ready to use, if fail, panic

func OpenFileInEditor

func OpenFileInEditor(filename string) error

OpenFileInEditor opens filename in a text editor.

func ParseHostPort

func ParseHostPort(hostport string) (host, port string)

ParseHostPort Prase host and port

func PostFile

func PostFile(reader io.Reader, url, fieldname, filename string) (*http.Response, error)

PostFile upload file

func RebuildArgs

func RebuildArgs(args []string) []string

RebuildArgs move "--help" or "-h" flag to the end of the arg list

func Retry

func Retry(doFunc func() error, opts ...RetryOption) error

Retry retries the func until it returns no error or reaches attempts limit or timed out, either one is earlier

func RetryUntil

func RetryUntil(f func() error, when func(error) bool) error

RetryUntil when the when func returns true

func SHA256

func SHA256(reader io.Reader) (string, error)

SHA256 returns the hash of reader

func SHA512

func SHA512(reader io.Reader) (string, error)

SHA512 returns the hash of reader

func SaveFileWithBackup

func SaveFileWithBackup(path string, data []byte, backupDir string) error

SaveFileWithBackup will backup the file before save it. e.g., backup meta.yaml as meta-2006-01-02T15:04:05Z07:00.yaml backup the files in the same dir of path if backupDir is empty.

func ShowDiff

func ShowDiff(t1 string, t2 string, w io.Writer)

ShowDiff write diff result into the Writer. return false if there's no diff.

func TailN

func TailN(fname string, n int) (lines []string, err error)

TailN try get the latest n line of the file.

func Tar

func Tar(writer io.Writer, from string) error

Tar compresses the folder to tarball with gzip

func Ternary

func Ternary(condition bool, a, b any) any

Ternary operator

func Untar

func Untar(reader io.Reader, to string) error

Untar decompresses the tarball

func UserHome

func UserHome() string

UserHome returns home directory of current user

func ValidateSpecDiff

func ValidateSpecDiff(s1, s2 any) error

ValidateSpecDiff checks and validates the new spec to see if the modified keys are all marked as editable

func WriteFile

func WriteFile(name string, data []byte, perm os.FileMode) error

WriteFile call os.WriteFile, but use max(parent permission,minPerm)

Types

type AnyQueue

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

AnyQueue is a queue stores any

func NewAnyQueue

func NewAnyQueue(eq func(a any, b any) bool, aa ...any) *AnyQueue

NewAnyQueue builds a AnyQueue

func (*AnyQueue) Get

func (q *AnyQueue) Get(val any) any

Get returns previous stored value that equals to val and remove it from the queue, if not found, return nil

func (*AnyQueue) Put

func (q *AnyQueue) Put(val any)

Put inserts `val` into `q`.

type AnySet

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

AnySet is a set stores any

func NewAnySet

func NewAnySet(eq func(a any, b any) bool, aa ...any) *AnySet

NewAnySet builds a AnySet

func (*AnySet) Difference

func (s *AnySet) Difference(rhs *AnySet) *AnySet

Difference returns the difference of two sets

func (*AnySet) Exist

func (s *AnySet) Exist(val any) bool

Exist checks whether `val` exists in `s`.

func (*AnySet) Insert

func (s *AnySet) Insert(val any)

Insert inserts `val` into `s`.

func (*AnySet) Intersection

func (s *AnySet) Intersection(rhs *AnySet) *AnySet

Intersection returns the intersection of two sets

func (*AnySet) Remove

func (s *AnySet) Remove(val any)

Remove removes `val` from `s`

func (*AnySet) Slice

func (s *AnySet) Slice() []any

Slice converts the set to a slice

type Constraint

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

Constraint for semver

func NewConstraint

func NewConstraint(raw string) (*Constraint, error)

NewConstraint creates a constraint to check whether a semver is valid. Only support ^ and ~ and x|X|*

func (*Constraint) Check

func (c *Constraint) Check(v string) bool

Check checks whether a version is satisfies the constraint

type HTTPClient

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

HTTPClient is a wrap of http.Client

func NewHTTPClient

func NewHTTPClient(timeout time.Duration, tlsConfig *tls.Config) *HTTPClient

NewHTTPClient returns a new HTTP client with timeout and HTTPS support

func (*HTTPClient) Client

func (c *HTTPClient) Client() *http.Client

Client returns the http.Client

func (*HTTPClient) Delete

func (c *HTTPClient) Delete(ctx context.Context, url string, body io.Reader) ([]byte, int, error)

Delete send a DELETE request to the url and returns the response and status code.

func (*HTTPClient) Download

func (c *HTTPClient) Download(ctx context.Context, url, filePath string) error

Download fetch an URL with GET method and Download the response to filePath

func (*HTTPClient) Get

func (c *HTTPClient) Get(ctx context.Context, url string) ([]byte, error)

Get fetch an URL with GET method and returns the response

func (*HTTPClient) GetWithStatusCode

func (c *HTTPClient) GetWithStatusCode(ctx context.Context, url string) ([]byte, int, error)

GetWithStatusCode fetch a URL with GET method and returns the response, also the status code.

func (*HTTPClient) Post

func (c *HTTPClient) Post(ctx context.Context, url string, body io.Reader) ([]byte, error)

Post send a POST request to the url and returns the response

func (*HTTPClient) PostWithStatusCode

func (c *HTTPClient) PostWithStatusCode(ctx context.Context, url string, body io.Reader) ([]byte, int, error)

PostWithStatusCode send a POST request to the url and returns the response, also the http status code.

func (*HTTPClient) Put

func (c *HTTPClient) Put(ctx context.Context, url string, body io.Reader) ([]byte, int, error)

Put send a PUT request to the url and returns the response, also the status code

func (*HTTPClient) SetRequestHeader

func (c *HTTPClient) SetRequestHeader(key, value string)

SetRequestHeader set http request header

func (*HTTPClient) WithClient

func (c *HTTPClient) WithClient(client *http.Client) *HTTPClient

WithClient uses the specified HTTP client

type HashValidationErr

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

HashValidationErr is the error indicates a failed hash validation

func (*HashValidationErr) Error

func (e *HashValidationErr) Error() string

Error implements the error interface

func (*HashValidationErr) Is

func (e *HashValidationErr) Is(target error) bool

Is implements the error interface

func (*HashValidationErr) Unwrap

func (e *HashValidationErr) Unwrap() error

Unwrap implements the error interface

type RetryOption

type RetryOption struct {
	Attempts int64
	Delay    time.Duration
	Timeout  time.Duration
}

RetryOption is options for Retry()

type StringSet

type StringSet map[string]struct{}

StringSet is a string set.

func NewStringSet

func NewStringSet(ss ...string) StringSet

NewStringSet builds a string set.

func (StringSet) Difference

func (s StringSet) Difference(rhs StringSet) StringSet

Difference returns the difference of two sets

func (StringSet) Exist

func (s StringSet) Exist(val string) bool

Exist checks whether `val` exists in `s`.

func (StringSet) Insert

func (s StringSet) Insert(val string)

Insert inserts `val` into `s`.

func (StringSet) Intersection

func (s StringSet) Intersection(rhs StringSet) StringSet

Intersection returns the intersection of two sets

func (StringSet) Join

func (s StringSet) Join(add StringSet) StringSet

Join add all elements of `add` to `s`.

func (StringSet) Remove

func (s StringSet) Remove(val string)

Remove removes `val` from `s`

func (StringSet) Slice

func (s StringSet) Slice() []string

Slice converts the set to a slice

type TableDisplayer

type TableDisplayer struct {
	Header []string
	Rows   [][]string
	Writer io.Writer
}

TableDisplayer is a simple table displayer

func NewTableDisplayer

func NewTableDisplayer(w io.Writer, header []string) *TableDisplayer

NewTableDisplayer creates a new TableDisplayer

func (*TableDisplayer) AddRow

func (t *TableDisplayer) AddRow(row ...string)

AddRow adds a row to the table

func (*TableDisplayer) Display

func (t *TableDisplayer) Display()

Display the table

type Version

type Version string

Version represents a version string, like: v3.1.2

func (Version) IsEmpty

func (v Version) IsEmpty() bool

IsEmpty returns true if the `Version` is a empty string

func (Version) IsNightly

func (v Version) IsNightly() bool

IsNightly returns true if the version is nightly

func (Version) IsValid

func (v Version) IsValid() bool

IsValid checks whether is the version string valid

func (Version) String

func (v Version) String() string

String implements the fmt.Stringer interface

Directories

Path Synopsis
process
process

Jump to

Keyboard shortcuts

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