util

package
v1.3.633 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2018 License: Apache-2.0 Imports: 41 Imported by: 130

Documentation

Index

Constants

View Source
const (
	DefaultWritePermissions = 0760

	MaximumNewDirectoryAttempts = 1000
)
View Source
const (
	ALIGN_LEFT   = 0
	ALIGN_CENTER = 1
	ALIGN_RIGHT  = 2
)
View Source
const (
	APPSERVER  = "appserver"
	LIBERTY    = "liberty"
	DROPWIZARD = "dropwizard"
)
View Source
const DateFormat = "January 2 2006"
View Source
const (
	DefaultSuggestionsMinimumDistance = 2
)

Variables

View Source
var ColorError = color.New(color.FgRed).SprintFunc()
View Source
var ColorInfo = color.New(color.FgGreen).SprintFunc()
View Source
var ColorStatus = color.New(color.FgBlue).SprintFunc()
View Source
var ColorWarning = color.New(color.FgYellow).SprintFunc()

Functions

func AtoInt32

func AtoInt32(text string) (int32, error)

func BackupDir

func BackupDir() (string, error)

func BasicAuth

func BasicAuth(username, password string) string

func CacheDir

func CacheDir() (string, error)

func CheckMark

func CheckMark() string

CheckMark returns the check mark unicode character. We could configure this to use no color or avoid unicode using platform, env vars or config?

func ColorNameValues

func ColorNameValues() []string

ColorNameValues returns all the color names sorted

func CombineErrors

func CombineErrors(errs ...error) error

Combine combines the non null errors into a single error or returns null

func CombineMapTrees

func CombineMapTrees(destination map[string]interface{}, input map[string]interface{})

CombineMapTrees recursively copies all the values from the input map into the destination map preserving any missing entries in the destination

func ConfigDir

func ConfigDir() (string, error)

func Confirm

func Confirm(message string, defaultValue bool, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) bool

Confirm prompts the user to confirm something

func Contains

func Contains(arr []string, str string) bool

func ConvertAllMapKeysToString

func ConvertAllMapKeysToString(i interface{}) interface{}

ConvertAllMapKeysToString will recursively go through an object and convert all keys of a map (and any submaps) to Strings. This is necessary for json handlers (eg vault) where an item of a submap must be map[string]interface{} rather than the more lenient map[interface{}]interface{} that you get from yaml unmarshalling

func CopyDirOverwrite

func CopyDirOverwrite(src string, dst string) (err error)

CopyDirOverwrite copies from the source dir to the destination dir overwriting files along the way

func CreateUniqueDirectory

func CreateUniqueDirectory(dir string, name string, maximumAttempts int) (string, error)

CreateUniqueDirectory creates a new directory but if the combination of dir and name exists then append a number until a unique name is found

func DeleteDirContents

func DeleteDirContents(dir string) error

DeleteDirContents removes all the contents of the given directory

func DeleteFile

func DeleteFile(fileName string) (err error)

DeleteFile deletes a file from the operating system. This should NOT be used to delete any sensitive information because it can easily be recovered. Use DestroyFile to delete sensitive information

func DestroyFile

func DestroyFile(filename string) error

DestroyFile will securely delete a file by first overwriting it with random bytes, then deleting it. This should always be used for deleting sensitive information

func DiffSlices

func DiffSlices(oldSlice []string, newSlice []string) ([]string, []string)

DiffSlices compares the two slices and returns an array of items to delete from the old slice and a slice of new values to add to

func DownloadFile

func DownloadFile(filepath string, url string) (err error)

Download a file from the given URL

func DraftDir

func DraftDir() (string, error)

func EncodeKubernetesName

func EncodeKubernetesName(name string) string

EncodeKubernetesName takes a string and turns it into a form suitable for use as a Kubernetes name. Note there is no decode functionality provided atm (and things like escaping escape codes aren't handled), so round-tripping is not possible yet. K8S names are lower case, numbers, '-', and '.'. Invalid characters are percent-encoded in a _similar_ way to URL encoding, with a period ('.') followed by the numerical character code. Conversion is:

Upper case letters -> lower case.
'a-z', '0-9', '-', '.' -> left as-is.
Any other characters: percent-encoded ('.' + rune hex code).

func EnvironmentsDir

func EnvironmentsDir() (string, error)

func FileExists

func FileExists(path string) (bool, error)

func FirstFileExists

func FirstFileExists(paths ...string) (string, error)

FirstFileExists returns the first file which exists or an error if we can't detect if a file that exists

func FirstNotEmptyString

func FirstNotEmptyString(values ...string) string

FirstNotEmptyString returns the first non empty string or the empty string if none can be found

func FormatDate

func FormatDate(t time.Time) string

func GetAndCleanEnviron

func GetAndCleanEnviron(keys []string) (map[string]string, error)

GetAndCleanEnviron cleans the provided env variables and returns their current value

func GetClient

func GetClient() *http.Client

GetClient returns a Client reference with our default configuration

func GetClientWithTimeout

func GetClientWithTimeout(duration time.Duration) *http.Client

GetClientWithTimeout returns a client with JX default transport and user specified timeout

func GetColor

func GetColor(optionName string, colorNames []string) (*color.Color, error)

GetColor returns the color for the list of colour names and option name

func GetCustomClient

func GetCustomClient(transport http.RoundTripper, timeout int) *http.Client

GetCustomClient returns a client with user specified transport and timeout (in seconds)

func GetLatestFullTagFromGithub

func GetLatestFullTagFromGithub(githubOwner, githubRepo string) (string, error)

GetLatestFullTagFromGithub gets the latest 'full' tag from a specific github repo. This (at present) ignores releases with a hyphen in it, usually used with -SNAPSHOT, or -RC1 or -beta

func GetLatestReleaseFromGitHub

func GetLatestReleaseFromGitHub(githubOwner, githubRepo string) (string, error)

GetLatestReleaseFromGitHub gets the latest Release from a specific github repo

func GetLatestTagFromGithub

func GetLatestTagFromGithub(githubOwner, githubRepo string) (string, error)

GetLatestTagFromGithub gets the latest (in github order) tag from a specific github repo

func GetLatestVersionFromGitHub

func GetLatestVersionFromGitHub(githubOwner, githubRepo string) (semver.Version, error)

func GetLatestVersionStringFromGitHub

func GetLatestVersionStringFromGitHub(githubOwner, githubRepo string) (string, error)

func GetMockAPIResponseFromFile

func GetMockAPIResponseFromFile(dataDir string, route MethodMap) mocker

@param dataDir Location of test data json file @param router Should map a URL path to a map that maps a method to a JSON response file name. Conceptually: (url, method) -> file See pkg/gits/bitbucket_cloud_test.go for an example.

func GetTagsFromGithub

func GetTagsFromGithub(githubOwner, githubRepo string) ([]*github.RepositoryTag, error)

GetTagsFromGithub gets the list of tags on a specific github repo

func HomeDir

func HomeDir() string

func Int32ToA

func Int32ToA(n int32) string

func InvalidArg

func InvalidArg(value string, values []string) error

func InvalidArgError

func InvalidArgError(value string, err error) error

func InvalidArgf

func InvalidArgf(value string, message string, a ...interface{}) error

func InvalidOption

func InvalidOption(name string, value string, values []string) error

func InvalidOptionError

func InvalidOptionError(option string, value string, err error) error

func InvalidOptionf

func InvalidOptionf(option string, value string, message string, a ...interface{}) error

func IsEmpty

func IsEmpty(name string) (bool, error)

func JXBinLocation

func JXBinLocation() (string, error)

JXBinLocation finds the JX config directory and creates a bin directory inside it if it does not already exist. Returns the JX bin path

func JXBinaryLocation

func JXBinaryLocation() (string, error)

JXBinaryLocation Returns the path to the currently installed JX binary.

func KillProcesses

func KillProcesses(binary string) error

func KillProcessesTree

func KillProcessesTree(binary string, processes []*process.Process, m map[int32]bool) (bool, error)

func LoadBytes

func LoadBytes(dir, name string) ([]byte, error)

loads a file

func LoadCacheData

func LoadCacheData(fileName string, loader CacheLoader) ([]byte, error)

LoadCacheData loads cached data from the given cache file name and loader

func LogsDir

func LogsDir() (string, error)

func MapKeys

func MapKeys(m map[string]string) []string

MapKeys returns the keys of a given map

func MarkdownLink(text string, url string) string

MarkdownLink returns a markdown link

func MavenBinaryLocation

func MavenBinaryLocation() (string, error)

func MergeMaps

func MergeMaps(maps ...map[string]string) map[string]string

MergeMaps merges all the maps together with the entries in the last map overwriting any earlier values

so if you want to add some annotations to a resource you can do resource.Annotations = kube.MergeMaps(resource.Annotations, myAnnotations)

func MissingArgument

func MissingArgument(name string) error

MissingArgument reports a missing command line argument name

func MissingOption

func MissingOption(name string) error

MissingOption reports a missing command line option using the full name expression

func NoWhiteSpaceValidator added in v1.3.600

func NoWhiteSpaceValidator() survey.Validator

NoWhiteSpaceValidator is an input validator for the survey package that disallows any whitespace in the input

func OrganisationsDir

func OrganisationsDir() (string, error)

func Pad

func Pad(s, pad string, width int, align int) string

func PadCenter

func PadCenter(s, pad string, width int) string

func PadLeft

func PadLeft(s, pad string, width int) string

func PadRight

func PadRight(s, pad string, width int) string

func ParseBool

func ParseBool(text string) (bool, error)

ParseBool parses the boolean string. Returns false if the string is empty

func ParseDate

func ParseDate(dateText string) (time.Time, error)

func PathWithBinary

func PathWithBinary(paths ...string) string

PathWithBinary Sets the $PATH variable. Accepts an optional slice of strings containing paths to add to $PATH

func PickName

func PickName(names []string, message string, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) (string, error)

PickName gets the user to pick an option from a list of options

func PickNameWithDefault

func PickNameWithDefault(names []string, message string, defaultValue string, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) (string, error)

PickNameWithDefault gets the user to pick an option from a list of options, with a default option specified

func PickNames

func PickNames(names []string, message string, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) ([]string, error)

PickNames gets the user to pick multiple selections from a list of options, with a default option specified

func PickPassword

func PickPassword(message string, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) (string, error)

PickPassword gets a password (via hidden input) from a user's free-form input

func PickRequiredNameWithDefault

func PickRequiredNameWithDefault(names []string, message string, defaultValue string, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) (string, error)

PickRequiredNameWithDefault gets the user to pick an option from a list of options, with a default option specified

func PickValue

func PickValue(message string, defaultValue string, required bool, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) (string, error)

PickValue gets an answer to a prompt from a user's free-form input

func PluginBinDir

func PluginBinDir(ns string) (string, error)

PluginBinDir returns the plugin bin directory for the given ns

func PomFlavour

func PomFlavour(path string) (string, error)

func RandStringBytesMaskImprSrc

func RandStringBytesMaskImprSrc(n int) (string, error)

RandStringBytesMaskImprSrc returns a random hexadecimal string of length n.

func RecreateDirs

func RecreateDirs(dirs ...string) error

DeleteDirContents removes all the contents of the given directory

func RegexpSplit

func RegexpSplit(text string, regexSeperator string) []string

RegexpSplit splits a string into an array using the regexSep as a separator

func RenameDir

func RenameDir(src string, dst string, force bool) (err error)

func RenameFile

func RenameFile(src string, dst string) (err error)

func RestoreEnviron

func RestoreEnviron(environ map[string]string) error

RestoreEnviron sets the in the environment the environment variables provided as input

func Retry

func Retry(maxElapsedTime time.Duration, f func() error) error

Retry retries with exponential backoff the given function

func ReverseStrings

func ReverseStrings(a []string)

func RunCommandBackground

func RunCommandBackground(name string, output io.Writer, verbose bool, args ...string) error

func SelectNames

func SelectNames(names []string, message string, selectAll bool, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) ([]string, error)

SelectNames select which names from the list should be chosen

func SelectNamesWithFilter

func SelectNamesWithFilter(names []string, message string, selectAll bool, filter string, help string, in terminal.FileReader, out terminal.FileWriter, outErr io.Writer) ([]string, error)

SelectNamesWithFilter selects from a list of names with a given filter. Optionally selecting them all

func SortedMapKeys

func SortedMapKeys(m map[string]string) []string

SortedMapKeys returns the sorted keys of the given map

func StringArrayIndex

func StringArrayIndex(array []string, value string) int

func StringArrayToLower

func StringArrayToLower(values []string) []string

StringArrayToLower returns a string slice with all the values converted to lower case

func StringArraysEqual

func StringArraysEqual(a1 []string, a2 []string) bool

StringArraysEqual returns true if the two string slices are equal

func StringIndexes

func StringIndexes(text string, value string) []int

StringIndexes returns all the indices where the value occurs in the given string

func StringMapHasValue

func StringMapHasValue(m map[string]string, value string) bool

StringMapHasValue returns true if the given map contains the given value

func StringMatchesAny

func StringMatchesAny(text string, includes []string, excludes []string) bool

StringMatches returns true if the given text matches the includes/excludes lists

func StringMatchesPattern

func StringMatchesPattern(text string, pattern string) bool

StringMatchesPattern returns true if the given text matches the includes/excludes lists

func SuggestionsFor

func SuggestionsFor(typedName string, values []string, suggestionsMinimumDistance int, explicitSuggestions ...string) []string

func ToMapStringInterfaceFromStruct

func ToMapStringInterfaceFromStruct(obj interface{}) (map[string]interface{}, error)

ToMapStringInterfaceFromStruct marshals a struct to a generic map[string]interface{} by marshalling it to json and back Use JSON for the marshalling instead of YAML because sub-structs will get marshalled into map[interface{}]interface{} when using YAML, but map[string]interface{} when using JSON and vault libraries can't handle map[interface{}]interface{}

func ToStringMapStringFromStruct

func ToStringMapStringFromStruct(obj interface{}) map[string]string

ToStringMapStringFromStruct returns string[map]string from any struct. Use structs tag to change map keys. e.g. ServerName string `structs:"server_name"`

func ToStructFromMapStringInterface

func ToStructFromMapStringInterface(m map[string]interface{}, str interface{}) error

ToStructFromMapStringInterface marshals a generic map[string]interface{} to a struct by marshalling to json and back Use JSON for the marshalling instead of YAML because sub-structs will get marshalled into map[interface{}]interface{} when using YAML, but map[string]interface{} when using JSON and vault libraries can't handle map[interface{}]interface{}

func URLEqual

func URLEqual(url1, url2 string) bool

URLEqual verifies if URLs are equal

func UnTargz

func UnTargz(tarball, target string, onlyFiles []string) error

untargz a tarball to a target, from http://blog.ralch.com/tutorial/golang-working-with-tar-and-gzipf

func UnTargzAll

func UnTargzAll(tarball, target string) error

untargz a tarball to a target including any folders inside the tarball http://blog.ralch.com/tutorial/golang-working-with-tar-and-gzipf

func Unzip

func Unzip(src, dest string) error

Unzips the archvie into the specified directory returns an error if a general issue occurred unzipping the archive

func UnzipSpecificFiles

func UnzipSpecificFiles(src, dest string, onlyFiles ...string) error

Unzips the specified files from the archive returns an error if any of the specified files are not found or a general issue occurred unzipping the archive

func UrlHostNameWithoutPort

func UrlHostNameWithoutPort(rawUri string) (string, error)

UrlHostNameWithoutPort returns the host name without any port of the given URL like string

func UrlJoin

func UrlJoin(paths ...string) string

UrlJoin joins the given paths so that there is only ever one '/' character between the paths

Types

type CacheLoader

type CacheLoader func() ([]byte, error)

type Command

type Command struct {
	Errors             []error
	Dir                string
	Name               string
	Args               []string
	ExponentialBackOff *backoff.ExponentialBackOff
	Timeout            time.Duration
	Out                io.Writer
	Err                io.Writer
	Env                map[string]string
	// contains filtered or unexported fields
}

Command is a struct containing the details of an external command to be executed

func (*Command) Attempts

func (c *Command) Attempts() int

Attempts The number of times the command has been executed

func (*Command) CurrentArgs

func (c *Command) CurrentArgs() []string

CurrentArgs returns the current command arguments

func (*Command) CurrentDir

func (c *Command) CurrentDir() string

CurrentDir returns the current Dir

func (*Command) CurrentEnv

func (c *Command) CurrentEnv() map[string]string

CurrentEnv returns the current envrionment variables

func (*Command) CurrentName

func (c *Command) CurrentName() string

CurrentName returns the current name of the command

func (*Command) DidError

func (c *Command) DidError() bool

DidError returns a boolean if any error occurred in any execution of the command

func (*Command) DidFail

func (c *Command) DidFail() bool

DidFail returns a boolean if the command could not complete (errored on every attempt)

func (*Command) Error

func (c *Command) Error() error

Error returns the last error

func (*Command) Run

func (c *Command) Run() (string, error)

Run Execute the command and block waiting for return values

func (*Command) RunWithoutRetry

func (c *Command) RunWithoutRetry() (string, error)

RunWithoutRetry Execute the command without retrying on failure and block waiting for return values

func (*Command) SetArgs

func (c *Command) SetArgs(args []string)

SetArgs Setter method for Args to enable use of interface instead of Command struct

func (*Command) SetDir

func (c *Command) SetDir(dir string)

SetDir Setter method for Dir to enable use of interface instead of Command struct

func (*Command) SetEnv

func (c *Command) SetEnv(env map[string]string)

SetEnv Setter method for Env to enable use of interface instead of Command struct

func (*Command) SetEnvVariable

func (c *Command) SetEnvVariable(name string, value string)

SetEnvVariable sets an environment variable into the environment

func (*Command) SetExponentialBackOff

func (c *Command) SetExponentialBackOff(backoff *backoff.ExponentialBackOff)

SetExponentialBackOff Setter method for ExponentialBackOff to enable use of interface instead of Command struct

func (*Command) SetName

func (c *Command) SetName(name string)

SetName Setter method for Name to enable use of interface instead of Command struct

func (*Command) SetTimeout

func (c *Command) SetTimeout(timeout time.Duration)

SetTimeout Setter method for Timeout to enable use of interface instead of Command struct

type Commander

type Commander interface {
	DidError() bool
	DidFail() bool
	Error() error
	Run() (string, error)
	RunWithoutRetry() (string, error)
	SetName(string)
	CurrentName() string
	SetDir(string)
	CurrentDir() string
	SetArgs([]string)
	CurrentArgs() []string
	SetTimeout(time.Duration)
	SetExponentialBackOff(*backoff.ExponentialBackOff)
	SetEnv(map[string]string)
	CurrentEnv() map[string]string
	SetEnvVariable(string, string)
}

Commander defines the interface for a Command

type MethodMap

type MethodMap map[string]string

type Router

type Router map[string]MethodMap

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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