util

package
v2.1.83 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2020 License: Apache-2.0 Imports: 50 Imported by: 16

Documentation

Index

Constants

View Source
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"

	// DefaultGitUserName default value to use for git "user.name"
	DefaultGitUserName = "jenkins-x-bot"

	// DefaultGitUserEmail default value to use for git "user.email"
	DefaultGitUserEmail = "jenkins-x@googlegroups.com"

	// EnvVarBranchName is the environment variable that will hold the name of the branch being built during pipelines
	EnvVarBranchName = "BRANCH_NAME"
)
View Source
const (
	DefaultWritePermissions = 0760

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

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

Variables

View Source
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().

View Source
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().

View Source
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().

View Source
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().

View Source
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().

View Source
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().

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

DisallowedLabelCharacters regex of chars not allowed in lables

Functions

func AsBool

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

AsBool attempts to convert unk to a bool

func AsFloat64

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

AsFloat64 attempts to convert unk to a float64

func AsInt64

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

AsInt64 attempts to convert unk to an int64

func AsMapOfStringsIntefaces

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

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

func AsSliceOfStrings

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

AsSliceOfStrings attempts to convert unk to a slice of strings

func AsString

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

AsString attempts to convert unk to a string

func AtoInt32

func AtoInt32(text string) (int32, error)

func BackupDir

func BackupDir() (string, error)

func BasicAuth

func BasicAuth(username, password string) string

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

func CacheDir

func CacheDir() (string, error)

func CallWithExponentialBackOff

func CallWithExponentialBackOff(url string, auth string, httpMethod string, reqBody []byte, reqParams url.Values) ([]byte, error)

CallWithExponentialBackOff make a http call with exponential backoff retry

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 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, handles IOFileHandles) (bool, error)

Confirm prompts the user to confirm something

func Contains

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

func ContentTypeForFileName

func ContentTypeForFileName(name string) string

ContentTypeForFileName returns the MIME type for the given file name

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 CopyDirPreserve

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 CopyFileOrDir

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

CopyFileOrDir copies the source file or directory to the given destination

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 DeleteDirContentsExcept

func DeleteDirContentsExcept(dir string, exceptDir string) error

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 DereferenceBool

func DereferenceBool(b *bool) bool

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

func DereferenceFloat64

func DereferenceFloat64(f *float64) float64

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

func DereferenceInt

func DereferenceInt(i *int) int

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

func DereferenceInt64

func DereferenceInt64(i *int64) int64

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

func DereferenceString

func DereferenceString(s *string) string

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

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 DirExists

func DirExists(path string) (bool, error)

DirExists checks if path exists and is a directory

func DownloadFile

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

Download a file from the given URL

func DraftDir

func DraftDir() (string, error)

func DurationString

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

DurationString returns the duration between start and end time as string

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 ExtractKeyValuePairs

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

func FileExists(path string) (bool, error)

FileExists checks if path exists and is a file

func FileIsEmpty

func FileIsEmpty(path string) (bool, error)

FileIsEmpty checks if a file is empty

func FilterFileExists

func FilterFileExists(paths []string) []string

FilterFileExists filters out files which do not exist

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 GenerateSchema

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

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

func GetAndCleanEnviron

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

GetAndCleanEnviron cleans the provided env variables and returns their current value

func GetBasicAuthUserAndPassword

func GetBasicAuthUserAndPassword(auth string) (string, string)

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) (*github.RepositoryTag, 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 GetLatestReleaseFromGitHubURL

func GetLatestReleaseFromGitHubURL(gitURL string) (string, error)

GetLatestReleaseFromGitHubURL returns the latest release version for the git URL

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 GetLatestVersionStringFromBucketURLs

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

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

func GetLatestVersionStringFromGitHub

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

func GetMapValueAsIntViaPath

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

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

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

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

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

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 GetSh

func GetSh() string

GetSh returns the default sh path. Windows returns sh, other platform returns /bin/sh.

func GetTagsFromGithub

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

GetTagsFromGithub gets the list of tags on a specific github repo

func GitCredentialsFile

func GitCredentialsFile() string

GitCredentialsFile returns the location of the git credentials file

func GlobAllFiles

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

func HashPassword(password string) string

HashPassword hashes the given password with SHA1

func HomeDir

func HomeDir() string

func IgnoreFile

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

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 interface{}, err error) error

InvalidOptionError returns an error that shows the invalid option

func InvalidOptionf

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

InvalidOptionf returns an error that shows the invalid option

func IsEmpty

func IsEmpty(name string) (bool, error)

func IsValidUrl added in v2.1.56

func IsValidUrl(s string) bool

IsValidUrl tests a string to determine if it is a well-structured url or not.

func IsZeroOfUnderlyingType

func IsZeroOfUnderlyingType(x interface{}) bool

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

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 KeyValuesToMap

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

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

func KillProcesses

func KillProcesses(binary string) error

func KillProcessesTree

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

func KubeConfigFile

func KubeConfigFile() string

KubeConfigFile gets the .kube/config file

func ListDirectory

func ListDirectory(root string, recurse bool) error

ListDirectory logs the directory at path

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 LocalFileSystemSecretsDir

func LocalFileSystemSecretsDir() (string, error)

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

func LogsDir

func LogsDir() (string, error)

func MapKeys

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

MapKeys returns the keys of a given map

func MapToKeyValues

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

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

func MapToString

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

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 MissingEnv

func MissingEnv(name string) error

MissingEnv reports a missing environment variable

func MissingOption

func MissingOption(name string) error

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

func MissingOptionWithOptions

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

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(customPaths ...string) string

PathWithBinary Returns the path to be used to execute a binary from, takes the form JX_HOME/bin:mvnBinDir:customPaths

func PickName

func PickName(names []string, message string, help string, handles IOFileHandles) (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, handles IOFileHandles) (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, handles IOFileHandles) ([]string, error)

PickNames gets the user to pick multiple selections from a list of options

func PickNamesWithDefaults

func PickNamesWithDefaults(names []string, defaults []string, message string, help string, handles IOFileHandles) ([]string, error)

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

func PickPassword

func PickPassword(message string, help string, handles IOFileHandles) (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, handles IOFileHandles) (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, handles IOFileHandles) (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 PrettyPrint

func PrettyPrint(i interface{}) string

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

func QuestionAnswer

func QuestionAnswer(question string, answer string) string

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

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 RemoveScheme

func RemoveScheme(u string) string

RemoveScheme removes the scheme from a URL

func RemoveStringFromSlice

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

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

func RenameFile

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

func ReplaceAllStringSubmatchFunc

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

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 RetryWithInitialDelay

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

RetryWithInitialDelay retires with exponential backoff and initial delay the given function

func RetryWithInitialDelaySlower

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

func ReverseStrings(a []string)

func RunCommandBackground

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

func SanitizeLabel

func SanitizeLabel(label string) string

SanitizeLabel returns a label with disallowed characters removed

func SanitizeURL

func SanitizeURL(unsanitizedUrl string) string

SanitizeURL sanitizes by stripping the user and password

func SelectNames

func SelectNames(names []string, message string, selectAll bool, help string, handles IOFileHandles) ([]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, handles IOFileHandles) ([]string, error)

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

func SetMapValueViaPath

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

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

SortedMapKeys returns the sorted keys of the given map

func StartsWith

func StartsWith(s, substr string) bool

StartsWith returns true if the string starts with the given substring

func StringArrayHasPrefixIndex

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

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

func StringArrayIndex

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

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

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 StringContainsAny

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

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

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

StringMatchesAny 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 StringsContaining

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

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

func StripTrailingSlash

func StripTrailingSlash(url string) string

StripTrailingSlash removes any trailing forward slashes on the URL

func SuggestionsFor

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

func ToCamelCase

func ToCamelCase(s string) string

ToCamelCase turn "my-super-name" into "MySuperName" Usefule for creating valid go-template variable names

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 ToObjectMap

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

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

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 ToValidFileSystemName

func ToValidFileSystemName(name string) string

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

func URLToHostName

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

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

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

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 UrlEqual

func UrlEqual(url1, url2 string) bool

UrlEqual verifies if URLs are equal

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

func ValidateYaml

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

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

WriteJenkinsfileStatements writes the given Jenkinsfile statements as a string

func YesNo

func YesNo(t bool) string

YesNo returns a Yes/No conversion for a boolean parameter

Types

type CacheLoader

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

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

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 environment 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

func (*Command) String

func (c *Command) String() string

type CommandError

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) Cause

func (c CommandError) Cause() error

func (CommandError) Error

func (c CommandError) Error() string

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 Group

type Group struct {
	Value string
	Start int
	End   int
}

Group is a submatch group

type IOFileHandles

type IOFileHandles struct {
	Err io.Writer
	In  terminal.FileReader
	Out terminal.FileWriter
}

IOFileHandles is a struct for holding CommonOptions' In, Out, and Err I/O handles, to simplify function calls.

type MethodMap

type MethodMap map[string]string

type Router

type Router map[string]MethodMap

type Statement

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

Statement represents a statement in a Jenkinsfile

func (*Statement) ContextEquals

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

func (s *Statement) Text() string

Text returns the text line of the current function or statement

type Writer

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

Writer implements the struct for Jenkinsfilewriter

func NewWriter

func NewWriter(indentCount int) *Writer

NewWriter creates a Jenkinsfile writer

func (*Writer) String

func (w *Writer) String() string

String returns the string value of this writer

func (*Writer) Write

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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