jx: github.com/jenkins-x/jx/pkg/util Index | Files | Directories

package util

import "github.com/jenkins-x/jx/pkg/util"


Package Files

auth.go cache.go color.go commands.go constants.go date.go dirs.go downloads.go environ.go error.go files.go http_utils.go interface.go jenkinsfile_writer.go k8s.go maps.go markdown.go numbers.go padding.go pickers.go pom_flavour.go process.go regex.go retry.go strings.go structs.go suggestions.go test.go types.go unzip.go urls.go validation.go


const (
    // PlaceHolderPrefix is prefix for placeholders
    PlaceHolderPrefix = "REPLACE_ME"

    // PlaceHolderAppName placeholder for app name
    PlaceHolderAppName = PlaceHolderPrefix + "_APP_NAME"

    // PlaceHolderGitProvider placeholder for git provider
    PlaceHolderGitProvider = PlaceHolderPrefix + "_GIT_PROVIDER"

    // PlaceHolderOrg placeholder for org
    PlaceHolderOrg = PlaceHolderPrefix + "_ORG"

    // PlaceHolderDockerRegistryOrg placeholder for docker registry
    PlaceHolderDockerRegistryOrg = PlaceHolderPrefix + "_DOCKER_REGISTRY_ORG"
const (
    DefaultWritePermissions = 0760

    // DefaultFileWritePermissions default permissions when creating a file
    DefaultFileWritePermissions = 0644

    MaximumNewDirectoryAttempts = 1000
const (
    ALIGN_LEFT   = 0
    ALIGN_RIGHT  = 2
const (
    MAVEN        = "maven"
    MAVEN_JAVA11 = "maven-java11"
    APPSERVER    = "appserver"
    LIBERTY      = "liberty"
    DROPWIZARD   = "dropwizard"
const DateFormat = "January 2 2006"
const (
    DefaultSuggestionsMinimumDistance = 2


var ColorAnswer = color.New(color.FgCyan).SprintFunc()

ColorAnswer returns a new function that returns answer-colorized (cyan) strings for the given arguments with fmt.Sprint().

var ColorBold = color.New(color.Bold).SprintFunc()

ColorBold returns a new function that returns bold-colorized (bold) strings for the given arguments with fmt.Sprint().

var ColorError = color.New(color.FgRed).SprintFunc()

ColorError returns a new function that returns error-colorized (red) strings for the given arguments with fmt.Sprint().

var ColorInfo = color.New(color.FgGreen).SprintFunc()

ColorInfo returns a new function that returns info-colorized (green) strings for the given arguments with fmt.Sprint().

var ColorStatus = color.New(color.FgBlue).SprintFunc()

ColorStatus returns a new function that returns status-colorized (blue) strings for the given arguments with fmt.Sprint().

var ColorWarning = color.New(color.FgYellow).SprintFunc()

ColorWarning returns a new function that returns warning-colorized (yellow) strings for the given arguments with fmt.Sprint().

var DisallowedLabelCharacters = regexp.MustCompile("[^a-z0-9-]")

DisallowedLabelCharacters regex of chars not allowed in lables

func AsBool Uses

func AsBool(unk interface{}) (bool, error)

AsBool attempts to convert unk to a bool

func AsFloat64 Uses

func AsFloat64(unk interface{}) (float64, error)

AsFloat64 attempts to convert unk to a float64

func AsInt64 Uses

func AsInt64(unk interface{}) (int64, error)

AsInt64 attempts to convert unk to an int64

func AsMapOfStringsIntefaces Uses

func AsMapOfStringsIntefaces(unk interface{}) (map[string]interface{}, error)

AsMapOfStringsIntefaces attempts to convert unk to a map[string]interface{}

func AsSliceOfStrings Uses

func AsSliceOfStrings(unk interface{}) ([]string, error)

AsSliceOfStrings attempts to convert unk to a slice of strings

func AsString Uses

func AsString(unk interface{}) (string, error)

AsString attempts to convert unk to a string

func AtoInt32 Uses

func AtoInt32(text string) (int32, error)

func BackupDir Uses

func BackupDir() (string, error)

func BasicAuth Uses

func BasicAuth(username, password string) string

BasicAuth encodes the provided user name and password as basic auth credentials

func CacheDir Uses

func CacheDir() (string, error)

func CheckMark Uses

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 Uses

func ColorNameValues() []string

ColorNameValues returns all the color names sorted

func CombineErrors Uses

func CombineErrors(errs ...error) error

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

func CombineMapTrees Uses

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 Uses

func ConfigDir() (string, error)

func Confirm Uses

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 Uses

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

func ContentTypeForFileName Uses

func ContentTypeForFileName(name string) string

ContentTypeForFileName returns the MIME type for the given file name

func ConvertAllMapKeysToString Uses

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 CopyDir Uses

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

credit https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04

func CopyDirOverwrite Uses

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

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

func CopyDirPreserve Uses

func CopyDirPreserve(src string, dst string) error

CopyDirPreserve copies from the src dir to the dst dir if the file does NOT already exist in dst

func CopyFile Uses

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

credit https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04

func CopyFileOrDir Uses

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

CopyFileOrDir copies the source file or directory to the given destination

func CreateUniqueDirectory Uses

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 Uses

func DeleteDirContents(dir string) error

DeleteDirContents removes all the contents of the given directory

func DeleteDirContentsExcept Uses

func DeleteDirContentsExcept(dir string, exceptDir string) error

func DeleteFile Uses

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 DereferenceBool Uses

func DereferenceBool(b *bool) bool

DereferenceBool will return the bool value or the empty value for bool

func DereferenceFloat64 Uses

func DereferenceFloat64(f *float64) float64

DereferenceFloat64 will return the float64 value or the empty value for float64

func DereferenceInt Uses

func DereferenceInt(i *int) int

DereferenceInt will return the int value or the empty value for int

func DereferenceInt64 Uses

func DereferenceInt64(i *int64) int64

DereferenceInt64 will return the int value or the empty value for i

func DereferenceString Uses

func DereferenceString(s *string) string

DereferenceString will return the string value or the empty value for string

func DestroyFile Uses

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 Uses

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 DirExists Uses

func DirExists(path string) (bool, error)

DirExists checks if path exists and is a directory

func DownloadFile Uses

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

Download a file from the given URL

func DraftDir Uses

func DraftDir() (string, error)

func DurationString Uses

func DurationString(start *metav1.Time, end *metav1.Time) string

DurationString returns the duration between start and end time as string

func EncodeKubernetesName Uses

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 Uses

func EnvironmentsDir() (string, error)

func ExtractKeyValuePairs Uses

func ExtractKeyValuePairs(values []string, sep string) (map[string]string, error)

ExtractKeyValuePairs creates a map of an string array assuming that each array element is of the form <key><sep><value>. An error is returned is a array element cannot be split into a key/value pair using the specified separator.

func FileExists Uses

func FileExists(path string) (bool, error)

func FileIsEmpty Uses

func FileIsEmpty(path string) (bool, error)

FileIsEmpty checks if a file is empty

func FilterFileExists Uses

func FilterFileExists(paths []string) []string

FilterFileExists filters out files which do not exist

func FirstFileExists Uses

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 Uses

func FirstNotEmptyString(values ...string) string

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

func FormatDate Uses

func FormatDate(t time.Time) string

func GenerateSchema Uses

func GenerateSchema(target interface{}) *schemagen.Schema

GenerateSchema generates a JSON schema for the given struct type and returns it.

func GetAndCleanEnviron Uses

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

GetAndCleanEnviron cleans the provided env variables and returns their current value

func GetClient Uses

func GetClient() *http.Client

GetClient returns a Client reference with our default configuration

func GetClientWithTimeout Uses

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

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

func GetColor Uses

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

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

func GetCustomClient Uses

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

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

func GetLatestFullTagFromGithub Uses

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 Uses

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

GetLatestReleaseFromGitHub gets the latest Release from a specific github repo

func GetLatestReleaseFromGitHubURL Uses

func GetLatestReleaseFromGitHubURL(gitURL string) (string, error)

GetLatestReleaseFromGitHubURL returns the latest release version for the git URL

func GetLatestTagFromGithub Uses

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

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

func GetLatestVersionFromGitHub Uses

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

func GetLatestVersionStringCloudBeesBucketURLs Uses

func GetLatestVersionStringCloudBeesBucketURLs(versionStrings []string) (semver.Version, error)

GetLatestVersionStringCloudBeesBucketURLs return the latest version from a list of buckets with the version at the end of the path

func GetLatestVersionStringFromGitHub Uses

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

func GetMapValueAsIntViaPath Uses

func GetMapValueAsIntViaPath(m map[string]interface{}, path string) int

GetMapValueAsIntViaPath returns the int value at the given path mean `m["foo"]["bar"]["whatnot"]`

func GetMapValueAsMapViaPath Uses

func GetMapValueAsMapViaPath(m map[string]interface{}, path string) map[string]interface{}

GetMapValueAsMapViaPath returns the map value at the given path mean `m["foo"]["bar"]["whatnot"]`

func GetMapValueAsStringViaPath Uses

func GetMapValueAsStringViaPath(m map[string]interface{}, path string) string

GetMapValueAsStringViaPath returns the string value at the given path mean `m["foo"]["bar"]["whatnot"]`

func GetMapValueViaPath Uses

func GetMapValueViaPath(m map[string]interface{}, path string) interface{}

GetMapValueViaPath returns the value at the given path mean `m["foo"]["bar"]["whatnot"]`

func GetMockAPIResponseFromFile Uses

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 Uses

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

GetTagsFromGithub gets the list of tags on a specific github repo

func GlobAllFiles Uses

func GlobAllFiles(basedir string, pattern string, fn func(string) error) error

GlobAllFiles performs a glob on the pattern and then processes all the files found. if a folder matches the glob its treated as another glob to recurse into the directory

func HashPassword Uses

func HashPassword(password string) string

HashPassword hashes the given password with SHA1

func HomeDir Uses

func HomeDir() string

func IgnoreFile Uses

func IgnoreFile(path string, ignores []string) (bool, error)

IgnoreFile returns true if the path matches any of the ignores. The match is the same as filepath.Match.

func Int32ToA Uses

func Int32ToA(n int32) string

func InvalidArg Uses

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

func InvalidArgError Uses

func InvalidArgError(value string, err error) error

func InvalidArgf Uses

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

func InvalidOption Uses

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

func InvalidOptionError Uses

func InvalidOptionError(option string, value interface{}, err error) error

InvalidOptionError returns an error that shows the invalid option

func InvalidOptionf Uses

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

InvalidOptionf returns an error that shows the invalid option

func IsEmpty Uses

func IsEmpty(name string) (bool, error)

func IsZeroOfUnderlyingType Uses

func IsZeroOfUnderlyingType(x interface{}) bool

IsZeroOfUnderlyingType checks if the underlying type of the interface is set to it's zero value

func JXBinLocation Uses

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 Uses

func JXBinaryLocation() (string, error)

JXBinaryLocation Returns the path to the currently installed JX binary.

func KeyValuesToMap Uses

func KeyValuesToMap(values []string) map[string]string

KeyValuesToMap converts the set of values of the form "foo=abc" into a map

func KillProcesses Uses

func KillProcesses(binary string) error

func KillProcessesTree Uses

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

func KubeConfigFile Uses

func KubeConfigFile() string

KubeConfigFile gets the .kube/config file

func ListDirectory Uses

func ListDirectory(root string, recurse bool) error

ListDirectory logs the directory at path

func LoadBytes Uses

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

loads a file

func LoadCacheData Uses

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

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

func LocalFileSystemSecretsDir Uses

func LocalFileSystemSecretsDir() (string, error)

LocalFileSystemSecretsDir returns the default local file system secrets location for the file system alternative to vault

func LogsDir Uses

func LogsDir() (string, error)

func MapKeys Uses

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

MapKeys returns the keys of a given map

func MapToKeyValues Uses

func MapToKeyValues(values map[string]string) []string

MapToKeyValues converts the the map into a sorted array of key/value pairs

func MapToString Uses

func MapToString(m map[string]string) string

MapToString converts the map to a string

func MarkdownLink(text string, url string) string

MarkdownLink returns a markdown link

func MavenBinaryLocation Uses

func MavenBinaryLocation() (string, error)

func MergeMaps Uses

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 Uses

func MissingArgument(name string) error

MissingArgument reports a missing command line argument name

func MissingEnv Uses

func MissingEnv(name string) error

MissingEnv reports a missing environment variable

func MissingOption Uses

func MissingOption(name string) error

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

func MissingOptionWithOptions Uses

func MissingOptionWithOptions(name string, options []string) error

MissingOptionWithOptions reports a missing command line option using the full name expression along with a list of available values

func OrganisationsDir Uses

func OrganisationsDir() (string, error)

func Pad Uses

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

func PadCenter Uses

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

func PadLeft Uses

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

func PadRight Uses

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

func ParseBool Uses

func ParseBool(text string) (bool, error)

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

func ParseDate Uses

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

func PathWithBinary Uses

func PathWithBinary(paths ...string) string

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

func PickName Uses

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 Uses

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 Uses

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

func PickNamesWithDefaults Uses

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

PickNamesWithDefaults gets the user to pick multiple selections from a list of options with a set of default selections

func PickPassword Uses

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 Uses

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 Uses

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 Uses

func PluginBinDir(ns string) (string, error)

PluginBinDir returns the plugin bin directory for the given ns

func PomFlavour Uses

func PomFlavour(path string) (string, error)

func PrettyPrint Uses

func PrettyPrint(i interface{}) string

PrettyPrint returns an indented string representation of the passed struct for the purpose of logging/debugging.

func QuestionAnswer Uses

func QuestionAnswer(question string, answer string) string

QuestionAnswer returns strings like Cobra question/answers for default cli options

func RandStringBytesMaskImprSrc Uses

func RandStringBytesMaskImprSrc(n int) (string, error)

RandStringBytesMaskImprSrc returns a random hexadecimal string of length n.

func RecreateDirs Uses

func RecreateDirs(dirs ...string) error

DeleteDirContents removes all the contents of the given directory

func RegexpSplit Uses

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

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

func RemoveScheme Uses

func RemoveScheme(u string) string

RemoveScheme removes the scheme from a URL

func RemoveStringFromSlice Uses

func RemoveStringFromSlice(strings []string, toRemove string) []string

RemoveStringFromSlice removes the first occurrence of the specified string from a slice, if it exists and returns the result

func RenameDir Uses

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

func RenameFile Uses

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

func ReplaceAllStringSubmatchFunc Uses

func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func(groups []Group) []string) string

ReplaceAllStringSubmatchFunc will replace all the submatches found in str by re by calling repl and replacing each submatch with the result. Both the argument and the result of repl ignore the entire match (i.e. the item at index 0 is the first submatch)

func RestoreEnviron Uses

func RestoreEnviron(environ map[string]string) error

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

func Retry Uses

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

Retry retries with exponential backoff the given function

func RetryWithInitialDelay Uses

func RetryWithInitialDelay(initialDelay, maxElapsedTime time.Duration, f func() error) error

RetryWithInitialDelay retires with exponential backoff and initial delay the given function

func RetryWithInitialDelaySlower Uses

func RetryWithInitialDelaySlower(initialDelay, maxElapsedTime time.Duration, f func() error) error

RetryWithInitialDelaySlower retries with exponential backoff, an initial delay and with a slower rate

func ReverseStrings Uses

func ReverseStrings(a []string)

func RunCommandBackground Uses

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

func SanitizeLabel Uses

func SanitizeLabel(label string) string

SanitizeLabel returns a label with disallowed characters removed

func SelectNames Uses

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 Uses

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 SetMapValueViaPath Uses

func SetMapValueViaPath(m map[string]interface{}, path string, value interface{})

SetMapValueViaPath sets the map key using the given path which supports the form `foo.bar.whatnot` to mean `m["foo"]["bar"]["whatnot"]` lazily creating maps as the path is navigated

func SortedMapKeys Uses

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

SortedMapKeys returns the sorted keys of the given map

func StartsWith Uses

func StartsWith(s, substr string) bool

StartsWith returns true if the string starts with the given substring

func StringArrayHasPrefixIndex Uses

func StringArrayHasPrefixIndex(array []string, prefix string) int

StringArrayHasPrefixIndex returns the index in the slice which the value has the given prefix

func StringArrayIndex Uses

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

StringArrayIndex returns the index in the slice which equals the given value

func StringArrayToLower Uses

func StringArrayToLower(values []string) []string

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

func StringArraysEqual Uses

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

StringArraysEqual returns true if the two string slices are equal

func StringContainsAny Uses

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

StringContainsAny returns true if the given text contains the includes/excludes lists

func StringIndexes Uses

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

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

func StringMapHasValue Uses

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

StringMapHasValue returns true if the given map contains the given value

func StringMatchesAny Uses

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

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

func StringMatchesPattern Uses

func StringMatchesPattern(text string, pattern string) bool

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

func StringsContaining Uses

func StringsContaining(slice []string, filter string) []string

StringsContaining if the filter is not empty return all the strings which contain the text

func StripCredentialsFromURL Uses

func StripCredentialsFromURL(u *url.URL) string

StripCredentialsFromURL strip credentials from URL

func StripTrailingSlash Uses

func StripTrailingSlash(url string) string

StripTrailingSlash removes any trailing forward slashes on the URL

func SuggestionsFor Uses

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

func ToMapStringInterfaceFromStruct Uses

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 ToObjectMap Uses

func ToObjectMap(object interface{}) (map[string]interface{}, error)

ToObjectMap converts the given object into a map of strings/maps using YAML marshalling

func ToStringMapStringFromStruct Uses

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 Uses

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 ToValidFileSystemName Uses

func ToValidFileSystemName(name string) string

ToValidFileSystemName converts the name to one that can safely be used on the filesystem

func URLEqual Uses

func URLEqual(url1, url2 string) bool

URLEqual verifies if URLs are equal

func URLToHostName Uses

func URLToHostName(svcURL string) string

URLToHostName converts the given URL to a host name returning the error string if its not a URL

func UnTarFile Uses

func UnTarFile(header *tar.Header, path string, tarReader *tar.Reader) error

UnTarFile extracts one file from the tar, or creates a directory

func UnTargz Uses

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 Uses

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 Uses

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 Uses

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 Uses

func UrlHostNameWithoutPort(rawUri string) (string, error)

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

func UrlJoin Uses

func UrlJoin(paths ...string) string

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

func ValidateYaml Uses

func ValidateYaml(target interface{}, data []byte) ([]string, error)

ValidateYaml generates a JSON schema for the given struct type, and then validates the given YAML against that schema, ignoring Containers and missing fields.

func WriteJenkinsfileStatements Uses

func WriteJenkinsfileStatements(indentCount int, statements []*Statement) string

WriteJenkinsfileStatements writes the given Jenkinsfile statements as a string

func YesNo Uses

func YesNo(t bool) string

YesNo returns a Yes/No conversion for a boolean parameter

type CacheLoader Uses

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

CacheLoader defines cache value population callback that should be executed if cache entry with given key is not present.

type Command Uses

type Command struct {
    Errors             []error
    Dir                string
    Name               string
    Args               []string
    ExponentialBackOff *backoff.ExponentialBackOff
    Timeout            time.Duration
    Out                io.Writer
    Err                io.Writer
    In                 io.Reader
    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 Uses

func (c *Command) Attempts() int

Attempts The number of times the command has been executed

func (*Command) CurrentArgs Uses

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

CurrentArgs returns the current command arguments

func (*Command) CurrentDir Uses

func (c *Command) CurrentDir() string

CurrentDir returns the current Dir

func (*Command) CurrentEnv Uses

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

CurrentEnv returns the current environment variables

func (*Command) CurrentName Uses

func (c *Command) CurrentName() string

CurrentName returns the current name of the command

func (*Command) DidError Uses

func (c *Command) DidError() bool

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

func (*Command) DidFail Uses

func (c *Command) DidFail() bool

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

func (*Command) Error Uses

func (c *Command) Error() error

Error returns the last error

func (*Command) Run Uses

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

Run Execute the command and block waiting for return values

func (*Command) RunWithoutRetry Uses

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

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

func (*Command) SetArgs Uses

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

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

func (*Command) SetDir Uses

func (c *Command) SetDir(dir string)

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

func (*Command) SetEnv Uses

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 Uses

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

SetEnvVariable sets an environment variable into the environment

func (*Command) SetExponentialBackOff Uses

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

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

func (*Command) SetName Uses

func (c *Command) SetName(name string)

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

func (*Command) SetTimeout Uses

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

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

func (*Command) String Uses

func (c *Command) String() string

type CommandError Uses

type CommandError struct {
    Command Command
    Output  string
    // contains filtered or unexported fields

CommandError is the error object encapsulating an error from a Command

func (CommandError) Error Uses

func (c CommandError) Error() string

type Commander Uses

type Commander interface {
    DidError() bool
    DidFail() bool
    Error() error
    Run() (string, error)
    RunWithoutRetry() (string, error)
    CurrentName() string
    CurrentDir() string
    CurrentArgs() []string
    CurrentEnv() map[string]string
    SetEnvVariable(string, string)

Commander defines the interface for a Command go:generate pegomock generate github.com/jenkins-x/jx/pkg/util Commander -o mocks/commander.go

type Group Uses

type Group struct {
    Value string
    Start int
    End   int

Group is a submatch group

type MethodMap Uses

type MethodMap map[string]string

type Router Uses

type Router map[string]MethodMap

type Statement Uses

type Statement struct {
    Function  string
    Arguments []string
    Statement string
    Children  []*Statement

Statement represents a statement in a Jenkinsfile

func (*Statement) ContextEquals Uses

func (s *Statement) ContextEquals(that *Statement) bool

ContextEquals returns true if this statement is a context statement and it equals the same context as that statement

func (*Statement) Text Uses

func (s *Statement) Text() string

Text returns the text line of the current function or statement

type Writer Uses

type Writer struct {
    InitialIndent string
    IndentText    string
    Buffer        bytes.Buffer
    IndentCount   int

Writer implements the struct for Jenkinsfilewriter

func NewWriter Uses

func NewWriter(indentCount int) *Writer

NewWriter creates a Jenkinsfile writer

func (*Writer) String Uses

func (w *Writer) String() string

String returns the string value of this writer

func (*Writer) Write Uses

func (w *Writer) Write(inputStatements []*Statement)



Package util imports 49 packages (graph) and is imported by 114 packages. Updated 2019-09-16. Refresh now. Tools for package owners.