utils

package
v1.187.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2025 License: Apache-2.0 Imports: 53 Imported by: 0

Documentation

Overview

Package utils provides markdown utilities for error handling and output formatting in the Atmos CLI application.

Index

Constants

View Source
const (
	DefaultStackConfigFileExtension = ".yaml"
	YamlFileExtension               = ".yaml"
	YmlFileExtension                = ".yml"
	YamlTemplateExtension           = ".yaml.tmpl"
	YmlTemplateExtension            = ".yml.tmpl"
	TemplateExtension               = ".tmpl"
)
View Source
const (
	LogLevelTrace = "Trace"
	LogLevelDebug = "Debug"
)
View Source
const (
	// Atmos YAML functions.
	AtmosYamlFuncExec            = "!exec"
	AtmosYamlFuncStore           = "!store"
	AtmosYamlFuncStoreGet        = "!store.get"
	AtmosYamlFuncTemplate        = "!template"
	AtmosYamlFuncTerraformOutput = "!terraform.output"
	AtmosYamlFuncTerraformState  = "!terraform.state"
	AtmosYamlFuncEnv             = "!env"
	AtmosYamlFuncInclude         = "!include"
	AtmosYamlFuncGitRoot         = "!repo-root"

	DefaultYAMLIndent = 2
)
View Source
const MaxShellDepth = 10

MaxShellDepth is the maximum number of nested shell commands that can be executed .

View Source
const MaxURISize = 2048

Variables

View Source
var (
	ErrURIEmpty                      = fmt.Errorf("URI cannot be empty")
	ErrURIExceedsMaxLength           = fmt.Errorf("URI exceeds maximum length of 2048 characters")
	ErrURICannotContainPathTraversal = fmt.Errorf("URI cannot contain path traversal sequences")
	ErrURICannotContainSpaces        = fmt.Errorf("URI cannot contain spaces")
	ErrUnsupportedURIScheme          = fmt.Errorf("unsupported URI scheme")
	ErrInvalidOCIURIFormat           = fmt.Errorf("invalid OCI URI format")
)
View Source
var (
	ErrMaxShellDepthExceeded = errors.New("ATMOS_SHLVL exceeds maximum allowed depth. Infinite recursion?")
	ErrConvertingShellLevel  = errors.New("converting ATMOS_SHLVL to number error")
	ErrBindingShellLevelEnv  = errors.New("binding ATMOS_SHLVL env var error")
)
View Source
var (
	AtmosYamlTags = []string{
		AtmosYamlFuncExec,
		AtmosYamlFuncStore,
		AtmosYamlFuncStoreGet,
		AtmosYamlFuncTemplate,
		AtmosYamlFuncTerraformOutput,
		AtmosYamlFuncTerraformState,
		AtmosYamlFuncEnv,
	}

	ErrIncludeYamlFunctionInvalidArguments    = errors.New("invalid number of arguments in the !include function")
	ErrIncludeYamlFunctionInvalidFile         = errors.New("the !include function references a file that does not exist")
	ErrIncludeYamlFunctionInvalidAbsPath      = errors.New("failed to convert the file path to an absolute path in the !include function")
	ErrIncludeYamlFunctionFailedStackManifest = errors.New("failed to process the stack manifest with the !include function")
	ErrNilAtmosConfig                         = errors.New("atmosConfig cannot be nil")
)
View Source
var ErrFailedToProcessHclFile = errors.New("failed to process HCL file")
View Source
var ErrInvalidAtmosYAMLFunction = fmt.Errorf("invalid Atmos YAML function")
View Source
var OsExit = os.Exit

OsExit is a variable for testing, so we can mock os.Exit.

Functions

func Coalesce added in v1.31.0

func Coalesce[T comparable](v ...T) (result T)

Coalesce returns the first non-empty argument. Arguments must be comparable

func ConvertEnvVars added in v1.4.22

func ConvertEnvVars(envVarsMap map[string]any) []string

ConvertEnvVars converts ENV vars from a map to a list of strings in the format ["key1=val1", "key2=val2", "key3=val3" ...].

func ConvertFromJSON added in v1.9.0

func ConvertFromJSON(jsonString string) (any, error)

ConvertFromJSON converts the provided JSON-encoded string to Go data types

func ConvertPathsToAbsolutePaths

func ConvertPathsToAbsolutePaths(paths []string) ([]string, error)

ConvertPathsToAbsolutePaths converts a slice of paths to a slice of absolute paths

func ConvertToHclAst added in v1.6.0

func ConvertToHclAst(data any) (ast.Node, error)

ConvertToHclAst converts the provided value to an HCL abstract syntax tree

func ConvertToJSON added in v1.6.0

func ConvertToJSON(data any) (string, error)

ConvertToJSON converts the provided value to a JSON-encoded string

func ConvertToJSONFast added in v1.6.0

func ConvertToJSONFast(data any) (string, error)

ConvertToJSONFast converts the provided value to a JSON-encoded string using 'ConfigFastest' config and json.Marshal without indents

func ConvertToYAML added in v1.6.0

func ConvertToYAML(data any, opts ...YAMLOptions) (string, error)

func CtyToGo added in v1.169.0

func CtyToGo(value cty.Value) any

CtyToGo converts cty.Value to Go types.

func DefaultHighlightSettings added in v1.148.0

func DefaultHighlightSettings() *schema.SyntaxHighlighting

DefaultHighlightSettings returns the default syntax highlighting settings

func DisplayDocs added in v1.124.0

func DisplayDocs(componentDocs string, usePager bool) error

DisplayDocs displays component documentation directly through the terminal or through a pager (like less). The use of a pager is determined by the pagination value set in the CLI Settings for Atmos

func EnsureDir added in v1.5.0

func EnsureDir(fileName string) error

EnsureDir accepts a file path and creates all the intermediate subdirectories

func EnvironToMap added in v1.160.4

func EnvironToMap() map[string]string

EnvironToMap converts all the environment variables in the environment into a map of strings.

func EvaluateYqExpression added in v1.140.0

func EvaluateYqExpression(atmosConfig *schema.AtmosConfiguration, data any, yq string) (any, error)

func EvaluateYqExpressionWithType added in v1.175.0

func EvaluateYqExpressionWithType[T any](atmosConfig *schema.AtmosConfiguration, data T, yq string) (*T, error)

func ExecuteShellAndReturnOutput added in v1.173.0

func ExecuteShellAndReturnOutput(
	command string,
	name string,
	dir string,
	env []string,
	dryRun bool,
) (string, error)

ExecuteShellAndReturnOutput runs a shell script and capture its standard output .

func ExtractAtmosConfig added in v1.148.0

func ExtractAtmosConfig(data any) schema.AtmosConfiguration

ExtractAtmosConfig extracts the Atmos configuration from any data type. It handles both direct AtmosConfiguration instances and pointers to AtmosConfiguration. If the data is neither, it returns an empty configuration.

func FileExists

func FileExists(filename string) bool

FileExists checks if the file exists and is not a directory

func FileOrDirExists added in v1.11.3

func FileOrDirExists(filename string) bool

FileOrDirExists checks if the file or directory exists

func GetAllFilesInDir added in v1.55.0

func GetAllFilesInDir(dir string) ([]string, error)

GetAllFilesInDir returns all files in the provided directory and all subdirectories

func GetAllYamlFilesInDir added in v1.55.0

func GetAllYamlFilesInDir(dir string) ([]string, error)

GetAllYamlFilesInDir returns all YAML files in the provided directory and all subdirectories

func GetAtmosConfigJSON added in v1.175.0

func GetAtmosConfigJSON(atmosConfig *schema.AtmosConfiguration) (string, error)

func GetFileNameFromURL added in v1.97.0

func GetFileNameFromURL(rawURL string) (string, error)

GetFileNameFromURL extracts the file name from a URL

func GetGlobMatches added in v1.4.21

func GetGlobMatches(pattern string) ([]string, error)

GetGlobMatches tries to read and return the Glob matches content from the sync map if it exists in the map, otherwise it finds and returns all files matching the pattern, stores the files in the map and returns the files

func GetHighlightSettings added in v1.148.0

func GetHighlightSettings(config *schema.AtmosConfiguration) *schema.SyntaxHighlighting

GetHighlightSettings returns the syntax highlighting settings from the config or defaults

func GetHighlightedJSON added in v1.176.0

func GetHighlightedJSON(atmosConfig *schema.AtmosConfiguration, data any) (string, error)

func GetHighlightedYAML added in v1.176.0

func GetHighlightedYAML(atmosConfig *schema.AtmosConfiguration, data any) (string, error)

func GetLatestGitHubRepoRelease added in v1.60.0

func GetLatestGitHubRepoRelease(owner string, repo string) (string, error)

GetLatestGitHubRepoRelease returns the latest release tag for a GitHub repository.

func GetLineEnding added in v1.155.0

func GetLineEnding() string

GetLineEnding returns the appropriate line ending for the current platform

func GetNextShellLevel added in v1.173.0

func GetNextShellLevel() (int, error)

GetNextShellLevel increments the ATMOS_SHLVL and returns the new value or an error if maximum depth is exceeded .

func HighlightCode added in v1.148.0

func HighlightCode(code string, lexerName string, theme string) (string, error)

HighlightCode highlights the given code using chroma with the specified lexer and theme

func HighlightCodeWithConfig added in v1.148.0

func HighlightCodeWithConfig(config *schema.AtmosConfiguration, code string, format ...string) (string, error)

HighlightCodeWithConfig highlights the given code using the provided configuration.

func InitializeMarkdown added in v1.162.0

func InitializeMarkdown(atmosConfig schema.AtmosConfiguration)

InitializeMarkdown initializes a new Markdown renderer.

func IsDirectory

func IsDirectory(path string) (bool, error)

IsDirectory checks if the path is a directory

func IsPathAbsolute added in v1.4.0

func IsPathAbsolute(path string) bool

IsPathAbsolute checks if the provided file path is absolute

func IsSocket added in v1.83.1

func IsSocket(path string) (bool, error)

IsSocket checks if a file is a socket

func IsURL added in v1.97.0

func IsURL(s string) bool

IsURL checks if a string is a URL

func IsValidScheme added in v1.169.0

func IsValidScheme(scheme string) bool

IsValidScheme checks if the URL scheme is valid.

func IsYaml

func IsYaml(file string) bool

IsYaml checks if the file has YAML extension (does not check file schema, nor validates the file)

func JSONToMapOfInterfaces added in v1.88.0

func JSONToMapOfInterfaces(input string) (schema.AtmosSectionMapType, error)

JSONToMapOfInterfaces takes a JSON string as input and returns a map[string]any

func JoinAbsolutePathWithPath added in v1.4.27

func JoinAbsolutePathWithPath(basePath string, providedPath string) (string, error)

JoinAbsolutePathWithPath checks if the provided path is absolute. If the provided path is relative, it joins the base path with the path and returns the absolute path

func JoinAbsolutePathWithPaths

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

JoinAbsolutePathWithPaths joins a base path with each item in the path slice and returns a slice of absolute paths

func MapKeyExists added in v1.4.1

func MapKeyExists(m map[string]any, key string) bool

MapKeyExists checks if a key already defined in a map

func MapOfInterfaceKeysToMapOfStringKeys added in v1.160.3

func MapOfInterfaceKeysToMapOfStringKeys(input map[any]any) map[string]any

MapOfInterfaceKeysToMapOfStringKeys converts map[any]any to map[string]any

func MapOfInterfacesToMapOfStrings added in v1.111.0

func MapOfInterfacesToMapOfStrings(input map[string]any) map[string]string

MapOfInterfacesToMapOfStrings converts map[string]any to map[string]string

func MatchWildcard added in v1.170.0

func MatchWildcard(pattern, str string) (bool, error)

MatchWildcard checks if a string matches a wildcard pattern. The pattern can include glob patterns: - '*' matches any sequence of non-separator characters. - '?' matches any single non-separator character. - '[abc]' matches any character within the brackets. - '[a-z]' matches any character in the range. - '**' matches any number of directories or files recursively. - '{abc,xyz}` matches the string "abc" or "xyz".

func PathMatch added in v1.4.21

func PathMatch(pattern, name string) (bool, error)

PathMatch returns true if `name` matches the file name `pattern`. PathMatch will automatically use your system's path separator to split `name` and `pattern`. On systems where the path separator is `'\'`, escaping will be disabled.

Note: this is meant as a drop-in replacement for filepath.Match(). It assumes that both `pattern` and `name` are using the system's path separator. If you can't be sure of that, use filepath.ToSlash() on both `pattern` and `name`, and then use the Match() function instead.

func PrintAsHcl added in v1.6.0

func PrintAsHcl(data any) error

PrintAsHcl prints the provided value as HCL (HashiCorp Language) document to the console

func PrintAsJSON

func PrintAsJSON(atmosConfig *schema.AtmosConfiguration, data any) error

PrintAsJSON prints the provided value as a JSON document to the console.

func PrintAsJSONToFileDescriptor added in v1.74.0

func PrintAsJSONToFileDescriptor(atmosConfig schema.AtmosConfiguration, data any) error

PrintAsJSONToFileDescriptor prints the provided value as JSON document to a file descriptor

func PrintAsYAML

func PrintAsYAML(atmosConfig *schema.AtmosConfiguration, data any) error

PrintAsYAML prints the provided value as YAML document to the console

func PrintAsYAMLToFileDescriptor added in v1.74.0

func PrintAsYAMLToFileDescriptor(atmosConfig *schema.AtmosConfiguration, data any) error

PrintAsYAMLToFileDescriptor prints the provided value as YAML document to a file descriptor

func PrintAsYAMLWithConfig added in v1.176.0

func PrintAsYAMLWithConfig(atmosConfig *schema.AtmosConfiguration, data any) error

func PrintMessage added in v1.5.0

func PrintMessage(message string)

PrintMessage prints the message to the console

func PrintMessageInColor added in v1.54.0

func PrintMessageInColor(message string, messageColor *color.Color)

PrintMessageInColor prints the message to the console using the provided color

func PrintMessageToUpgradeToAtmosLatestRelease added in v1.119.0

func PrintMessageToUpgradeToAtmosLatestRelease(latestVersion string)

PrintMessageToUpgradeToAtmosLatestRelease prints info on how to upgrade Atmos to the latest version

func PrintfMarkdown added in v1.162.0

func PrintfMarkdown(format string, a ...interface{})

PrintfMarkdown prints a message in Markdown format.

func PrintfMessageToTUI added in v1.166.0

func PrintfMessageToTUI(message string, args ...any)

PrintfMessageToTUI prints the message to the stderr.

func ProcessTagEnv added in v1.173.0

func ProcessTagEnv(
	input string,
) (string, error)

func ProcessTagExec added in v1.173.0

func ProcessTagExec(
	input string,
) (any, error)

func ProcessTagGitRoot added in v1.173.0

func ProcessTagGitRoot(input string) (string, error)

GetGitRoot returns the root directory of the Git repository using go-git.

func ResolveRelativePath added in v1.153.0

func ResolveRelativePath(path string, basePath string) string

ResolveRelativePath checks if a path is relative to the current directory and if so, resolves it relative to the current file's directory. It ensures the resolved path exists within the base path.

func SearchConfigFile added in v1.94.0

func SearchConfigFile(path string) (string, bool)

SearchConfigFile searches for a config file in the provided path. If the path has a file extension, it checks if the file exists. If the path does not have a file extension, it checks for the existence of the file with the provided path and the possible config file extensions

func ShellRunner added in v1.173.0

func ShellRunner(command string, name string, dir string, env []string, out io.Writer) error

ShellRunner uses mvdan.cc/sh/v3's parser and interpreter to run a shell script and divert its stdout .

func SliceContainsInt

func SliceContainsInt(s []int, i int) bool

SliceContainsInt checks if an int is present in a slice

func SliceContainsString

func SliceContainsString(s []string, str string) bool

SliceContainsString checks if a string is present in a slice

func SliceContainsStringHasPrefix added in v1.23.0

func SliceContainsStringHasPrefix(s []string, prefix string) bool

SliceContainsStringHasPrefix checks if a slice contains a string that begins with the given prefix

func SliceContainsStringStartsWith

func SliceContainsStringStartsWith(s []string, str string) bool

SliceContainsStringStartsWith checks if a slice contains a string that the given string begins with

func SliceOfInterfacesToSliceOdStrings added in v1.9.0

func SliceOfInterfacesToSliceOdStrings(input []any) []string

SliceOfInterfacesToSliceOdStrings converts a slice of any to a slice os strings

func SliceOfInterfacesToSliceOfStrings added in v1.88.0

func SliceOfInterfacesToSliceOfStrings(input []any) ([]string, error)

SliceOfInterfacesToSliceOfStrings takes a slice of interfaces and converts it to a slice of strings

func SliceOfPathsContainsPath added in v1.17.0

func SliceOfPathsContainsPath(paths []string, checkPath string) bool

SliceOfPathsContainsPath checks if a slice of file paths contains a path

func SliceOfStringsToSpaceSeparatedString

func SliceOfStringsToSpaceSeparatedString(s []string) string

SliceOfStringsToSpaceSeparatedString checks if an int is present in a slice

func SortMapByKeysAndValuesUniq added in v1.54.0

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

SortMapByKeysAndValuesUniq sorts the provided map by the keys, sorts the map values (lists of strings), and makes the values unique

func SplitStringAtFirstOccurrence added in v1.160.4

func SplitStringAtFirstOccurrence(s string, sep string) [2]string

SplitStringAtFirstOccurrence splits a string into two parts at the first occurrence of the separator

func SplitStringByDelimiter added in v1.153.0

func SplitStringByDelimiter(str string, delimiter rune) ([]string, error)

SplitStringByDelimiter splits a string by the delimiter, not splitting inside quotes.

func StringKeysFromMap

func StringKeysFromMap(m map[string]any) []string

StringKeysFromMap returns a slice of sorted string keys from the provided map

func TrimBasePathFromPath

func TrimBasePathFromPath(basePath string, path string) string

TrimBasePathFromPath trims the base path prefix from the path

func UniqueStrings

func UniqueStrings(input []string) []string

UniqueStrings returns a unique subset of the string slice provided

func UnmarshalYAML added in v1.88.0

func UnmarshalYAML[T any](input string) (T, error)

UnmarshalYAML unmarshals YAML into a Go type.

func UnmarshalYAMLFromFile added in v1.153.0

func UnmarshalYAMLFromFile[T any](atmosConfig *schema.AtmosConfiguration, input string, file string) (T, error)

UnmarshalYAMLFromFile unmarshals YAML downloaded from a file into a Go type.

func ValidateURI added in v1.169.0

func ValidateURI(uri string) error

ValidateURI validates URIs.

func WriteTerraformBackendConfigToFileAsHcl added in v1.7.0

func WriteTerraformBackendConfigToFileAsHcl(
	filePath string,
	backendType string,
	backendConfig map[string]any,
) error

WriteTerraformBackendConfigToFileAsHcl writes the provided Terraform backend config to the specified file https://dev.to/pdcommunity/write-terraform-files-in-go-with-hclwrite-2e1j https://pkg.go.dev/github.com/hashicorp/hcl/v2/hclwrite

func WriteToFileAsHcl added in v1.6.0

func WriteToFileAsHcl(
	filePath string,
	data any,
	fileMode os.FileMode,
) error

WriteToFileAsHcl converts the provided value to HCL (HashiCorp Language) and writes it to the specified file

func WriteToFileAsJSON

func WriteToFileAsJSON(filePath string, data any, fileMode os.FileMode) error

WriteToFileAsJSON converts the provided value to JSON and writes it to the specified file

func WriteToFileAsYAML

func WriteToFileAsYAML(filePath string, data any, fileMode os.FileMode) error

WriteToFileAsYAML converts the provided value to YAML and writes it to the specified file

func WriteToFileAsYAMLWithConfig added in v1.176.0

func WriteToFileAsYAMLWithConfig(atmosConfig *schema.AtmosConfiguration, filePath string, data any, fileMode os.FileMode) error

Types

type HighlightWriter added in v1.148.0

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

HighlightWriter returns an io.Writer that highlights code written to it

func NewHighlightWriter added in v1.148.0

func NewHighlightWriter(w io.Writer, config schema.AtmosConfiguration, format ...string) *HighlightWriter

NewHighlightWriter creates a new HighlightWriter

func (*HighlightWriter) Write added in v1.148.0

func (h *HighlightWriter) Write(p []byte) (n int, err error)

Write implements io.Writer The returned byte count n is the length of p regardless of whether the highlighting process changes the actual number of bytes written to the underlying writer. This maintains compatibility with the io.Writer interface contract while still providing syntax highlighting functionality.

type YAMLOptions added in v1.176.0

type YAMLOptions struct {
	Indent int
}

Jump to

Keyboard shortcuts

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