util

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const TerraformLockFile = ".terraform.lock.hcl"
View Source
const TerragruntCacheDir = ".terragrunt-cache"

Variables

View Source
var (
	// GlobalFallbackLogEntry is a global fallback logentry for the application
	// Should be used in cases when more specific logger can't be created (like in the very beginning, when we have not yet
	// parsed command line arguments).
	//
	// This might go away once we migrate toproper cli library
	// (see https://github.com/c3xdev/c3x/internal/hclstack/blob/master/cli/args.go#L29)
	GlobalFallbackLogEntry *logrus.Entry
)

Functions

func AsTerraformEnvVarJsonValue

func AsTerraformEnvVarJsonValue(value interface{}) (string, error)

Convert the given value to a JSON value that can be passed to Terraform as an environment variable. For the most part, this converts the value directly to JSON using Go's built-in json.Marshal. However, we have special handling for strings, which with normal JSON conversion would be wrapped in quotes, but when passing them to Terraform via env vars, we need to NOT wrap them in quotes, so this method adds special handling for that case.

func CanonicalPath

func CanonicalPath(path string, basePath string) (string, error)

CanonicalPath returns the canonical version of the given path, relative to the given base path. That is, if the given path is a relative path, assume it is relative to the given base path. A canonical path is an absolute path with all relative components (e.g. "../") fully resolved, which makes it safe to compare paths as strings.

func CanonicalPaths

func CanonicalPaths(paths []string, basePath string) ([]string, error)

Return the canonical version of the given paths, relative to the given base path. That is, if a given path is a relative path, assume it is relative to the given base path. A canonical path is an absolute path with all relative components (e.g. "../") fully resolved, which makes it safe to compare paths as strings.

func CleanPath

func CleanPath(path string) string

Use this function when cleaning paths to ensure the returned path uses / as the path separator to improve cross-platform compatibility

func CloneStringList

func CloneStringList(listToClone []string) []string

Make a copy of the given list of strings

func CloneStringMap

func CloneStringMap(mapToClone map[string]string) map[string]string

Make a copy of the given map of strings

func CommaSeparatedStrings

func CommaSeparatedStrings(list []string) string

CommaSeparatedStrings returns an HCL compliant formatted list of strings (each string within double quote)

func ContainsPath

func ContainsPath(path, subpath string) bool

ContainsPath returns true if path contains the given subpath E.g. path="foo/bar/bee", subpath="bar/bee" -> true E.g. path="foo/bar/bee", subpath="bar/be" -> false (because be is not a directory)

func CopyFile

func CopyFile(source string, destination string) error

Copy a file from source to destination

func CopyFolderContents

func CopyFolderContents(source, destination, manifestFile string, includeInCopy []string) error

Copy the files and folders within the source folder into the destination folder. Note that hidden files and folders (those starting with a dot) will be skipped. Will create a specified manifest file that contains paths of all copied files.

func CopyFolderContentsWithFilter

func CopyFolderContentsWithFilter(source, destination, manifestFile string, filter func(absolutePath string) bool) error

Copy the files and folders within the source folder into the destination folder. Pass each file and folder through the given filter function and only copy it if the filter returns true. Will create a specified manifest file that contains paths of all copied files.

func CopyLockFile

func CopyLockFile(sourceFolder string, destinationFolder string, logger *logrus.Entry) error

Terraform 0.14 now generates a lock file when you run `terraform init`. If any such file exists, this function will copy the lock file to the destination folder

func CreateLogEntry

func CreateLogEntry(prefix string, level logrus.Level) *logrus.Entry

CreateLogEntry creates a logger entry with the given prefix field

func CreateLogEntryWithWriter

func CreateLogEntryWithWriter(writer io.Writer, prefix string, level logrus.Level, hooks logrus.LevelHooks) *logrus.Entry

CreateLoggerWithWriter Create a logger around the given output stream and prefix

func CreateLogger

func CreateLogger(lvl logrus.Level) *logrus.Logger

CreateLogger creates a logger. If debug is set, we use ErrorLevel to enable verbose output, otherwise - only errors are shown

func DisableLogColors

func DisableLogColors()

func DoWithRetry

func DoWithRetry(actionDescription string, maxRetries int, sleepBetweenRetries time.Duration, logger *logrus.Entry, logLevel logrus.Level, action func() error) error

DoWithRetry runs the specified action. If it returns a value, return that value. If it returns an error, sleep for sleepBetweenRetries and try again, up to a maximum of maxRetries retries. If maxRetries is exceeded, return a MaxRetriesExceeded error.

func EncodeBase64Sha1

func EncodeBase64Sha1(str string) string

Returns the base 64 encoded sha1 hash of the given string

func EnsureDirectory

func EnsureDirectory(path string) error

EnsureDirectory creates a directory at this path if it does not exist, or error if the path exists and is a file.

func FileExists

func FileExists(path string) bool

Return true if the given file exists

func FileNotExists

func FileNotExists(path string) bool

Return true if the given file does not exist

func FileOrData

func FileOrData(maybePath string) (string, error)

FileOrData will read the contents of the data of the given arg if it is a file, and otherwise return the contents by itself. This will return an error if the given path is a directory.

func FirstArg

func FirstArg(args []string) string

A convenience method that returns the first item (0th index) in the given list or an empty string if this is an empty list

func GenerateRandomSha256

func GenerateRandomSha256() (string, error)

func GetDefaultLogLevel

func GetDefaultLogLevel() logrus.Level

GetDefaultLogLevel returns the default log level to use. The log level is resolved based on the environment variable with name from LogLevelEnvVar, falling back to info if unspecified or there is an error parsing the given log level.

func GetDiagnosticsWriter

func GetDiagnosticsWriter(logger *logrus.Entry, parser *hclparse.Parser) hcl.DiagnosticWriter

GetDiagnosticsWriter returns a hcl2 parsing diagnostics emitter for the current terminal.

func GetPathRelativeTo

func GetPathRelativeTo(path string, basePath string) (string, error)

Return the relative path you would have to take to get from basePath to path

func GetRandomTime

func GetRandomTime(lowerBound, upperBound time.Duration) time.Duration

GetRandomTime returns a random duration between lowerBound and upperBound (inclusive). Negative bounds are converted to their absolute values. If bounds are equal, that value is returned. If lowerBound > upperBound, the bounds are swapped.

func GlobCanonicalPath

func GlobCanonicalPath(basePath string, globPaths ...string) ([]string, error)

GlobCanonicalPath returns the canonical versions of the given glob paths, relative to the given base path.

func Grep

func Grep(regex *regexp.Regexp, glob string) (bool, error)

Returns true if the given regex can be found in any of the files matched by the given glob

func HasPathPrefix

func HasPathPrefix(path, prefix string) bool

HasPathPrefix returns true if path starts with the given path prefix E.g. path="/foo/bar/biz", prefix="/foo/bar" -> true E.g. path="/foo/bar/biz", prefix="/foo/ba" -> false (because ba is not a directory path)

func IsCommandExecutable

func IsCommandExecutable(command string, args ...string) bool

IsCommandExecutable - returns true if a command can be executed without errors.

func IsDir

func IsDir(path string) bool

Return true if the path points to a directory

func IsFile

func IsFile(path string) bool

Return true if the path points to a file

func IsSymLink(path string) bool

IsSymLink returns true if the given file is a symbolic link Per https://stackoverflow.com/a/18062079/2308858

func JoinPath

func JoinPath(elem ...string) string

Windows systems use \ as the path separator *nix uses / Use this function when joining paths to force the returned path to use / as the path separator This will improve cross-platform compatibility

func JoinTerraformModulePath

func JoinTerraformModulePath(modulesFolder string, path string) string

Join two paths together with a double-slash between them, as this is what Terraform uses to identify where a "repo" ends and a path within the repo begins. Note: The Terraform docs only mention two forward-slashes, so it's not clear if on Windows those should be two back-slashes? https://www.terraform.io/docs/modules/sources.html

func KindOf

func KindOf(value interface{}) reflect.Kind

Return the kind of the type or Invalid if value is nil

func LastArg

func LastArg(args []string) string

A convenience method that returns the last item in the given list or an empty string if this is an empty list

func ListContainsElement

func ListContainsElement(list []string, element string) bool

Return true if the given list contains the given element

func ListContainsSublist

func ListContainsSublist(list, sublist []string) bool

ListContainsSublist returns true if an instance of the sublist can be found in the given list

func ListEquals

func ListEquals(a, b []string) bool

ListEquals returns true if the two lists are equal

func ListHasPrefix

func ListHasPrefix(list, prefix []string) bool

ListHasPrefix returns true if list starts with the given prefix list

func MatchesAny

func MatchesAny(regExps []string, s string) bool

func Min

func Min(x, y int) int

func MustWalkTerraformOutput

func MustWalkTerraformOutput(value interface{}, path ...string) interface{}

MustWalkTerraformOutput is a helper utility to deeply return a value from a terraform output.

nil will be returned if the path is invalid

Using an example terraform output:
  a = {
    b = {
      c = "foo"
    }
    "d" = [
      1,
      2
    ]
  }

path ["a", "b", "c"] will return "foo"
path ["a", "d", "1"] will return 2
path ["a", "foo"] will return nil

func ParseLogLevel

func ParseLogLevel(logLevelStr string) logrus.Level

func ParseTimestamp

func ParseTimestamp(ts string) (time.Time, error)

func PrefixedWriter

func PrefixedWriter(writer io.Writer, prefix string) io.Writer

func ReadFileAsString

func ReadFileAsString(path string) (string, error)

Return the contents of the file at the given path as a string

func RemoveDuplicatesFromList

func RemoveDuplicatesFromList(list []string) []string

Returns a copy of the given list with all duplicates removed (keeping the first encountereds)

func RemoveDuplicatesFromListKeepLast

func RemoveDuplicatesFromListKeepLast(list []string) []string

Returns a copy of the given list with all duplicates removed (keeping the last encountereds)

func RemoveElementFromList

func RemoveElementFromList(list []string, element string) []string

Return a copy of the given list with all instances of the given element removed

func SecondArg

func SecondArg(args []string) string

A convenience method that returns the second item (1st index) in the given list or an empty string if this is a list that has less than 2 items in it

func SplitPath

func SplitPath(path string) []string

SplitPath splits the given path into a list. E.g. "foo/bar/boo.txt" -> ["foo", "bar", "boo.txt"] E.g. "/foo/bar/boo.txt" -> ["", "foo", "bar", "boo.txt"] Notice that if path is absolute the resulting list will begin with an empty string.

func SplitUrls

func SplitUrls(s, sep string) []string

SplitUrls slices s into all substrings separated by sep and returns a slice of the substrings between those separators. Taking into account that the `=` sign can also be used as a git tag, e.g. `git@github.com/test.git?ref=feature`

func StringListInsert

func StringListInsert(list []string, element string, index int) []string

StringListInsert will insert the given string in to the provided string list at the specified index and return the new list of strings. To insert the element, we append the item to the tail of the string and then prepend the existing items.

func TerragruntExcludes

func TerragruntExcludes(path string) bool

func UniqueId

func UniqueId() string

UniqueId returns a random 6-character base62 string for use in naming test resources.

func WriteFileWithSamePermissions

func WriteFileWithSamePermissions(source string, destination string, contents []byte) error

Write a file to the given destination with the given contents using the same permissions as the file at source

Types

type FatalError

type FatalError struct {
	Underlying error
}

FatalError is error interface for cases that should not be retried.

func (FatalError) Error

func (err FatalError) Error() string

type LogWriter

type LogWriter struct {
	Logger *logrus.Entry
	Level  logrus.Level
}

LogWriter - Writer implementation which redirect Write requests to configured logger and level

func (*LogWriter) Write

func (w *LogWriter) Write(p []byte) (n int, err error)

type MaxRetriesExceeded

type MaxRetriesExceeded struct {
	Description string
	MaxRetries  int
}

MaxRetriesExceeded is an error that occurs when the maximum amount of retries is exceeded.

func (MaxRetriesExceeded) Error

func (err MaxRetriesExceeded) Error() string

type PathIsNotDirectory

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

PathIsNotDirectory is returned when the given path is unexpectedly not a directory.

func (PathIsNotDirectory) Error

func (err PathIsNotDirectory) Error() string

type PathIsNotFile

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

PathIsNotFile is returned when the given path is unexpectedly not a file.

func (PathIsNotFile) Error

func (err PathIsNotFile) Error() string

Jump to

Keyboard shortcuts

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