util

package
v2.2.2 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2024 License: Apache-2.0 Imports: 36 Imported by: 15

Documentation

Index

Constants

View Source
const (
	GitHubHost    string = "github.com"
	RawGitHubHost string = "raw.githubusercontent.com"
	GitLabHost    string = "gitlab.com"
	BitbucketHost string = "bitbucket.org"
)
View Source
const (
	HTTPRequestResponseTimeout   = 30 * time.Second           // HTTPRequestTimeout configures timeout of all HTTP requests
	ModeReadWriteFile            = 0600                       // default Permission for a file
	CredentialPrefix             = "odo-"                     // CredentialPrefix is the prefix of the credential that uses to access secure registry
	TelemetryClientName          = "devfile-library"          //TelemetryClientName is the name of the devfile library client
	TelemetryIndirectDevfileCall = "devfile-library-indirect" //TelemetryIndirectDevfileCall is used to identify calls made to retrieve the parent or plugin devfile
)
View Source
const WIN = "windows"

WIN represent the windows OS

Variables

View Source
var MockDevfileWithParentRef = `` /* 1509-byte string literal not displayed */
View Source
var MockParentDevfile = `` /* 727-byte string literal not displayed */

Functions

func AddFileToIgnoreFile

func AddFileToIgnoreFile(gitIgnoreFile, filename string) error

AddFileToIgnoreFile adds a file to the gitignore file. It only does that if the file doesn't exist

func CheckKubeConfigExist

func CheckKubeConfigExist() bool

CheckKubeConfigExist checks for existence of kubeconfig

func CheckOutputFlag

func CheckOutputFlag(outputFlag string) bool

CheckOutputFlag returns true if specified output format is supported

func CheckPathExists

func CheckPathExists(path string) bool

CheckPathExists checks if a path exists or not

func CloneGitRepo

func CloneGitRepo(gitUrlComponents map[string]string, destDir string) error

CloneGitRepo clones a GitHub repo to a destination directory Deprecated: in favor of the method git.CloneGitRepo() with the devfile/library/v2/pkg/git package

func ConvertGitSSHRemoteToHTTPS

func ConvertGitSSHRemoteToHTTPS(remote string) string

Converts Git ssh remote to https

func ConvertKeyValueStringToMap

func ConvertKeyValueStringToMap(params []string) map[string]string

ConvertKeyValueStringToMap converts String Slice of Parameters to a Map[String]string Each value of the slice is expected to be in the key=value format Values that do not conform to this "spec", will be ignored

func ConvertLabelsToSelector

func ConvertLabelsToSelector(labels map[string]string) string

ConvertLabelsToSelector converts the given labels to selector

func CopyAllDirFiles

func CopyAllDirFiles(srcDir, destDir string) error

CopyAllDirFiles recursively copies a source directory to a destination directory

func CopyFile

func CopyFile(srcPath string, dstPath string, info os.FileInfo) error

CopyFile copies file from source path to destination path

func DeletePath

func DeletePath(path string) error

DeletePath deletes a file/directory if it exists and doesn't throw error if it doesn't exist

func DisplayLog

func DisplayLog(followLog bool, rd io.ReadCloser, compName string) (err error)

DisplayLog displays logs to user stdout with some color formatting

func DownloadFile

func DownloadFile(params DownloadParams) error

DownloadFile downloads the file to the filepath given URL and token (if applicable)

func DownloadFileInMemory

func DownloadFileInMemory(url string) ([]byte, error)

DownloadFileInMemory uses the url to download the file and return bytes Deprecated, use DownloadInMemory() instead

func DownloadFileWithCache

func DownloadFileWithCache(params DownloadParams, cacheFor int) error

DownloadFileWithCache downloads the file to the filepath given URL and token (if applicable) cacheFor determines how long the response should be cached (in minutes), 0 for no caching

func DownloadInMemory added in v2.2.0

func DownloadInMemory(params HTTPRequestParams) ([]byte, error)

DownloadInMemory uses HTTPRequestParams to download the file and return bytes. Use the pkg/devfile/parser/utils.go DownloadInMemory() invocation if you want to call with a client instead.

func ExtractComponentType

func ExtractComponentType(namespacedVersionedComponentType string) string

ExtractComponentType returns only component type part from passed component type(default unqualified, fully qualified, versioned, etc...and their combinations) for use as component name Possible types of parameters: 1. "myproject/python:3.5" -- Return python 2. "python:3.5" -- Return python 3. nodejs -- Return nodejs

func FilterIgnores

func FilterIgnores(filesChanged, filesDeleted, absIgnoreRules []string) (filesChangedFiltered, filesDeletedFiltered []string)

FilterIgnores applies the glob rules on the filesChanged and filesDeleted and filters them returns the filtered results which match any of the glob rules

func GenFileURL

func GenFileURL(location string, os ...string) string

GenFileURL Converts file path on windows to /C:/path/to/file to work in URL

func GenerateRandomString

func GenerateRandomString(n int) string

GenerateRandomString generates a random string of lower case characters of the given size

func GetAbsGlobExps

func GetAbsGlobExps(directory string, globExps []string) []string

GetAbsGlobExps converts the relative glob expressions into absolute glob expressions returns the absolute glob expressions

func GetAbsPath

func GetAbsPath(path string) (string, error)

GetAbsPath returns absolute path from passed file path resolving even ~ to user home dir and any other such symbols that are only shell expanded can also be handled here

func GetAndExtractZip

func GetAndExtractZip(zipURL string, destination string, pathToUnzip string) error

GetAndExtractZip downloads a zip file from a URL with a http prefix or takes an absolute path prefixed with file:// and extracts it to a destination. pathToUnzip specifies the path within the zip folder to extract

func GetContainerPortsFromStrings

func GetContainerPortsFromStrings(ports []string) ([]corev1.ContainerPort, error)

GetContainerPortsFromStrings generates ContainerPort values from the array of string port values ports is the array containing the string port values

func GetDNS1123Name

func GetDNS1123Name(str string) string

GetDNS1123Name Converts passed string into DNS-1123 string

func GetGitUrlComponentsFromRaw

func GetGitUrlComponentsFromRaw(rawGitURL string) (map[string]string, error)

GetGitUrlComponentsFromRaw converts a raw GitHub file link to a map of the url components Deprecated: in favor of the method git.ParseGitUrl() with the devfile/library/v2/pkg/git package

func GetHostWithPort

func GetHostWithPort(inputURL string) (string, error)

GetHostWithPort parses provided url and returns string formated as host:port even if port was not specifically specified in the origin url. If port is not specified, standart port corresponding to url schema is provided. example: for url https://example.com function will return "example.com:443" for url https://example.com:8443 function will return "example:8443"

func GetIgnoreRulesFromDirectory

func GetIgnoreRulesFromDirectory(directory string) ([]string, error)

GetIgnoreRulesFromDirectory reads the .odoignore file, if present, and reads the rules from it if the .odoignore file is not found, then .gitignore is searched for the rules if both are not found, return empty array directory is the name of the directory to look into for either of the files rules is the array of rules (in string form)

func GetRandomName

func GetRandomName(prefix string, prefixMaxLen int, existList []string, retries int) (string, error)

GetRandomName returns a randomly generated name which can be used for naming odo and/or openshift entities prefix: Desired prefix part of the name prefixMaxLen: Desired maximum length of prefix part of random name; if -1 is passed, no limit on length will be enforced existList: List to verify that the returned name does not already exist retries: number of retries to try generating a unique name Returns:

  1. randomname: is prefix-suffix, where: prefix: string passed as prefix or fetched current directory of length same as the passed prefixMaxLen suffix: 4 char random string
  2. error: if requested number of retries also failed to generate unique name

func GetRemoteFilesMarkedForDeletion

func GetRemoteFilesMarkedForDeletion(delSrcRelPaths []string, remoteFolder string) []string

GetRemoteFilesMarkedForDeletion returns the list of remote files marked for deletion

func GetSortedKeys

func GetSortedKeys(mapping map[string]string) []string

GetSortedKeys retrieves the alphabetically-sorted keys of the specified map

func GetSplitValuesFromStr

func GetSplitValuesFromStr(inputStr string) []string

GetSplitValuesFromStr returns a slice containing the split string, using ',' as a separator

func HTTPGetFreePort

func HTTPGetFreePort() (int, error)

HTTPGetFreePort gets a free port from the system

func HTTPGetRequest

func HTTPGetRequest(request HTTPRequestParams, cacheFor int) ([]byte, error)

HTTPGetRequest gets resource contents given URL and token (if applicable) cacheFor determines how long the response should be cached (in minutes), 0 for no caching

func In

func In(arr []string, value string) bool

In checks if the value is in the array

func IsEmpty

func IsEmpty(name string) (bool, error)

IsEmpty checks to see if a directory is empty shamelessly taken from: https://stackoverflow.com/questions/30697324/how-to-check-if-directory-on-path-is-empty this helps detect any edge cases where an empty directory is copied over

func IsGitProviderRepo added in v2.2.1

func IsGitProviderRepo(url string) bool

IsGitProviderRepo checks if the url matches a repo from a supported git provider

func IsGlobExpMatch

func IsGlobExpMatch(strToMatch string, globExps []string) (bool, error)

IsGlobExpMatch compiles strToMatch against each of the passed globExps Parameters: strToMatch : a string for matching against the rules globExps : a list of glob patterns to match strToMatch with Returns: true if there is any match else false the error (if any) Notes: Source as well as glob expression to match is changed to forward slashes due to supporting Windows as well as support with the "github.com/gobwas/glob" library that we use.

func IsValidProjectDir

func IsValidProjectDir(path string, devfilePath string) error

IsValidProjectDir checks that the folder to download the project from devfile is either empty or only contains the devfile used.

func NamespaceOpenShiftObject

func NamespaceOpenShiftObject(componentName string, applicationName string) (string, error)

NamespaceOpenShiftObject hyphenates applicationName and componentName

func OpenBrowser

func OpenBrowser(url string) error

OpenBrowser opens the URL within the users default browser

func ParseComponentImageName

func ParseComponentImageName(imageName string) (string, string, string, string)

ParseComponentImageName returns 1. image name 2. component type i.e, builder image name 3. component name default value is component type else the user requested component name 4. component version which is by default latest else version passed with builder image name

func PathEqual

func PathEqual(firstPath string, secondPath string) bool

PathEqual compare the paths to determine if they are equal

func ReadFilePath

func ReadFilePath(u *url.URL, os string) string

ReadFilePath Reads file path form URL file:///C:/path/to/file to C:\path\to\file

func RemoveDuplicates

func RemoveDuplicates(s []string) []string

RemoveDuplicates goes through a string slice and removes all duplicates. Reference: https://siongui.github.io/2018/04/14/go-remove-duplicates-from-slice-or-array/

func RemoveRelativePathFromFiles

func RemoveRelativePathFromFiles(files []string, path string) ([]string, error)

RemoveRelativePathFromFiles removes a specified path from a list of files

func SliceDifference

func SliceDifference(s1 []string, s2 []string) []string

SliceDifference returns the values of s2 that do not exist in s1

func TruncateString

func TruncateString(str string, maxLen int) string

TruncateString truncates passed string to given length Note: if -1 is passed, the original string is returned

func Unzip

func Unzip(src, dest, pathToUnzip string) ([]string, error)

Unzip will decompress a zip archive, moving specified files and folders within the zip file (parameter 1) to an output directory (parameter 2) Source: https://golangcode.com/unzip-files-in-go/ pathToUnzip (parameter 3) is the path within the zip folder to extract

func ValidateFile

func ValidateFile(filePath string) error

ValidateFile validates the file

func ValidateK8sResourceName

func ValidateK8sResourceName(key string, value string) error

ValidateK8sResourceName sanitizes kubernetes resource name with the following requirements: - Contain at most 63 characters - Contain only lowercase alphanumeric characters or ‘-’ - Start with an alphanumeric character - End with an alphanumeric character - Must not contain all numeric values

func ValidateURL

func ValidateURL(sourceURL string) error

ValidateURL validates the URL

Types

type CommandType added in v2.2.1

type CommandType string
const (
	GitCommand CommandType = "git"
)

type DownloadParams

type DownloadParams struct {
	Request  HTTPRequestParams
	Filepath string
}

DownloadParams holds parameters of forming file download request

type GitUrl added in v2.2.1

type GitUrl struct {
	Protocol string // URL scheme
	Host     string // URL domain name
	Owner    string // name of the repo owner
	Repo     string // name of the repo
	Revision string // branch name, tag name, or commit id
	Path     string // path to a directory or file in the repo
	Token    string // authenticates private repo actions for parent devfiles
	IsFile   bool   // defines if the URL points to a file in the repo
}

func NewGitURL added in v2.2.1

func NewGitURL(url string, token string) (*GitUrl, error)

NewGitURL NewGitUrl creates a GitUrl from a string url and token. Will eventually replace NewGitUrlWithURL

func NewGitUrlWithURL added in v2.2.1

func NewGitUrlWithURL(url string) (GitUrl, error)

NewGitUrlWithURL NewGitUrl creates a GitUrl from a string url

func ParseGitUrl added in v2.2.1

func ParseGitUrl(fullUrl string) (GitUrl, error)

ParseGitUrl extracts information from a support git url Only supports git repositories hosted on GitHub, GitLab, and Bitbucket

func (*GitUrl) CloneGitRepo added in v2.2.1

func (g *GitUrl) CloneGitRepo(destDir string) error

func (*GitUrl) GetToken added in v2.2.1

func (g *GitUrl) GetToken() string

func (*GitUrl) GitRawFileAPI added in v2.2.1

func (g *GitUrl) GitRawFileAPI() string

GitRawFileAPI returns the endpoint for the git providers raw file

func (*GitUrl) IsGitProviderRepo added in v2.2.1

func (g *GitUrl) IsGitProviderRepo() bool

IsGitProviderRepo checks if the url matches a repo from a supported git provider

func (*GitUrl) IsPublic added in v2.2.1

func (g *GitUrl) IsPublic(httpTimeout *int) bool

IsPublic checks if the GitUrl is public with a get request to the repo using an empty token Returns true if the request succeeds Deprecated. Avoid using since this will cause rate limiting issues

func (*GitUrl) SetToken added in v2.2.1

func (g *GitUrl) SetToken(token string, httpTimeout *int) error

SetToken validates the token with a get request to the repo before setting the token Defaults token to empty on failure. Deprecated. Avoid using since this will cause rate limiting issues

type HTTPClient added in v2.2.1

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type HTTPRequestParams

type HTTPRequestParams struct {
	URL                 string
	Token               string
	Timeout             *int
	TelemetryClientName string //optional client name for telemetry
}

HTTPRequestParams holds parameters of forming http request

type MockDownloadOptions added in v2.2.2

type MockDownloadOptions struct {
	MockDevfile    bool
	MockDockerfile bool
	MockFile       string
	MockParent     *MockParent
}

type MockGitUrl added in v2.2.1

type MockGitUrl struct {
	Protocol string // URL scheme
	Host     string // URL domain name
	Owner    string // name of the repo owner
	Repo     string // name of the repo
	Revision string // branch name, tag name, or commit id
	Path     string // path to a directory or file in the repo
	Token    string // used for authenticating a private repo
	IsFile   bool   // defines if the URL points to a file in the repo
}

func (*MockGitUrl) CloneGitRepo added in v2.2.1

func (m *MockGitUrl) CloneGitRepo(destDir string) error

func (MockGitUrl) DownloadInMemoryWithClient added in v2.2.2

func (m MockGitUrl) DownloadInMemoryWithClient(params HTTPRequestParams, httpClient HTTPClient, options MockDownloadOptions) ([]byte, error)

func (*MockGitUrl) GetToken added in v2.2.1

func (m *MockGitUrl) GetToken() string

func (*MockGitUrl) IsGitProviderRepo added in v2.2.1

func (m *MockGitUrl) IsGitProviderRepo() bool

func (*MockGitUrl) SetToken added in v2.2.1

func (m *MockGitUrl) SetToken(token string) error

type MockParent added in v2.2.2

type MockParent struct {
	IsMainDevfileDownloaded   bool
	IsParentDevfileDownloaded bool
}

type ResourceRequirementInfo

type ResourceRequirementInfo struct {
	ResourceType corev1.ResourceName
	MinQty       resource.Quantity
	MaxQty       resource.Quantity
}

ResourceRequirementInfo holds resource quantity before transformation into its appropriate form in container spec

func FetchResourceQuantity

func FetchResourceQuantity(resourceType corev1.ResourceName, min string, max string, request string) (*ResourceRequirementInfo, error)

FetchResourceQuantity takes passed min, max and requested resource quantities and returns min and max resource requests

Jump to

Keyboard shortcuts

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