utils

package
v1.202.1 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: Apache-2.0 Imports: 60 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"
	AtmosYamlFuncIncludeRaw              = "!include.raw"
	AtmosYamlFuncGitRoot                 = "!repo-root"
	AtmosYamlFuncCwd                     = "!cwd"
	AtmosYamlFuncRandom                  = "!random"
	AtmosYamlFuncLiteral                 = "!literal"
	AtmosYamlFuncAwsAccountID            = "!aws.account_id"
	AtmosYamlFuncAwsCallerIdentityArn    = "!aws.caller_identity_arn"
	AtmosYamlFuncAwsCallerIdentityUserID = "!aws.caller_identity_user_id"
	AtmosYamlFuncAwsRegion               = "!aws.region"

	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
View Source
const (
	// Newline is the newline character constant.
	Newline = "\n"
)

Variables

View Source
var (
	ErrURIEmpty                      = errors.New("URI cannot be empty")
	ErrURIExceedsMaxLength           = errors.New("URI exceeds maximum length of 2048 characters")
	ErrURICannotContainPathTraversal = errors.New("URI cannot contain path traversal sequences")
	ErrURICannotContainSpaces        = errors.New("URI cannot contain spaces")
	ErrUnsupportedURIScheme          = errors.New("unsupported URI scheme")
	ErrInvalidOCIURIFormat           = errors.New("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,
		AtmosYamlFuncCwd,
		AtmosYamlFuncRandom,
		AtmosYamlFuncLiteral,
		AtmosYamlFuncAwsAccountID,
		AtmosYamlFuncAwsCallerIdentityArn,
		AtmosYamlFuncAwsCallerIdentityUserID,
		AtmosYamlFuncAwsRegion,
	}

	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 = errors.New("invalid Atmos YAML function")
View Source
var (
	ErrUnknownComponentType = errors.New("unknown component type")
)

Static errors for component path resolution.

View Source
var OsExit = os.Exit

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

Functions

func AppendJSONPathIndex added in v1.194.0

func AppendJSONPathIndex(basePath string, index int) string

AppendJSONPathIndex appends an array index to an existing JSONPath. Examples:

AppendJSONPathIndex("vars.zones", 0) -> "vars.zones[0]"
AppendJSONPathIndex("", 0) -> "[0]"

func AppendJSONPathKey added in v1.194.0

func AppendJSONPathKey(basePath, key string) string

AppendJSONPathKey appends a key to an existing JSONPath. Examples:

AppendJSONPathKey("vars", "name") -> "vars.name"
AppendJSONPathKey("", "vars") -> "vars"

func BuildJSONPath added in v1.194.0

func BuildJSONPath(components ...string) string

BuildJSONPath constructs a JSONPath-style path from components. Examples:

BuildJSONPath("vars", "name") -> "vars.name"
BuildJSONPath("vars", "tags", "environment") -> "vars.tags.environment"
BuildJSONPath("import", "[0]") -> "import[0]"

func CleanDuplicatedPath added in v1.201.0

func CleanDuplicatedPath(path string) string

CleanDuplicatedPath removes duplicate path segments that sometimes occur due to symlink resolution or path joining issues. For example: /foo/bar/foo/bar/baz becomes /foo/bar/baz.

func ClearInternPool added in v1.195.0

func ClearInternPool()

ClearInternPool clears the intern pool. Should only be used in tests.

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 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 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 FormatList added in v1.202.0

func FormatList(items []string) string

FormatList formats a list of strings into a markdown bullet list. Each item is formatted as a backtick-quoted bullet point.

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 GetComponentBasePath added in v1.192.0

func GetComponentBasePath(atmosConfig *schema.AtmosConfiguration, componentType string) (string, error)

GetComponentBasePath returns just the base path for a component type. Useful when you need the base directory without a specific component.

func GetComponentPath added in v1.192.0

func GetComponentPath(atmosConfig *schema.AtmosConfiguration, componentType string, componentFolderPrefix string, component string) (string, error)

GetComponentPath returns the absolute path to a component, respecting all configuration and overrides. Priority order: 1. Environment variables (if set, these completely override config) 2. Already-resolved absolute paths in atmosConfig 3. Constructed from BasePath + configured component paths

This function makes NO assumptions about directory names - it only uses what's configured.

func GetFileNameFromURL added in v1.97.0

func GetFileNameFromURL(rawURL string) (string, error)

GetFileNameFromURL extracts the file name from a URL.

func GetGitHubLatestRelease added in v1.195.0

func GetGitHubLatestRelease(owner, repo string) (*github.RepositoryRelease, error)

GetGitHubLatestRelease fetches the latest stable release from GitHub. Deprecated: Use github.GetLatestReleaseInfo instead.

func GetGitHubReleaseByTag added in v1.195.0

func GetGitHubReleaseByTag(owner, repo, tag string) (*github.RepositoryRelease, error)

GetGitHubReleaseByTag fetches a specific GitHub release by tag name. Deprecated: Use github.GetReleaseByTag instead.

func GetGitHubRepoReleases added in v1.195.0

func GetGitHubRepoReleases(opts GitHubReleasesOptions) ([]*github.RepositoryRelease, error)

GetGitHubRepoReleases fetches GitHub releases with pagination, prerelease filtering, and date filtering. Deprecated: Use github.GetReleases instead.

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 GetJSONPathLeaf added in v1.194.0

func GetJSONPathLeaf(path string) string

GetJSONPathLeaf returns the last component of a JSONPath. Examples:

GetJSONPathLeaf("vars.name") -> "name"
GetJSONPathLeaf("vars.zones[0]") -> "[0]"
GetJSONPathLeaf("vars") -> "vars"

func GetJSONPathParent added in v1.194.0

func GetJSONPathParent(path string) string

GetJSONPathParent returns the parent path of a JSONPath. Examples:

GetJSONPathParent("vars.name") -> "vars"
GetJSONPathParent("vars.zones[0]") -> "vars.zones"
GetJSONPathParent("vars") -> ""

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. Deprecated: Use github.GetLatestRelease instead.

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 GoToCty added in v1.198.0

func GoToCty(value any) cty.Value

GoToCty converts Go types to cty.Value recursively.

func HasYAMLPosition added in v1.194.0

func HasYAMLPosition(positions PositionMap, path string) bool

HasYAMLPosition checks if a position exists for a specific JSONPath.

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 Intern added in v1.195.0

func Intern(_ *schema.AtmosConfiguration, s string) string

Intern returns a canonical representation of the string. If the string already exists in the intern pool, returns the existing instance. Otherwise, adds the string to the pool and returns it. This reduces memory usage by deduplicating common strings across YAML files.

Common interned strings in Atmos:

  • YAML keys: "vars", "settings", "metadata", "env", "backend", "terraform", "helmfile".
  • Stack names, component names, file paths.
  • Common values: "true", "false", "default", region names.

Thread-safe for concurrent use. Note: perf.Track removed from this critical path function as it's called millions of times. Statistics use atomic operations instead of locks to avoid contention in the hot path.

func InternMapKeys added in v1.195.0

func InternMapKeys(atmosConfig *schema.AtmosConfiguration, m map[string]any) map[string]any

InternMapKeys interns all keys in a map. Returns a new map with interned keys and original values. Note: Values are not interned as they may be of various types. Note: perf.Track removed to avoid overhead on frequently-called function.

func InternSlice added in v1.195.0

func InternSlice(atmosConfig *schema.AtmosConfiguration, strings []string) []string

InternSlice interns all strings in a slice. Returns a new slice with interned strings. Note: perf.Track removed to avoid overhead on frequently-called function.

func InternStringsInMap added in v1.195.0

func InternStringsInMap(atmosConfig *schema.AtmosConfiguration, data any) any

InternStringsInMap recursively interns all string keys and string values in a map[string]any. This reduces memory usage by deduplicating common strings across YAML files. Common interned values: component names, stack names, "true"/"false", region names, etc. Note: perf.Track removed from this critical path function as it's called recursively many times.

func IsDirectory

func IsDirectory(path string) (bool, error)

IsDirectory checks if the path is a directory.

func IsJSONPathIndex added in v1.194.0

func IsJSONPathIndex(component string) bool

IsJSONPathIndex checks if a component is an array index. Examples:

IsJSONPathIndex("[0]") -> true
IsJSONPathIndex("name") -> false

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 IsTemplateFile added in v1.193.0

func IsTemplateFile(filePath string) bool

IsTemplateFile returns true if the file path has a .yaml.tmpl or .yml.tmpl extension.

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 JoinPath added in v1.193.0

func JoinPath(basePath string, providedPath string) string

JoinPath joins two paths handling absolute paths correctly. If the second path is absolute, it returns the second path. Otherwise, it joins the paths using filepath.Join which:

  • Normalizes path separators to the OS-specific separator
  • Cleans the resulting path (removes . and .. elements)
  • Handles empty paths appropriately

This function follows standard Go path behavior and does NOT check if the path exists on the filesystem.

func JoinPathAndValidate added in v1.193.0

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

JoinPathAndValidate joins paths and validates the result exists in filesystem. It builds on JoinPath for path construction and adds filesystem validation.

func JoinPaths added in v1.193.0

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

JoinPaths joins a base path with each item in the path slice and returns a slice of joined paths. This is a pure path construction function without filesystem validation.

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 OpenUrl added in v1.194.0

func OpenUrl(urlStr string) error

func ParseJSONPathIndex added in v1.194.0

func ParseJSONPathIndex(component string) (int, bool)

ParseJSONPathIndex extracts the index from an array index component. Examples:

ParseJSONPathIndex("[0]") -> 0, true
ParseJSONPathIndex("[42]") -> 42, true
ParseJSONPathIndex("name") -> 0, false

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 normalizes both pattern and name to use forward slashes for cross-platform compatibility, then uses doublestar.Match (not PathMatch) which expects Unix-style paths. This ensures patterns work consistently on Windows, Linux, and macOS.

Note: perf.Track() removed from this hot path to reduce overhead (called 2M+ times). Results are cached to avoid redundant pattern matching during affected detection.

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 with syntax highlighting. Use PrintAsJSONSimple for non-TTY output (pipes, redirects) to avoid expensive highlighting.

func PrintAsJSONSimple added in v1.195.0

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

PrintAsJSONSimple prints the provided value as JSON document without syntax highlighting. This is a fast-path for non-TTY output (files, pipes, redirects) that skips expensive syntax highlighting, reducing output time significantly for large configurations.

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 with syntax highlighting. Use PrintAsYAMLSimple for non-TTY output (pipes, redirects) to avoid expensive highlighting.

func PrintAsYAMLSimple added in v1.195.0

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

PrintAsYAMLSimple prints the provided value as YAML document without syntax highlighting. This is a fast-path for non-TTY output (files, pipes, redirects) that skips expensive syntax highlighting, reducing output time from ~6s to <1s for large configurations.

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 PrintParsedYAMLCacheStats added in v1.195.0

func PrintParsedYAMLCacheStats()

PrintParsedYAMLCacheStats prints cache statistics for debugging. This helps identify cache effectiveness and opportunities for optimization.

func PrintfMarkdown added in v1.162.0

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

PrintfMarkdown prints a message in Markdown format.

func PrintfMarkdownToTUI added in v1.194.0

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

PrintfMarkdownToTUI prints a message in Markdown format to stderr. This is useful for notices, warnings, and other messages that should not interfere with stdout when piping command output.

func PrintfMessageToTUI added in v1.166.0

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

PrintfMessageToTUI prints the message to the stderr.

func ProcessIncludeRawTag added in v1.191.0

func ProcessIncludeRawTag(
	atmosConfig *schema.AtmosConfiguration,
	node *yaml.Node,
	val string,
	file string,
) error

ProcessIncludeRawTag processes the !include.raw tag. It always returns the file content as a raw string, regardless of extension.

func ProcessIncludeTag added in v1.191.0

func ProcessIncludeTag(
	atmosConfig *schema.AtmosConfiguration,
	node *yaml.Node,
	val string,
	file string,
) error

ProcessIncludeTag processes the !include tag with extension-based parsing. It parses files based on their extension, not their content.

func ProcessTagCwd added in v1.202.0

func ProcessTagCwd(input string) (string, error)

ProcessTagCwd returns the current working directory. If a path argument is provided after the tag, it is joined with CWD. Format: "!cwd" or "!cwd <path>".

func ProcessTagEnv added in v1.173.0

func ProcessTagEnv(
	input string,
	envContext EnvVarContext,
) (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)

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

func ProcessTagRandom added in v1.201.0

func ProcessTagRandom(input string) (int, error)

ProcessTagRandom processes the !random YAML function and returns a random integer within the specified range. Usage:

!random           - Generate random number between 0 and 65535
!random max       - Generate random number between 0 and max
!random min max   - Generate random number between min and max

Examples:

!random           -> random number 0-65535
!random 100       -> random number 0-100
!random 1024 65535 -> random number 1024-65535

func ResetInternStats added in v1.195.0

func ResetInternStats()

ResetInternStats resets interning statistics. Primarily for testing. Uses atomic stores for lock-free access.

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 SliceOfInterfacesToSliceOfStrings added in v1.88.0

func SliceOfInterfacesToSliceOfStrings(input []any) []string

SliceOfInterfacesToSliceOfStrings converts a slice of any to a slice of strings. Each element is converted to a string using fmt.Sprintf with the "%v" format.

func SliceOfInterfacesToSliceOfStringsWithTypeAssertion added in v1.192.0

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

SliceOfInterfacesToSliceOfStringsWithTypeAssertion takes a slice of interfaces and converts it to a slice of strings using type assertion. This function returns an error if any element is not a string.

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 joins a slice of strings into a single space-separated string.

func SliceRemoveFlag added in v1.192.0

func SliceRemoveFlag(slice []string, flagName string) []string

SliceRemoveFlag removes all occurrences of a flag from a slice, handling both "--flag" and "--flag=value" forms. This function safely handles multiple occurrences and returns a new slice with all flag instances removed. The function preserves the original slice and returns a new slice with the flags removed.

func SliceRemoveFlagAndValue added in v1.192.0

func SliceRemoveFlagAndValue(args []string, flagName string) []string

SliceRemoveFlagAndValue removes --flag and an optional following value (if the next arg does not start with "-"). It preserves order of remaining args.

func SliceRemoveString added in v1.192.0

func SliceRemoveString(slice []string, str string) []string

SliceRemoveString removes only the first occurrence of the provided string from a slice. This function may mutate the input slice's backing array (i.e., it is not a pure/non-mutating operation). Callers must use the returned slice (assign it) because the original slice may be modified or re-sliced. Advise callers to copy the slice before calling if they need to preserve the original contents.

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 SplitJSONPath added in v1.194.0

func SplitJSONPath(path string) []string

SplitJSONPath splits a JSONPath into its components. Examples:

SplitJSONPath("vars.name") -> ["vars", "name"]
SplitJSONPath("vars.zones[0]") -> ["vars", "zones", "[0]"]
SplitJSONPath("vars.tags.environment") -> ["vars", "tags", "environment"]

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 WrapLongStrings added in v1.194.0

func WrapLongStrings(data any, maxLength int) any

WrapLongStrings walks a data structure and converts strings longer than maxLength to LongString type, which will be encoded as YAML folded scalars (>) for better readability.

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 ComponentInfo added in v1.201.0

type ComponentInfo struct {
	ComponentType string // "terraform", "helmfile", "packer"
	FolderPrefix  string // "vpc", "networking/vpc", etc. (empty if component is at base)
	ComponentName string // "security-group", "vpc", etc.
	FullComponent string // Full component path as it appears in stack config (folder_prefix/component or just component)
}

ComponentInfo represents extracted component information from a filesystem path.

func ExtractComponentInfoFromPath added in v1.201.0

func ExtractComponentInfoFromPath(
	atmosConfig *schema.AtmosConfiguration,
	path string,
) (*ComponentInfo, error)

ExtractComponentInfoFromPath extracts component information from an absolute filesystem path. Returns error if path is not within configured component directories.

Examples:

  • /project/components/terraform/vpc/security-group → {terraform, vpc, security-group, vpc/security-group}
  • /project/components/terraform/vpc → {terraform, "", vpc, vpc}
  • /project/components/helmfile/app → {helmfile, "", app, app}

type EnvVarContext added in v1.199.0

type EnvVarContext interface {
	// GetComponentEnvSection returns the component's env section map, or nil if not available.
	GetComponentEnvSection() map[string]any
}

EnvVarContext provides context for environment variable lookup. It allows !env to check stack manifest env sections before falling back to OS environment.

type GitHubReleasesOptions added in v1.195.0

type GitHubReleasesOptions = gh.ReleasesOptions

GitHubReleasesOptions contains options for fetching GitHub releases. Deprecated: Use github.ReleasesOptions instead.

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 InternStats added in v1.195.0

type InternStats struct {
	Requests   int64 // Total intern requests.
	Hits       int64 // Cache hits (string already interned).
	Misses     int64 // Cache misses (new string added).
	SavedBytes int64 // Estimated memory saved (bytes).
}

InternStats represents string interning statistics.

func GetInternStats added in v1.195.0

func GetInternStats() InternStats

GetInternStats returns current interning statistics. Useful for debugging and performance analysis. Uses atomic loads for lock-free access.

type LongString added in v1.194.0

type LongString string

LongString is a string type that encodes as a YAML folded scalar (>). This is used to wrap long strings across multiple lines for better readability.

func (LongString) MarshalYAML added in v1.194.0

func (s LongString) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaler to encode as a folded scalar.

type Position added in v1.194.0

type Position struct {
	Line   int // 1-indexed line number.
	Column int // 1-indexed column number.
}

Position represents a line and column position in a YAML file.

func GetYAMLPosition added in v1.194.0

func GetYAMLPosition(positions PositionMap, path string) Position

GetYAMLPosition gets the position for a specific JSONPath from the position map. Returns Position{0, 0} if not found.

type PositionMap added in v1.194.0

type PositionMap map[string]Position

PositionMap maps JSONPath-style paths to their positions in a YAML file.

func ExtractYAMLPositions added in v1.194.0

func ExtractYAMLPositions(node *yaml.Node, enabled bool) PositionMap

ExtractYAMLPositions extracts line/column positions from a YAML node tree. Returns a map of JSONPath -> Position for all values in the YAML. If enabled is false, returns an empty map immediately (zero overhead).

func UnmarshalYAMLFromFileWithPositions added in v1.194.0

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

UnmarshalYAMLFromFileWithPositions unmarshals YAML and returns position information. The positions map contains line/column information for each value in the YAML. If atmosConfig.TrackProvenance is false, returns an empty position map. Uses caching with content-aware keys to correctly handle template-processed files. The cache key includes both file path and content hash, ensuring that: - Static files are cached by path (same content = cache hit) - Template files with same context get cache hits - Template files with different contexts get separate cache entries (correct behavior).

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